xref: /linux/arch/x86/kvm/x86.c (revision 51d90a15fedf8366cb96ef68d0ea2d0bf15417d2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/kvm_host.h>
21 #include "irq.h"
22 #include "ioapic.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
29 #include "x86.h"
30 #include "cpuid.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33 #include "lapic.h"
34 #include "xen.h"
35 #include "smm.h"
36 
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
40 #include <linux/fs.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/suspend.h>
63 #include <linux/smp.h>
64 
65 #include <trace/events/ipi.h>
66 #include <trace/events/kvm.h>
67 
68 #include <asm/debugreg.h>
69 #include <asm/msr.h>
70 #include <asm/desc.h>
71 #include <asm/mce.h>
72 #include <asm/pkru.h>
73 #include <linux/kernel_stat.h>
74 #include <asm/fpu/api.h>
75 #include <asm/fpu/xcr.h>
76 #include <asm/fpu/xstate.h>
77 #include <asm/pvclock.h>
78 #include <asm/div64.h>
79 #include <asm/irq_remapping.h>
80 #include <asm/mshyperv.h>
81 #include <asm/hypervisor.h>
82 #include <asm/tlbflush.h>
83 #include <asm/intel_pt.h>
84 #include <asm/emulate_prefix.h>
85 #include <asm/sgx.h>
86 #include <clocksource/hyperv_timer.h>
87 
88 #define CREATE_TRACE_POINTS
89 #include "trace.h"
90 
91 #define MAX_IO_MSRS 256
92 
93 /*
94  * Note, kvm_caps fields should *never* have default values, all fields must be
95  * recomputed from scratch during vendor module load, e.g. to account for a
96  * vendor module being reloaded with different module parameters.
97  */
98 struct kvm_caps kvm_caps __read_mostly;
99 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
100 
101 struct kvm_host_values kvm_host __read_mostly;
102 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
103 
104 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
105 
106 #define emul_to_vcpu(ctxt) \
107 	((struct kvm_vcpu *)(ctxt)->vcpu)
108 
109 /* EFER defaults:
110  * - enable syscall per default because its emulated by KVM
111  * - enable LME and LMA per default on 64 bit KVM
112  */
113 #ifdef CONFIG_X86_64
114 static
115 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
116 #else
117 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
118 #endif
119 
120 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
121 
122 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
123 
124 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
125                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
126 
127 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
128 static void process_nmi(struct kvm_vcpu *vcpu);
129 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
130 static void store_regs(struct kvm_vcpu *vcpu);
131 static int sync_regs(struct kvm_vcpu *vcpu);
132 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
133 
134 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
135 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136 
137 static DEFINE_MUTEX(vendor_module_lock);
138 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
139 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
140 
141 struct kvm_x86_ops kvm_x86_ops __read_mostly;
142 
143 #define KVM_X86_OP(func)					     \
144 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
145 				*(((struct kvm_x86_ops *)0)->func));
146 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
147 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
148 #include <asm/kvm-x86-ops.h>
149 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
150 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
151 
152 static bool __read_mostly ignore_msrs = 0;
153 module_param(ignore_msrs, bool, 0644);
154 
155 bool __read_mostly report_ignored_msrs = true;
156 module_param(report_ignored_msrs, bool, 0644);
157 EXPORT_SYMBOL_FOR_KVM_INTERNAL(report_ignored_msrs);
158 
159 unsigned int min_timer_period_us = 200;
160 module_param(min_timer_period_us, uint, 0644);
161 
162 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
163 static u32 __read_mostly tsc_tolerance_ppm = 250;
164 module_param(tsc_tolerance_ppm, uint, 0644);
165 
166 bool __read_mostly enable_vmware_backdoor = false;
167 module_param(enable_vmware_backdoor, bool, 0444);
168 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_vmware_backdoor);
169 
170 /*
171  * Flags to manipulate forced emulation behavior (any non-zero value will
172  * enable forced emulation).
173  */
174 #define KVM_FEP_CLEAR_RFLAGS_RF	BIT(1)
175 static int __read_mostly force_emulation_prefix;
176 module_param(force_emulation_prefix, int, 0644);
177 
178 int __read_mostly pi_inject_timer = -1;
179 module_param(pi_inject_timer, bint, 0644);
180 
181 /* Enable/disable PMU virtualization */
182 bool __read_mostly enable_pmu = true;
183 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_pmu);
184 module_param(enable_pmu, bool, 0444);
185 
186 bool __read_mostly eager_page_split = true;
187 module_param(eager_page_split, bool, 0644);
188 
189 /* Enable/disable SMT_RSB bug mitigation */
190 static bool __read_mostly mitigate_smt_rsb;
191 module_param(mitigate_smt_rsb, bool, 0444);
192 
193 /*
194  * Restoring the host value for MSRs that are only consumed when running in
195  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
196  * returns to userspace, i.e. the kernel can run with the guest's value.
197  */
198 #define KVM_MAX_NR_USER_RETURN_MSRS 16
199 
200 struct kvm_user_return_msrs {
201 	struct user_return_notifier urn;
202 	bool registered;
203 	struct kvm_user_return_msr_values {
204 		u64 host;
205 		u64 curr;
206 	} values[KVM_MAX_NR_USER_RETURN_MSRS];
207 };
208 
209 u32 __read_mostly kvm_nr_uret_msrs;
210 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_nr_uret_msrs);
211 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
212 static DEFINE_PER_CPU(struct kvm_user_return_msrs, user_return_msrs);
213 
214 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
215 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
216 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
217 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
218 
219 #define XFEATURE_MASK_CET_ALL	(XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
220 /*
221  * Note, KVM supports exposing PT to the guest, but does not support context
222  * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
223  * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
224  * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
225  */
226 #define KVM_SUPPORTED_XSS	(XFEATURE_MASK_CET_ALL)
227 
228 bool __read_mostly allow_smaller_maxphyaddr = 0;
229 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
230 
231 bool __read_mostly enable_apicv = true;
232 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
233 
234 bool __read_mostly enable_ipiv = true;
235 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
236 
237 bool __read_mostly enable_device_posted_irqs = true;
238 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
239 
240 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
241 	KVM_GENERIC_VM_STATS(),
242 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
243 	STATS_DESC_COUNTER(VM, mmu_pte_write),
244 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
245 	STATS_DESC_COUNTER(VM, mmu_flooded),
246 	STATS_DESC_COUNTER(VM, mmu_recycled),
247 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
248 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
249 	STATS_DESC_ICOUNTER(VM, pages_4k),
250 	STATS_DESC_ICOUNTER(VM, pages_2m),
251 	STATS_DESC_ICOUNTER(VM, pages_1g),
252 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
253 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
254 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
255 };
256 
257 const struct kvm_stats_header kvm_vm_stats_header = {
258 	.name_size = KVM_STATS_NAME_SIZE,
259 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
260 	.id_offset = sizeof(struct kvm_stats_header),
261 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
262 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
263 		       sizeof(kvm_vm_stats_desc),
264 };
265 
266 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
267 	KVM_GENERIC_VCPU_STATS(),
268 	STATS_DESC_COUNTER(VCPU, pf_taken),
269 	STATS_DESC_COUNTER(VCPU, pf_fixed),
270 	STATS_DESC_COUNTER(VCPU, pf_emulate),
271 	STATS_DESC_COUNTER(VCPU, pf_spurious),
272 	STATS_DESC_COUNTER(VCPU, pf_fast),
273 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
274 	STATS_DESC_COUNTER(VCPU, pf_guest),
275 	STATS_DESC_COUNTER(VCPU, tlb_flush),
276 	STATS_DESC_COUNTER(VCPU, invlpg),
277 	STATS_DESC_COUNTER(VCPU, exits),
278 	STATS_DESC_COUNTER(VCPU, io_exits),
279 	STATS_DESC_COUNTER(VCPU, mmio_exits),
280 	STATS_DESC_COUNTER(VCPU, signal_exits),
281 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
282 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
283 	STATS_DESC_COUNTER(VCPU, l1d_flush),
284 	STATS_DESC_COUNTER(VCPU, halt_exits),
285 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
286 	STATS_DESC_COUNTER(VCPU, irq_exits),
287 	STATS_DESC_COUNTER(VCPU, host_state_reload),
288 	STATS_DESC_COUNTER(VCPU, fpu_reload),
289 	STATS_DESC_COUNTER(VCPU, insn_emulation),
290 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
291 	STATS_DESC_COUNTER(VCPU, hypercalls),
292 	STATS_DESC_COUNTER(VCPU, irq_injections),
293 	STATS_DESC_COUNTER(VCPU, nmi_injections),
294 	STATS_DESC_COUNTER(VCPU, req_event),
295 	STATS_DESC_COUNTER(VCPU, nested_run),
296 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
297 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
298 	STATS_DESC_COUNTER(VCPU, preemption_reported),
299 	STATS_DESC_COUNTER(VCPU, preemption_other),
300 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
301 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
302 };
303 
304 const struct kvm_stats_header kvm_vcpu_stats_header = {
305 	.name_size = KVM_STATS_NAME_SIZE,
306 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
307 	.id_offset = sizeof(struct kvm_stats_header),
308 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
309 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
310 		       sizeof(kvm_vcpu_stats_desc),
311 };
312 
313 static struct kmem_cache *x86_emulator_cache;
314 
315 /*
316  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
317  * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
318  * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.  msrs_to_save holds MSRs that
319  * require host support, i.e. should be probed via RDMSR.  emulated_msrs holds
320  * MSRs that KVM emulates without strictly requiring host support.
321  * msr_based_features holds MSRs that enumerate features, i.e. are effectively
322  * CPUID leafs.  Note, msr_based_features isn't mutually exclusive with
323  * msrs_to_save and emulated_msrs.
324  */
325 
326 static const u32 msrs_to_save_base[] = {
327 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
328 	MSR_STAR,
329 #ifdef CONFIG_X86_64
330 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
331 #endif
332 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
333 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
334 	MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
335 	MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
336 	MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
337 	MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
338 	MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
339 	MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
340 	MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
341 	MSR_IA32_UMWAIT_CONTROL,
342 
343 	MSR_IA32_XFD, MSR_IA32_XFD_ERR, MSR_IA32_XSS,
344 
345 	MSR_IA32_U_CET, MSR_IA32_S_CET,
346 	MSR_IA32_PL0_SSP, MSR_IA32_PL1_SSP, MSR_IA32_PL2_SSP,
347 	MSR_IA32_PL3_SSP, MSR_IA32_INT_SSP_TAB,
348 };
349 
350 static const u32 msrs_to_save_pmu[] = {
351 	MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
352 	MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
353 	MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
354 	MSR_CORE_PERF_GLOBAL_CTRL,
355 	MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
356 
357 	/* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
358 	MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
359 	MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
360 	MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
361 	MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
362 	MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
363 	MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
364 	MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
365 	MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
366 
367 	MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
368 	MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
369 
370 	/* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
371 	MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
372 	MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
373 	MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
374 	MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
375 
376 	MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
377 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
378 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
379 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
380 };
381 
382 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
383 			ARRAY_SIZE(msrs_to_save_pmu)];
384 static unsigned num_msrs_to_save;
385 
386 static const u32 emulated_msrs_all[] = {
387 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
388 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
389 
390 #ifdef CONFIG_KVM_HYPERV
391 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
392 	HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
393 	HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
394 	HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
395 	HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
396 	HV_X64_MSR_RESET,
397 	HV_X64_MSR_VP_INDEX,
398 	HV_X64_MSR_VP_RUNTIME,
399 	HV_X64_MSR_SCONTROL,
400 	HV_X64_MSR_STIMER0_CONFIG,
401 	HV_X64_MSR_VP_ASSIST_PAGE,
402 	HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
403 	HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
404 	HV_X64_MSR_SYNDBG_OPTIONS,
405 	HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
406 	HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
407 	HV_X64_MSR_SYNDBG_PENDING_BUFFER,
408 #endif
409 
410 	MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
411 	MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
412 
413 	MSR_IA32_TSC_ADJUST,
414 	MSR_IA32_TSC_DEADLINE,
415 	MSR_IA32_ARCH_CAPABILITIES,
416 	MSR_IA32_PERF_CAPABILITIES,
417 	MSR_IA32_MISC_ENABLE,
418 	MSR_IA32_MCG_STATUS,
419 	MSR_IA32_MCG_CTL,
420 	MSR_IA32_MCG_EXT_CTL,
421 	MSR_IA32_SMBASE,
422 	MSR_SMI_COUNT,
423 	MSR_PLATFORM_INFO,
424 	MSR_MISC_FEATURES_ENABLES,
425 	MSR_AMD64_VIRT_SPEC_CTRL,
426 	MSR_AMD64_TSC_RATIO,
427 	MSR_IA32_POWER_CTL,
428 	MSR_IA32_UCODE_REV,
429 
430 	/*
431 	 * KVM always supports the "true" VMX control MSRs, even if the host
432 	 * does not.  The VMX MSRs as a whole are considered "emulated" as KVM
433 	 * doesn't strictly require them to exist in the host (ignoring that
434 	 * KVM would refuse to load in the first place if the core set of MSRs
435 	 * aren't supported).
436 	 */
437 	MSR_IA32_VMX_BASIC,
438 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
439 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
440 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
441 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
442 	MSR_IA32_VMX_MISC,
443 	MSR_IA32_VMX_CR0_FIXED0,
444 	MSR_IA32_VMX_CR4_FIXED0,
445 	MSR_IA32_VMX_VMCS_ENUM,
446 	MSR_IA32_VMX_PROCBASED_CTLS2,
447 	MSR_IA32_VMX_EPT_VPID_CAP,
448 	MSR_IA32_VMX_VMFUNC,
449 
450 	MSR_K7_HWCR,
451 	MSR_KVM_POLL_CONTROL,
452 };
453 
454 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
455 static unsigned num_emulated_msrs;
456 
457 /*
458  * List of MSRs that control the existence of MSR-based features, i.e. MSRs
459  * that are effectively CPUID leafs.  VMX MSRs are also included in the set of
460  * feature MSRs, but are handled separately to allow expedited lookups.
461  */
462 static const u32 msr_based_features_all_except_vmx[] = {
463 	MSR_AMD64_DE_CFG,
464 	MSR_IA32_UCODE_REV,
465 	MSR_IA32_ARCH_CAPABILITIES,
466 	MSR_IA32_PERF_CAPABILITIES,
467 	MSR_PLATFORM_INFO,
468 };
469 
470 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
471 			      (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
472 static unsigned int num_msr_based_features;
473 
474 /*
475  * All feature MSRs except uCode revID, which tracks the currently loaded uCode
476  * patch, are immutable once the vCPU model is defined.
477  */
kvm_is_immutable_feature_msr(u32 msr)478 static bool kvm_is_immutable_feature_msr(u32 msr)
479 {
480 	int i;
481 
482 	if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
483 		return true;
484 
485 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
486 		if (msr == msr_based_features_all_except_vmx[i])
487 			return msr != MSR_IA32_UCODE_REV;
488 	}
489 
490 	return false;
491 }
492 
kvm_is_advertised_msr(u32 msr_index)493 static bool kvm_is_advertised_msr(u32 msr_index)
494 {
495 	unsigned int i;
496 
497 	for (i = 0; i < num_msrs_to_save; i++) {
498 		if (msrs_to_save[i] == msr_index)
499 			return true;
500 	}
501 
502 	for (i = 0; i < num_emulated_msrs; i++) {
503 		if (emulated_msrs[i] == msr_index)
504 			return true;
505 	}
506 
507 	return false;
508 }
509 
510 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
511 			    bool host_initiated);
512 
kvm_do_msr_access(struct kvm_vcpu * vcpu,u32 msr,u64 * data,bool host_initiated,enum kvm_msr_access rw,msr_access_t msr_access_fn)513 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
514 					     u64 *data, bool host_initiated,
515 					     enum kvm_msr_access rw,
516 					     msr_access_t msr_access_fn)
517 {
518 	const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
519 	int ret;
520 
521 	BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
522 
523 	/*
524 	 * Zero the data on read failures to avoid leaking stack data to the
525 	 * guest and/or userspace, e.g. if the failure is ignored below.
526 	 */
527 	ret = msr_access_fn(vcpu, msr, data, host_initiated);
528 	if (ret && rw == MSR_TYPE_R)
529 		*data = 0;
530 
531 	if (ret != KVM_MSR_RET_UNSUPPORTED)
532 		return ret;
533 
534 	/*
535 	 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
536 	 * advertises to userspace, even if an MSR isn't fully supported.
537 	 * Simply check that @data is '0', which covers both the write '0' case
538 	 * and all reads (in which case @data is zeroed on failure; see above).
539 	 */
540 	if (host_initiated && !*data && kvm_is_advertised_msr(msr))
541 		return 0;
542 
543 	if (!ignore_msrs) {
544 		kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
545 				      op, msr, *data);
546 		return ret;
547 	}
548 
549 	if (report_ignored_msrs)
550 		kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
551 
552 	return 0;
553 }
554 
kvm_alloc_emulator_cache(void)555 static struct kmem_cache *kvm_alloc_emulator_cache(void)
556 {
557 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
558 	unsigned int size = sizeof(struct x86_emulate_ctxt);
559 
560 	return kmem_cache_create_usercopy("x86_emulator", size,
561 					  __alignof__(struct x86_emulate_ctxt),
562 					  SLAB_ACCOUNT, useroffset,
563 					  size - useroffset, NULL);
564 }
565 
566 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
567 
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)568 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
569 {
570 	int i;
571 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
572 		vcpu->arch.apf.gfns[i] = ~0;
573 }
574 
kvm_destroy_user_return_msrs(void)575 static void kvm_destroy_user_return_msrs(void)
576 {
577 	int cpu;
578 
579 	for_each_possible_cpu(cpu)
580 		WARN_ON_ONCE(per_cpu(user_return_msrs, cpu).registered);
581 
582 	kvm_nr_uret_msrs = 0;
583 }
584 
kvm_on_user_return(struct user_return_notifier * urn)585 static void kvm_on_user_return(struct user_return_notifier *urn)
586 {
587 	unsigned slot;
588 	struct kvm_user_return_msrs *msrs
589 		= container_of(urn, struct kvm_user_return_msrs, urn);
590 	struct kvm_user_return_msr_values *values;
591 
592 	msrs->registered = false;
593 	user_return_notifier_unregister(urn);
594 
595 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
596 		values = &msrs->values[slot];
597 		if (values->host != values->curr) {
598 			wrmsrq(kvm_uret_msrs_list[slot], values->host);
599 			values->curr = values->host;
600 		}
601 	}
602 }
603 
kvm_probe_user_return_msr(u32 msr)604 static int kvm_probe_user_return_msr(u32 msr)
605 {
606 	u64 val;
607 	int ret;
608 
609 	preempt_disable();
610 	ret = rdmsrq_safe(msr, &val);
611 	if (ret)
612 		goto out;
613 	ret = wrmsrq_safe(msr, val);
614 out:
615 	preempt_enable();
616 	return ret;
617 }
618 
kvm_add_user_return_msr(u32 msr)619 int kvm_add_user_return_msr(u32 msr)
620 {
621 	BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
622 
623 	if (kvm_probe_user_return_msr(msr))
624 		return -1;
625 
626 	kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
627 	return kvm_nr_uret_msrs++;
628 }
629 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_add_user_return_msr);
630 
kvm_find_user_return_msr(u32 msr)631 int kvm_find_user_return_msr(u32 msr)
632 {
633 	int i;
634 
635 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
636 		if (kvm_uret_msrs_list[i] == msr)
637 			return i;
638 	}
639 	return -1;
640 }
641 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_user_return_msr);
642 
kvm_user_return_msr_cpu_online(void)643 static void kvm_user_return_msr_cpu_online(void)
644 {
645 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
646 	u64 value;
647 	int i;
648 
649 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
650 		rdmsrq_safe(kvm_uret_msrs_list[i], &value);
651 		msrs->values[i].host = value;
652 		msrs->values[i].curr = value;
653 	}
654 }
655 
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)656 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
657 {
658 	if (!msrs->registered) {
659 		msrs->urn.on_user_return = kvm_on_user_return;
660 		user_return_notifier_register(&msrs->urn);
661 		msrs->registered = true;
662 	}
663 }
664 
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)665 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
666 {
667 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
668 	int err;
669 
670 	value = (value & mask) | (msrs->values[slot].host & ~mask);
671 	if (value == msrs->values[slot].curr)
672 		return 0;
673 	err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
674 	if (err)
675 		return 1;
676 
677 	msrs->values[slot].curr = value;
678 	kvm_user_return_register_notifier(msrs);
679 	return 0;
680 }
681 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_user_return_msr);
682 
kvm_get_user_return_msr(unsigned int slot)683 u64 kvm_get_user_return_msr(unsigned int slot)
684 {
685 	return this_cpu_ptr(&user_return_msrs)->values[slot].curr;
686 }
687 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_user_return_msr);
688 
drop_user_return_notifiers(void)689 static void drop_user_return_notifiers(void)
690 {
691 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
692 
693 	if (msrs->registered)
694 		kvm_on_user_return(&msrs->urn);
695 }
696 
697 /*
698  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
699  *
700  * Hardware virtualization extension instructions may fault if a reboot turns
701  * off virtualization while processes are running.  Usually after catching the
702  * fault we just panic; during reboot instead the instruction is ignored.
703  */
kvm_spurious_fault(void)704 noinstr void kvm_spurious_fault(void)
705 {
706 	/* Fault while not rebooting.  We want the trace. */
707 	BUG_ON(!kvm_rebooting);
708 }
709 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spurious_fault);
710 
711 #define EXCPT_BENIGN		0
712 #define EXCPT_CONTRIBUTORY	1
713 #define EXCPT_PF		2
714 
exception_class(int vector)715 static int exception_class(int vector)
716 {
717 	switch (vector) {
718 	case PF_VECTOR:
719 		return EXCPT_PF;
720 	case DE_VECTOR:
721 	case TS_VECTOR:
722 	case NP_VECTOR:
723 	case SS_VECTOR:
724 	case GP_VECTOR:
725 		return EXCPT_CONTRIBUTORY;
726 	default:
727 		break;
728 	}
729 	return EXCPT_BENIGN;
730 }
731 
732 #define EXCPT_FAULT		0
733 #define EXCPT_TRAP		1
734 #define EXCPT_ABORT		2
735 #define EXCPT_INTERRUPT		3
736 #define EXCPT_DB		4
737 
exception_type(int vector)738 static int exception_type(int vector)
739 {
740 	unsigned int mask;
741 
742 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
743 		return EXCPT_INTERRUPT;
744 
745 	mask = 1 << vector;
746 
747 	/*
748 	 * #DBs can be trap-like or fault-like, the caller must check other CPU
749 	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
750 	 */
751 	if (mask & (1 << DB_VECTOR))
752 		return EXCPT_DB;
753 
754 	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
755 		return EXCPT_TRAP;
756 
757 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
758 		return EXCPT_ABORT;
759 
760 	/* Reserved exceptions will result in fault */
761 	return EXCPT_FAULT;
762 }
763 
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)764 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
765 				   struct kvm_queued_exception *ex)
766 {
767 	if (!ex->has_payload)
768 		return;
769 
770 	switch (ex->vector) {
771 	case DB_VECTOR:
772 		/*
773 		 * "Certain debug exceptions may clear bit 0-3.  The
774 		 * remaining contents of the DR6 register are never
775 		 * cleared by the processor".
776 		 */
777 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
778 		/*
779 		 * In order to reflect the #DB exception payload in guest
780 		 * dr6, three components need to be considered: active low
781 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
782 		 * DR6_BS and DR6_BT)
783 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
784 		 * In the target guest dr6:
785 		 * FIXED_1 bits should always be set.
786 		 * Active low bits should be cleared if 1-setting in payload.
787 		 * Active high bits should be set if 1-setting in payload.
788 		 *
789 		 * Note, the payload is compatible with the pending debug
790 		 * exceptions/exit qualification under VMX, that active_low bits
791 		 * are active high in payload.
792 		 * So they need to be flipped for DR6.
793 		 */
794 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
795 		vcpu->arch.dr6 |= ex->payload;
796 		vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
797 
798 		/*
799 		 * The #DB payload is defined as compatible with the 'pending
800 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
801 		 * defined in the 'pending debug exceptions' field (enabled
802 		 * breakpoint), it is reserved and must be zero in DR6.
803 		 */
804 		vcpu->arch.dr6 &= ~BIT(12);
805 		break;
806 	case PF_VECTOR:
807 		vcpu->arch.cr2 = ex->payload;
808 		break;
809 	}
810 
811 	ex->has_payload = false;
812 	ex->payload = 0;
813 }
814 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_deliver_exception_payload);
815 
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)816 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
817 				       bool has_error_code, u32 error_code,
818 				       bool has_payload, unsigned long payload)
819 {
820 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
821 
822 	ex->vector = vector;
823 	ex->injected = false;
824 	ex->pending = true;
825 	ex->has_error_code = has_error_code;
826 	ex->error_code = error_code;
827 	ex->has_payload = has_payload;
828 	ex->payload = payload;
829 }
830 
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)831 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
832 				   bool has_error, u32 error_code,
833 				   bool has_payload, unsigned long payload)
834 {
835 	u32 prev_nr;
836 	int class1, class2;
837 
838 	kvm_make_request(KVM_REQ_EVENT, vcpu);
839 
840 	/*
841 	 * If the exception is destined for L2, morph it to a VM-Exit if L1
842 	 * wants to intercept the exception.
843 	 */
844 	if (is_guest_mode(vcpu) &&
845 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
846 		kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
847 					   has_payload, payload);
848 		return;
849 	}
850 
851 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
852 	queue:
853 		vcpu->arch.exception.pending = true;
854 		vcpu->arch.exception.injected = false;
855 
856 		vcpu->arch.exception.has_error_code = has_error;
857 		vcpu->arch.exception.vector = nr;
858 		vcpu->arch.exception.error_code = error_code;
859 		vcpu->arch.exception.has_payload = has_payload;
860 		vcpu->arch.exception.payload = payload;
861 		if (!is_guest_mode(vcpu))
862 			kvm_deliver_exception_payload(vcpu,
863 						      &vcpu->arch.exception);
864 		return;
865 	}
866 
867 	/* to check exception */
868 	prev_nr = vcpu->arch.exception.vector;
869 	if (prev_nr == DF_VECTOR) {
870 		/* triple fault -> shutdown */
871 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
872 		return;
873 	}
874 	class1 = exception_class(prev_nr);
875 	class2 = exception_class(nr);
876 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
877 	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
878 		/*
879 		 * Synthesize #DF.  Clear the previously injected or pending
880 		 * exception so as not to incorrectly trigger shutdown.
881 		 */
882 		vcpu->arch.exception.injected = false;
883 		vcpu->arch.exception.pending = false;
884 
885 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
886 	} else {
887 		/* replace previous exception with a new one in a hope
888 		   that instruction re-execution will regenerate lost
889 		   exception */
890 		goto queue;
891 	}
892 }
893 
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)894 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
895 {
896 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
897 }
898 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
899 
900 
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)901 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
902 			   unsigned long payload)
903 {
904 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
905 }
906 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
907 
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)908 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
909 				    u32 error_code, unsigned long payload)
910 {
911 	kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
912 }
913 
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)914 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
915 			   bool has_error_code, u32 error_code)
916 {
917 
918 	/*
919 	 * On VM-Entry, an exception can be pending if and only if event
920 	 * injection was blocked by nested_run_pending.  In that case, however,
921 	 * vcpu_enter_guest() requests an immediate exit, and the guest
922 	 * shouldn't proceed far enough to need reinjection.
923 	 */
924 	WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
925 
926 	/*
927 	 * Do not check for interception when injecting an event for L2, as the
928 	 * exception was checked for intercept when it was original queued, and
929 	 * re-checking is incorrect if _L1_ injected the exception, in which
930 	 * case it's exempt from interception.
931 	 */
932 	kvm_make_request(KVM_REQ_EVENT, vcpu);
933 
934 	vcpu->arch.exception.injected = true;
935 	vcpu->arch.exception.has_error_code = has_error_code;
936 	vcpu->arch.exception.vector = nr;
937 	vcpu->arch.exception.error_code = error_code;
938 	vcpu->arch.exception.has_payload = false;
939 	vcpu->arch.exception.payload = 0;
940 }
941 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
942 
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)943 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
944 {
945 	if (err)
946 		kvm_inject_gp(vcpu, 0);
947 	else
948 		return kvm_skip_emulated_instruction(vcpu);
949 
950 	return 1;
951 }
952 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
953 
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)954 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
955 {
956 	if (err) {
957 		kvm_inject_gp(vcpu, 0);
958 		return 1;
959 	}
960 
961 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
962 				       EMULTYPE_COMPLETE_USER_EXIT);
963 }
964 
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)965 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
966 {
967 	++vcpu->stat.pf_guest;
968 
969 	/*
970 	 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
971 	 * whether or not L1 wants to intercept "regular" #PF.
972 	 */
973 	if (is_guest_mode(vcpu) && fault->async_page_fault)
974 		kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
975 					   true, fault->error_code,
976 					   true, fault->address);
977 	else
978 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
979 					fault->address);
980 }
981 
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)982 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
983 				    struct x86_exception *fault)
984 {
985 	struct kvm_mmu *fault_mmu;
986 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
987 
988 	fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
989 					       vcpu->arch.walk_mmu;
990 
991 	/*
992 	 * Invalidate the TLB entry for the faulting address, if it exists,
993 	 * else the access will fault indefinitely (and to emulate hardware).
994 	 */
995 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
996 	    !(fault->error_code & PFERR_RSVD_MASK))
997 		kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
998 					KVM_MMU_ROOT_CURRENT);
999 
1000 	fault_mmu->inject_page_fault(vcpu, fault);
1001 }
1002 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_emulated_page_fault);
1003 
kvm_inject_nmi(struct kvm_vcpu * vcpu)1004 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
1005 {
1006 	atomic_inc(&vcpu->arch.nmi_queued);
1007 	kvm_make_request(KVM_REQ_NMI, vcpu);
1008 }
1009 
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1010 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1011 {
1012 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1013 }
1014 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
1015 
1016 /*
1017  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
1018  * a #GP and return false.
1019  */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1020 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1021 {
1022 	if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1023 		return true;
1024 	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1025 	return false;
1026 }
1027 
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1028 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1029 {
1030 	if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1031 		return true;
1032 
1033 	kvm_queue_exception(vcpu, UD_VECTOR);
1034 	return false;
1035 }
1036 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
1037 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)1038 static bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
1039 {
1040 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
1041 
1042 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
1043 }
1044 
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1045 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1046 {
1047 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1048 }
1049 
1050 /*
1051  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
1052  */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1053 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1054 {
1055 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1056 	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1057 	gpa_t real_gpa;
1058 	int i;
1059 	int ret;
1060 	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1061 
1062 	/*
1063 	 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1064 	 * to an L1 GPA.
1065 	 */
1066 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1067 				     PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1068 	if (real_gpa == INVALID_GPA)
1069 		return 0;
1070 
1071 	/* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1072 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1073 				       cr3 & GENMASK(11, 5), sizeof(pdpte));
1074 	if (ret < 0)
1075 		return 0;
1076 
1077 	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1078 		if ((pdpte[i] & PT_PRESENT_MASK) &&
1079 		    (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1080 			return 0;
1081 		}
1082 	}
1083 
1084 	/*
1085 	 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1086 	 * Shadow page roots need to be reconstructed instead.
1087 	 */
1088 	if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1089 		kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1090 
1091 	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1092 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1093 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1094 	vcpu->arch.pdptrs_from_userspace = false;
1095 
1096 	return 1;
1097 }
1098 EXPORT_SYMBOL_FOR_KVM_INTERNAL(load_pdptrs);
1099 
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1100 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1101 {
1102 #ifdef CONFIG_X86_64
1103 	if (cr0 & 0xffffffff00000000UL)
1104 		return false;
1105 #endif
1106 
1107 	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1108 		return false;
1109 
1110 	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1111 		return false;
1112 
1113 	return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1114 }
1115 
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1116 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1117 {
1118 	/*
1119 	 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1120 	 * indirect shadow MMUs.  If paging is disabled, no updates are needed
1121 	 * as there are no permission bits to emulate.  If TDP is enabled, the
1122 	 * MMU's metadata needs to be updated, e.g. so that emulating guest
1123 	 * translations does the right thing, but there's no need to unload the
1124 	 * root as CR0.WP doesn't affect SPTEs.
1125 	 */
1126 	if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1127 		if (!(cr0 & X86_CR0_PG))
1128 			return;
1129 
1130 		if (tdp_enabled) {
1131 			kvm_init_mmu(vcpu);
1132 			return;
1133 		}
1134 	}
1135 
1136 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1137 		/*
1138 		 * Clearing CR0.PG is defined to flush the TLB from the guest's
1139 		 * perspective.
1140 		 */
1141 		if (!(cr0 & X86_CR0_PG))
1142 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1143 		/*
1144 		 * Check for async #PF completion events when enabling paging,
1145 		 * as the vCPU may have previously encountered async #PFs (it's
1146 		 * entirely legal for the guest to toggle paging on/off without
1147 		 * waiting for the async #PF queue to drain).
1148 		 */
1149 		else if (kvm_pv_async_pf_enabled(vcpu))
1150 			kvm_make_request(KVM_REQ_APF_READY, vcpu);
1151 	}
1152 
1153 	if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1154 		kvm_mmu_reset_context(vcpu);
1155 }
1156 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr0);
1157 
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1158 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1159 {
1160 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
1161 
1162 	if (!kvm_is_valid_cr0(vcpu, cr0))
1163 		return 1;
1164 
1165 	cr0 |= X86_CR0_ET;
1166 
1167 	/* Write to CR0 reserved bits are ignored, even on Intel. */
1168 	cr0 &= ~CR0_RESERVED_BITS;
1169 
1170 #ifdef CONFIG_X86_64
1171 	if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1172 	    (cr0 & X86_CR0_PG)) {
1173 		int cs_db, cs_l;
1174 
1175 		if (!is_pae(vcpu))
1176 			return 1;
1177 		kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1178 		if (cs_l)
1179 			return 1;
1180 	}
1181 #endif
1182 	if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1183 	    is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1184 	    !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1185 		return 1;
1186 
1187 	if (!(cr0 & X86_CR0_PG) &&
1188 	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1189 		return 1;
1190 
1191 	if (!(cr0 & X86_CR0_WP) && kvm_is_cr4_bit_set(vcpu, X86_CR4_CET))
1192 		return 1;
1193 
1194 	kvm_x86_call(set_cr0)(vcpu, cr0);
1195 
1196 	kvm_post_set_cr0(vcpu, old_cr0, cr0);
1197 
1198 	return 0;
1199 }
1200 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr0);
1201 
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1202 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1203 {
1204 	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1205 }
1206 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_lmsw);
1207 
kvm_load_xfeatures(struct kvm_vcpu * vcpu,bool load_guest)1208 static void kvm_load_xfeatures(struct kvm_vcpu *vcpu, bool load_guest)
1209 {
1210 	if (vcpu->arch.guest_state_protected)
1211 		return;
1212 
1213 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE))
1214 		return;
1215 
1216 	if (vcpu->arch.xcr0 != kvm_host.xcr0)
1217 		xsetbv(XCR_XFEATURE_ENABLED_MASK,
1218 		       load_guest ? vcpu->arch.xcr0 : kvm_host.xcr0);
1219 
1220 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1221 	    vcpu->arch.ia32_xss != kvm_host.xss)
1222 		wrmsrq(MSR_IA32_XSS, load_guest ? vcpu->arch.ia32_xss : kvm_host.xss);
1223 }
1224 
kvm_load_guest_pkru(struct kvm_vcpu * vcpu)1225 static void kvm_load_guest_pkru(struct kvm_vcpu *vcpu)
1226 {
1227 	if (vcpu->arch.guest_state_protected)
1228 		return;
1229 
1230 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1231 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
1232 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1233 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1234 		wrpkru(vcpu->arch.pkru);
1235 }
1236 
kvm_load_host_pkru(struct kvm_vcpu * vcpu)1237 static void kvm_load_host_pkru(struct kvm_vcpu *vcpu)
1238 {
1239 	if (vcpu->arch.guest_state_protected)
1240 		return;
1241 
1242 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1243 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1244 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1245 		vcpu->arch.pkru = rdpkru();
1246 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1247 			wrpkru(vcpu->arch.host_pkru);
1248 	}
1249 }
1250 
1251 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1252 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1253 {
1254 	return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1255 }
1256 #endif
1257 
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1258 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1259 {
1260 	u64 xcr0 = xcr;
1261 	u64 old_xcr0 = vcpu->arch.xcr0;
1262 	u64 valid_bits;
1263 
1264 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
1265 	if (index != XCR_XFEATURE_ENABLED_MASK)
1266 		return 1;
1267 	if (!(xcr0 & XFEATURE_MASK_FP))
1268 		return 1;
1269 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1270 		return 1;
1271 
1272 	/*
1273 	 * Do not allow the guest to set bits that we do not support
1274 	 * saving.  However, xcr0 bit 0 is always set, even if the
1275 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1276 	 */
1277 	valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1278 	if (xcr0 & ~valid_bits)
1279 		return 1;
1280 
1281 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1282 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1283 		return 1;
1284 
1285 	if (xcr0 & XFEATURE_MASK_AVX512) {
1286 		if (!(xcr0 & XFEATURE_MASK_YMM))
1287 			return 1;
1288 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1289 			return 1;
1290 	}
1291 
1292 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
1293 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1294 		return 1;
1295 
1296 	vcpu->arch.xcr0 = xcr0;
1297 
1298 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1299 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
1300 	return 0;
1301 }
1302 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
1303 
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1304 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1305 {
1306 	/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1307 	if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1308 	    __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1309 		kvm_inject_gp(vcpu, 0);
1310 		return 1;
1311 	}
1312 
1313 	return kvm_skip_emulated_instruction(vcpu);
1314 }
1315 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
1316 
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1317 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1318 {
1319 	return __kvm_is_valid_cr4(vcpu, cr4) &&
1320 	       kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1321 }
1322 
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1323 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1324 {
1325 	if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1326 		kvm_mmu_reset_context(vcpu);
1327 
1328 	/*
1329 	 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1330 	 * according to the SDM; however, stale prev_roots could be reused
1331 	 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1332 	 * free them all.  This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1333 	 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1334 	 * so fall through.
1335 	 */
1336 	if (!tdp_enabled &&
1337 	    (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1338 		kvm_mmu_unload(vcpu);
1339 
1340 	/*
1341 	 * The TLB has to be flushed for all PCIDs if any of the following
1342 	 * (architecturally required) changes happen:
1343 	 * - CR4.PCIDE is changed from 1 to 0
1344 	 * - CR4.PGE is toggled
1345 	 *
1346 	 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1347 	 */
1348 	if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1349 	    (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1350 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1351 
1352 	/*
1353 	 * The TLB has to be flushed for the current PCID if any of the
1354 	 * following (architecturally required) changes happen:
1355 	 * - CR4.SMEP is changed from 0 to 1
1356 	 * - CR4.PAE is toggled
1357 	 */
1358 	else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1359 		 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1360 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1361 
1362 }
1363 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr4);
1364 
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1365 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1366 {
1367 	unsigned long old_cr4 = kvm_read_cr4(vcpu);
1368 
1369 	if (!kvm_is_valid_cr4(vcpu, cr4))
1370 		return 1;
1371 
1372 	if (is_long_mode(vcpu)) {
1373 		if (!(cr4 & X86_CR4_PAE))
1374 			return 1;
1375 		if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1376 			return 1;
1377 	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1378 		   && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1379 		   && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1380 		return 1;
1381 
1382 	if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1383 		/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1384 		if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1385 			return 1;
1386 	}
1387 
1388 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
1389 		return 1;
1390 
1391 	kvm_x86_call(set_cr4)(vcpu, cr4);
1392 
1393 	kvm_post_set_cr4(vcpu, old_cr4, cr4);
1394 
1395 	return 0;
1396 }
1397 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr4);
1398 
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1399 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1400 {
1401 	struct kvm_mmu *mmu = vcpu->arch.mmu;
1402 	unsigned long roots_to_free = 0;
1403 	int i;
1404 
1405 	/*
1406 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1407 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
1408 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
1409 	 * the invalidation, but the guest's TLB entries need to be flushed as
1410 	 * the CPU may have cached entries in its TLB for the target PCID.
1411 	 */
1412 	if (unlikely(tdp_enabled)) {
1413 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1414 		return;
1415 	}
1416 
1417 	/*
1418 	 * If neither the current CR3 nor any of the prev_roots use the given
1419 	 * PCID, then nothing needs to be done here because a resync will
1420 	 * happen anyway before switching to any other CR3.
1421 	 */
1422 	if (kvm_get_active_pcid(vcpu) == pcid) {
1423 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1424 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1425 	}
1426 
1427 	/*
1428 	 * If PCID is disabled, there is no need to free prev_roots even if the
1429 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1430 	 * with PCIDE=0.
1431 	 */
1432 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1433 		return;
1434 
1435 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1436 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1437 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1438 
1439 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1440 }
1441 
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1442 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1443 {
1444 	bool skip_tlb_flush = false;
1445 	unsigned long pcid = 0;
1446 #ifdef CONFIG_X86_64
1447 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1448 		skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1449 		cr3 &= ~X86_CR3_PCID_NOFLUSH;
1450 		pcid = cr3 & X86_CR3_PCID_MASK;
1451 	}
1452 #endif
1453 
1454 	/* PDPTRs are always reloaded for PAE paging. */
1455 	if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1456 		goto handle_tlb_flush;
1457 
1458 	/*
1459 	 * Do not condition the GPA check on long mode, this helper is used to
1460 	 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1461 	 * the current vCPU mode is accurate.
1462 	 */
1463 	if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1464 		return 1;
1465 
1466 	if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1467 		return 1;
1468 
1469 	if (cr3 != kvm_read_cr3(vcpu))
1470 		kvm_mmu_new_pgd(vcpu, cr3);
1471 
1472 	vcpu->arch.cr3 = cr3;
1473 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1474 	/* Do not call post_set_cr3, we do not get here for confidential guests.  */
1475 
1476 handle_tlb_flush:
1477 	/*
1478 	 * A load of CR3 that flushes the TLB flushes only the current PCID,
1479 	 * even if PCID is disabled, in which case PCID=0 is flushed.  It's a
1480 	 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1481 	 * and it's impossible to use a non-zero PCID when PCID is disabled,
1482 	 * i.e. only PCID=0 can be relevant.
1483 	 */
1484 	if (!skip_tlb_flush)
1485 		kvm_invalidate_pcid(vcpu, pcid);
1486 
1487 	return 0;
1488 }
1489 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr3);
1490 
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1491 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1492 {
1493 	if (cr8 & CR8_RESERVED_BITS)
1494 		return 1;
1495 	if (lapic_in_kernel(vcpu))
1496 		kvm_lapic_set_tpr(vcpu, cr8);
1497 	else
1498 		vcpu->arch.cr8 = cr8;
1499 	return 0;
1500 }
1501 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr8);
1502 
kvm_get_cr8(struct kvm_vcpu * vcpu)1503 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1504 {
1505 	if (lapic_in_kernel(vcpu))
1506 		return kvm_lapic_get_cr8(vcpu);
1507 	else
1508 		return vcpu->arch.cr8;
1509 }
1510 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_cr8);
1511 
kvm_update_dr0123(struct kvm_vcpu * vcpu)1512 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1513 {
1514 	int i;
1515 
1516 	if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1517 		for (i = 0; i < KVM_NR_DB_REGS; i++)
1518 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1519 	}
1520 }
1521 
kvm_update_dr7(struct kvm_vcpu * vcpu)1522 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1523 {
1524 	unsigned long dr7;
1525 
1526 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1527 		dr7 = vcpu->arch.guest_debug_dr7;
1528 	else
1529 		dr7 = vcpu->arch.dr7;
1530 	kvm_x86_call(set_dr7)(vcpu, dr7);
1531 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1532 	if (dr7 & DR7_BP_EN_MASK)
1533 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1534 }
1535 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_update_dr7);
1536 
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1537 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1538 {
1539 	u64 fixed = DR6_FIXED_1;
1540 
1541 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1542 		fixed |= DR6_RTM;
1543 
1544 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1545 		fixed |= DR6_BUS_LOCK;
1546 	return fixed;
1547 }
1548 
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1549 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1550 {
1551 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1552 
1553 	switch (dr) {
1554 	case 0 ... 3:
1555 		vcpu->arch.db[array_index_nospec(dr, size)] = val;
1556 		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1557 			vcpu->arch.eff_db[dr] = val;
1558 		break;
1559 	case 4:
1560 	case 6:
1561 		if (!kvm_dr6_valid(val))
1562 			return 1; /* #GP */
1563 		vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1564 		break;
1565 	case 5:
1566 	default: /* 7 */
1567 		if (!kvm_dr7_valid(val))
1568 			return 1; /* #GP */
1569 		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1570 		kvm_update_dr7(vcpu);
1571 		break;
1572 	}
1573 
1574 	return 0;
1575 }
1576 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_dr);
1577 
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1578 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1579 {
1580 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1581 
1582 	switch (dr) {
1583 	case 0 ... 3:
1584 		return vcpu->arch.db[array_index_nospec(dr, size)];
1585 	case 4:
1586 	case 6:
1587 		return vcpu->arch.dr6;
1588 	case 5:
1589 	default: /* 7 */
1590 		return vcpu->arch.dr7;
1591 	}
1592 }
1593 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_dr);
1594 
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1595 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1596 {
1597 	u32 pmc = kvm_rcx_read(vcpu);
1598 	u64 data;
1599 
1600 	if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
1601 		kvm_inject_gp(vcpu, 0);
1602 		return 1;
1603 	}
1604 
1605 	kvm_rax_write(vcpu, (u32)data);
1606 	kvm_rdx_write(vcpu, data >> 32);
1607 	return kvm_skip_emulated_instruction(vcpu);
1608 }
1609 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
1610 
1611 /*
1612  * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1613  * does not yet virtualize. These include:
1614  *   10 - MISC_PACKAGE_CTRLS
1615  *   11 - ENERGY_FILTERING_CTL
1616  *   12 - DOITM
1617  *   18 - FB_CLEAR_CTRL
1618  *   21 - XAPIC_DISABLE_STATUS
1619  *   23 - OVERCLOCKING_STATUS
1620  */
1621 
1622 #define KVM_SUPPORTED_ARCH_CAP \
1623 	(ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1624 	 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1625 	 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1626 	 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1627 	 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1628 	 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1629 
kvm_get_arch_capabilities(void)1630 static u64 kvm_get_arch_capabilities(void)
1631 {
1632 	u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1633 
1634 	/*
1635 	 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1636 	 * the nested hypervisor runs with NX huge pages.  If it is not,
1637 	 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1638 	 * L1 guests, so it need not worry about its own (L2) guests.
1639 	 */
1640 	data |= ARCH_CAP_PSCHANGE_MC_NO;
1641 
1642 	/*
1643 	 * If we're doing cache flushes (either "always" or "cond")
1644 	 * we will do one whenever the guest does a vmlaunch/vmresume.
1645 	 * If an outer hypervisor is doing the cache flush for us
1646 	 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1647 	 * capability to the guest too, and if EPT is disabled we're not
1648 	 * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1649 	 * require a nested hypervisor to do a flush of its own.
1650 	 */
1651 	if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1652 		data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1653 
1654 	if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1655 		data |= ARCH_CAP_RDCL_NO;
1656 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1657 		data |= ARCH_CAP_SSB_NO;
1658 	if (!boot_cpu_has_bug(X86_BUG_MDS))
1659 		data |= ARCH_CAP_MDS_NO;
1660 	if (!boot_cpu_has_bug(X86_BUG_RFDS))
1661 		data |= ARCH_CAP_RFDS_NO;
1662 	if (!boot_cpu_has_bug(X86_BUG_ITS))
1663 		data |= ARCH_CAP_ITS_NO;
1664 
1665 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1666 		/*
1667 		 * If RTM=0 because the kernel has disabled TSX, the host might
1668 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1669 		 * and therefore knows that there cannot be TAA) but keep
1670 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1671 		 * and we want to allow migrating those guests to tsx=off hosts.
1672 		 */
1673 		data &= ~ARCH_CAP_TAA_NO;
1674 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1675 		data |= ARCH_CAP_TAA_NO;
1676 	} else {
1677 		/*
1678 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1679 		 * host so the guest can choose between disabling TSX or
1680 		 * using VERW to clear CPU buffers.
1681 		 */
1682 	}
1683 
1684 	if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1685 		data |= ARCH_CAP_GDS_NO;
1686 
1687 	return data;
1688 }
1689 
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1690 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1691 			       bool host_initiated)
1692 {
1693 	WARN_ON_ONCE(!host_initiated);
1694 
1695 	switch (index) {
1696 	case MSR_IA32_ARCH_CAPABILITIES:
1697 		*data = kvm_get_arch_capabilities();
1698 		break;
1699 	case MSR_IA32_PERF_CAPABILITIES:
1700 		*data = kvm_caps.supported_perf_cap;
1701 		break;
1702 	case MSR_PLATFORM_INFO:
1703 		*data = MSR_PLATFORM_INFO_CPUID_FAULT;
1704 		break;
1705 	case MSR_IA32_UCODE_REV:
1706 		rdmsrq_safe(index, data);
1707 		break;
1708 	default:
1709 		return kvm_x86_call(get_feature_msr)(index, data);
1710 	}
1711 	return 0;
1712 }
1713 
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1714 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1715 {
1716 	return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1717 				 kvm_get_feature_msr);
1718 }
1719 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1720 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1721 {
1722 	if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1723 		return false;
1724 
1725 	if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1726 		return false;
1727 
1728 	if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1729 		return false;
1730 
1731 	if (efer & (EFER_LME | EFER_LMA) &&
1732 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1733 		return false;
1734 
1735 	if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1736 		return false;
1737 
1738 	return true;
1739 
1740 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1741 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1742 {
1743 	if (efer & efer_reserved_bits)
1744 		return false;
1745 
1746 	return __kvm_valid_efer(vcpu, efer);
1747 }
1748 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_valid_efer);
1749 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1750 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1751 {
1752 	u64 old_efer = vcpu->arch.efer;
1753 	u64 efer = msr_info->data;
1754 	int r;
1755 
1756 	if (efer & efer_reserved_bits)
1757 		return 1;
1758 
1759 	if (!msr_info->host_initiated) {
1760 		if (!__kvm_valid_efer(vcpu, efer))
1761 			return 1;
1762 
1763 		if (is_paging(vcpu) &&
1764 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1765 			return 1;
1766 	}
1767 
1768 	efer &= ~EFER_LMA;
1769 	efer |= vcpu->arch.efer & EFER_LMA;
1770 
1771 	r = kvm_x86_call(set_efer)(vcpu, efer);
1772 	if (r) {
1773 		WARN_ON(r > 0);
1774 		return r;
1775 	}
1776 
1777 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1778 		kvm_mmu_reset_context(vcpu);
1779 
1780 	if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1781 	    (efer & EFER_SVME))
1782 		kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1783 
1784 	return 0;
1785 }
1786 
kvm_enable_efer_bits(u64 mask)1787 void kvm_enable_efer_bits(u64 mask)
1788 {
1789        efer_reserved_bits &= ~mask;
1790 }
1791 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_enable_efer_bits);
1792 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1793 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1794 {
1795 	struct kvm_x86_msr_filter *msr_filter;
1796 	struct msr_bitmap_range *ranges;
1797 	struct kvm *kvm = vcpu->kvm;
1798 	bool allowed;
1799 	int idx;
1800 	u32 i;
1801 
1802 	/* x2APIC MSRs do not support filtering. */
1803 	if (index >= 0x800 && index <= 0x8ff)
1804 		return true;
1805 
1806 	idx = srcu_read_lock(&kvm->srcu);
1807 
1808 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1809 	if (!msr_filter) {
1810 		allowed = true;
1811 		goto out;
1812 	}
1813 
1814 	allowed = msr_filter->default_allow;
1815 	ranges = msr_filter->ranges;
1816 
1817 	for (i = 0; i < msr_filter->count; i++) {
1818 		u32 start = ranges[i].base;
1819 		u32 end = start + ranges[i].nmsrs;
1820 		u32 flags = ranges[i].flags;
1821 		unsigned long *bitmap = ranges[i].bitmap;
1822 
1823 		if ((index >= start) && (index < end) && (flags & type)) {
1824 			allowed = test_bit(index - start, bitmap);
1825 			break;
1826 		}
1827 	}
1828 
1829 out:
1830 	srcu_read_unlock(&kvm->srcu, idx);
1831 
1832 	return allowed;
1833 }
1834 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_msr_allowed);
1835 
1836 /*
1837  * Write @data into the MSR specified by @index.  Select MSR specific fault
1838  * checks are bypassed if @host_initiated is %true.
1839  * Returns 0 on success, non-0 otherwise.
1840  * Assumes vcpu_load() was already called.
1841  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1842 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1843 			 bool host_initiated)
1844 {
1845 	struct msr_data msr;
1846 
1847 	switch (index) {
1848 	case MSR_FS_BASE:
1849 	case MSR_GS_BASE:
1850 	case MSR_KERNEL_GS_BASE:
1851 	case MSR_CSTAR:
1852 	case MSR_LSTAR:
1853 		if (is_noncanonical_msr_address(data, vcpu))
1854 			return 1;
1855 		break;
1856 	case MSR_IA32_SYSENTER_EIP:
1857 	case MSR_IA32_SYSENTER_ESP:
1858 		/*
1859 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1860 		 * non-canonical address is written on Intel but not on
1861 		 * AMD (which ignores the top 32-bits, because it does
1862 		 * not implement 64-bit SYSENTER).
1863 		 *
1864 		 * 64-bit code should hence be able to write a non-canonical
1865 		 * value on AMD.  Making the address canonical ensures that
1866 		 * vmentry does not fail on Intel after writing a non-canonical
1867 		 * value, and that something deterministic happens if the guest
1868 		 * invokes 64-bit SYSENTER.
1869 		 */
1870 		data = __canonical_address(data, max_host_virt_addr_bits());
1871 		break;
1872 	case MSR_TSC_AUX:
1873 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1874 			return 1;
1875 
1876 		if (!host_initiated &&
1877 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1878 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1879 			return 1;
1880 
1881 		/*
1882 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1883 		 * incomplete and conflicting architectural behavior.  Current
1884 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1885 		 * reserved and always read as zeros.  Enforce Intel's reserved
1886 		 * bits check if the guest CPU is Intel compatible, otherwise
1887 		 * clear the bits.  This ensures cross-vendor migration will
1888 		 * provide consistent behavior for the guest.
1889 		 */
1890 		if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1891 			return 1;
1892 
1893 		data = (u32)data;
1894 		break;
1895 	case MSR_IA32_U_CET:
1896 	case MSR_IA32_S_CET:
1897 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1898 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1899 			return KVM_MSR_RET_UNSUPPORTED;
1900 		if (!kvm_is_valid_u_s_cet(vcpu, data))
1901 			return 1;
1902 		break;
1903 	case MSR_KVM_INTERNAL_GUEST_SSP:
1904 		if (!host_initiated)
1905 			return 1;
1906 		fallthrough;
1907 		/*
1908 		 * Note that the MSR emulation here is flawed when a vCPU
1909 		 * doesn't support the Intel 64 architecture. The expected
1910 		 * architectural behavior in this case is that the upper 32
1911 		 * bits do not exist and should always read '0'. However,
1912 		 * because the actual hardware on which the virtual CPU is
1913 		 * running does support Intel 64, XRSTORS/XSAVES in the
1914 		 * guest could observe behavior that violates the
1915 		 * architecture. Intercepting XRSTORS/XSAVES for this
1916 		 * special case isn't deemed worthwhile.
1917 		 */
1918 	case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1919 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1920 			return KVM_MSR_RET_UNSUPPORTED;
1921 		/*
1922 		 * MSR_IA32_INT_SSP_TAB is not present on processors that do
1923 		 * not support Intel 64 architecture.
1924 		 */
1925 		if (index == MSR_IA32_INT_SSP_TAB && !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1926 			return KVM_MSR_RET_UNSUPPORTED;
1927 		if (is_noncanonical_msr_address(data, vcpu))
1928 			return 1;
1929 		/* All SSP MSRs except MSR_IA32_INT_SSP_TAB must be 4-byte aligned */
1930 		if (index != MSR_IA32_INT_SSP_TAB && !IS_ALIGNED(data, 4))
1931 			return 1;
1932 		break;
1933 	}
1934 
1935 	msr.data = data;
1936 	msr.index = index;
1937 	msr.host_initiated = host_initiated;
1938 
1939 	return kvm_x86_call(set_msr)(vcpu, &msr);
1940 }
1941 
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1942 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1943 			bool host_initiated)
1944 {
1945 	return __kvm_set_msr(vcpu, index, *data, host_initiated);
1946 }
1947 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1948 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1949 				     u32 index, u64 data, bool host_initiated)
1950 {
1951 	return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1952 				 _kvm_set_msr);
1953 }
1954 
1955 /*
1956  * Read the MSR specified by @index into @data.  Select MSR specific fault
1957  * checks are bypassed if @host_initiated is %true.
1958  * Returns 0 on success, non-0 otherwise.
1959  * Assumes vcpu_load() was already called.
1960  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1961 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1962 			 bool host_initiated)
1963 {
1964 	struct msr_data msr;
1965 	int ret;
1966 
1967 	switch (index) {
1968 	case MSR_TSC_AUX:
1969 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1970 			return 1;
1971 
1972 		if (!host_initiated &&
1973 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1974 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1975 			return 1;
1976 		break;
1977 	case MSR_IA32_U_CET:
1978 	case MSR_IA32_S_CET:
1979 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1980 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1981 			return KVM_MSR_RET_UNSUPPORTED;
1982 		break;
1983 	case MSR_KVM_INTERNAL_GUEST_SSP:
1984 		if (!host_initiated)
1985 			return 1;
1986 		fallthrough;
1987 	case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1988 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1989 			return KVM_MSR_RET_UNSUPPORTED;
1990 		break;
1991 	}
1992 
1993 	msr.index = index;
1994 	msr.host_initiated = host_initiated;
1995 
1996 	ret = kvm_x86_call(get_msr)(vcpu, &msr);
1997 	if (!ret)
1998 		*data = msr.data;
1999 	return ret;
2000 }
2001 
kvm_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2002 int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2003 {
2004 	return __kvm_set_msr(vcpu, index, data, true);
2005 }
2006 
kvm_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2007 int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2008 {
2009 	return __kvm_get_msr(vcpu, index, data, true);
2010 }
2011 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)2012 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
2013 				     u32 index, u64 *data, bool host_initiated)
2014 {
2015 	return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
2016 				 __kvm_get_msr);
2017 }
2018 
__kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2019 int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2020 {
2021 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
2022 }
2023 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_read);
2024 
__kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2025 int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2026 {
2027 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
2028 }
2029 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_write);
2030 
kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2031 int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2032 {
2033 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
2034 		return KVM_MSR_RET_FILTERED;
2035 
2036 	return __kvm_emulate_msr_read(vcpu, index, data);
2037 }
2038 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_read);
2039 
kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2040 int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2041 {
2042 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
2043 		return KVM_MSR_RET_FILTERED;
2044 
2045 	return __kvm_emulate_msr_write(vcpu, index, data);
2046 }
2047 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
2048 
2049 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)2050 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
2051 {
2052 	if (!vcpu->run->msr.error) {
2053 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
2054 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2055 	}
2056 }
2057 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)2058 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2059 {
2060 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2061 }
2062 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)2063 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2064 {
2065 	complete_userspace_rdmsr(vcpu);
2066 	return complete_emulated_msr_access(vcpu);
2067 }
2068 
complete_fast_msr_access(struct kvm_vcpu * vcpu)2069 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2070 {
2071 	return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2072 }
2073 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2074 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2075 {
2076 	complete_userspace_rdmsr(vcpu);
2077 	return complete_fast_msr_access(vcpu);
2078 }
2079 
complete_fast_rdmsr_imm(struct kvm_vcpu * vcpu)2080 static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
2081 {
2082 	if (!vcpu->run->msr.error)
2083 		kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
2084 				   vcpu->run->msr.data);
2085 
2086 	return complete_fast_msr_access(vcpu);
2087 }
2088 
kvm_msr_reason(int r)2089 static u64 kvm_msr_reason(int r)
2090 {
2091 	switch (r) {
2092 	case KVM_MSR_RET_UNSUPPORTED:
2093 		return KVM_MSR_EXIT_REASON_UNKNOWN;
2094 	case KVM_MSR_RET_FILTERED:
2095 		return KVM_MSR_EXIT_REASON_FILTER;
2096 	default:
2097 		return KVM_MSR_EXIT_REASON_INVAL;
2098 	}
2099 }
2100 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2101 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2102 			      u32 exit_reason, u64 data,
2103 			      int (*completion)(struct kvm_vcpu *vcpu),
2104 			      int r)
2105 {
2106 	u64 msr_reason = kvm_msr_reason(r);
2107 
2108 	/* Check if the user wanted to know about this MSR fault */
2109 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2110 		return 0;
2111 
2112 	vcpu->run->exit_reason = exit_reason;
2113 	vcpu->run->msr.error = 0;
2114 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2115 	vcpu->run->msr.reason = msr_reason;
2116 	vcpu->run->msr.index = index;
2117 	vcpu->run->msr.data = data;
2118 	vcpu->arch.complete_userspace_io = completion;
2119 
2120 	return 1;
2121 }
2122 
__kvm_emulate_rdmsr(struct kvm_vcpu * vcpu,u32 msr,int reg,int (* complete_rdmsr)(struct kvm_vcpu *))2123 static int __kvm_emulate_rdmsr(struct kvm_vcpu *vcpu, u32 msr, int reg,
2124 			       int (*complete_rdmsr)(struct kvm_vcpu *))
2125 {
2126 	u64 data;
2127 	int r;
2128 
2129 	r = kvm_emulate_msr_read(vcpu, msr, &data);
2130 
2131 	if (!r) {
2132 		trace_kvm_msr_read(msr, data);
2133 
2134 		if (reg < 0) {
2135 			kvm_rax_write(vcpu, data & -1u);
2136 			kvm_rdx_write(vcpu, (data >> 32) & -1u);
2137 		} else {
2138 			kvm_register_write(vcpu, reg, data);
2139 		}
2140 	} else {
2141 		/* MSR read failed? See if we should ask user space */
2142 		if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_RDMSR, 0,
2143 				       complete_rdmsr, r))
2144 			return 0;
2145 		trace_kvm_msr_read_ex(msr);
2146 	}
2147 
2148 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2149 }
2150 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2151 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2152 {
2153 	return __kvm_emulate_rdmsr(vcpu, kvm_rcx_read(vcpu), -1,
2154 				   complete_fast_rdmsr);
2155 }
2156 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr);
2157 
kvm_emulate_rdmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2158 int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2159 {
2160 	vcpu->arch.cui_rdmsr_imm_reg = reg;
2161 
2162 	return __kvm_emulate_rdmsr(vcpu, msr, reg, complete_fast_rdmsr_imm);
2163 }
2164 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr_imm);
2165 
__kvm_emulate_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2166 static int __kvm_emulate_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2167 {
2168 	int r;
2169 
2170 	r = kvm_emulate_msr_write(vcpu, msr, data);
2171 	if (!r) {
2172 		trace_kvm_msr_write(msr, data);
2173 	} else {
2174 		/* MSR write failed? See if we should ask user space */
2175 		if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_WRMSR, data,
2176 				       complete_fast_msr_access, r))
2177 			return 0;
2178 		/* Signal all other negative errors to userspace */
2179 		if (r < 0)
2180 			return r;
2181 		trace_kvm_msr_write_ex(msr, data);
2182 	}
2183 
2184 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2185 }
2186 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2187 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2188 {
2189 	return __kvm_emulate_wrmsr(vcpu, kvm_rcx_read(vcpu),
2190 				   kvm_read_edx_eax(vcpu));
2191 }
2192 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr);
2193 
kvm_emulate_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2194 int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2195 {
2196 	return __kvm_emulate_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2197 }
2198 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr_imm);
2199 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2200 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2201 {
2202 	return kvm_skip_emulated_instruction(vcpu);
2203 }
2204 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2205 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2206 {
2207 	/* Treat an INVD instruction as a NOP and just skip it. */
2208 	return kvm_emulate_as_nop(vcpu);
2209 }
2210 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
2211 
handle_fastpath_invd(struct kvm_vcpu * vcpu)2212 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
2213 {
2214 	if (!kvm_emulate_invd(vcpu))
2215 		return EXIT_FASTPATH_EXIT_USERSPACE;
2216 
2217 	return EXIT_FASTPATH_REENTER_GUEST;
2218 }
2219 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
2220 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2221 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2222 {
2223 	kvm_queue_exception(vcpu, UD_VECTOR);
2224 	return 1;
2225 }
2226 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
2227 
2228 
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2229 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2230 {
2231 	bool enabled;
2232 
2233 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2234 		goto emulate_as_nop;
2235 
2236 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2237 		enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2238 	else
2239 		enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2240 
2241 	if (!enabled)
2242 		return kvm_handle_invalid_op(vcpu);
2243 
2244 emulate_as_nop:
2245 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
2246 	return kvm_emulate_as_nop(vcpu);
2247 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2248 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2249 {
2250 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2251 }
2252 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
2253 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2254 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2255 {
2256 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2257 }
2258 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
2259 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2260 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2261 {
2262 	xfer_to_guest_mode_prepare();
2263 
2264 	return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2265 	       kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2266 }
2267 
__handle_fastpath_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2268 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2269 {
2270 	switch (msr) {
2271 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2272 		if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
2273 		    kvm_x2apic_icr_write_fast(vcpu->arch.apic, data))
2274 			return EXIT_FASTPATH_NONE;
2275 		break;
2276 	case MSR_IA32_TSC_DEADLINE:
2277 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
2278 		break;
2279 	default:
2280 		return EXIT_FASTPATH_NONE;
2281 	}
2282 
2283 	trace_kvm_msr_write(msr, data);
2284 
2285 	if (!kvm_skip_emulated_instruction(vcpu))
2286 		return EXIT_FASTPATH_EXIT_USERSPACE;
2287 
2288 	return EXIT_FASTPATH_REENTER_GUEST;
2289 }
2290 
handle_fastpath_wrmsr(struct kvm_vcpu * vcpu)2291 fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu)
2292 {
2293 	return __handle_fastpath_wrmsr(vcpu, kvm_rcx_read(vcpu),
2294 				       kvm_read_edx_eax(vcpu));
2295 }
2296 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr);
2297 
handle_fastpath_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2298 fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2299 {
2300 	return __handle_fastpath_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2301 }
2302 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
2303 
2304 /*
2305  * Adapt set_msr() to msr_io()'s calling convention
2306  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2307 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2308 {
2309 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2310 }
2311 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2312 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2313 {
2314 	u64 val;
2315 
2316 	/*
2317 	 * Disallow writes to immutable feature MSRs after KVM_RUN.  KVM does
2318 	 * not support modifying the guest vCPU model on the fly, e.g. changing
2319 	 * the nVMX capabilities while L2 is running is nonsensical.  Allow
2320 	 * writes of the same value, e.g. to allow userspace to blindly stuff
2321 	 * all MSRs when emulating RESET.
2322 	 */
2323 	if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2324 	    (do_get_msr(vcpu, index, &val) || *data != val))
2325 		return -EINVAL;
2326 
2327 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2328 }
2329 
2330 #ifdef CONFIG_X86_64
2331 struct pvclock_clock {
2332 	int vclock_mode;
2333 	u64 cycle_last;
2334 	u64 mask;
2335 	u32 mult;
2336 	u32 shift;
2337 	u64 base_cycles;
2338 	u64 offset;
2339 };
2340 
2341 struct pvclock_gtod_data {
2342 	seqcount_t	seq;
2343 
2344 	struct pvclock_clock clock; /* extract of a clocksource struct */
2345 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2346 
2347 	ktime_t		offs_boot;
2348 	u64		wall_time_sec;
2349 };
2350 
2351 static struct pvclock_gtod_data pvclock_gtod_data;
2352 
update_pvclock_gtod(struct timekeeper * tk)2353 static void update_pvclock_gtod(struct timekeeper *tk)
2354 {
2355 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2356 
2357 	write_seqcount_begin(&vdata->seq);
2358 
2359 	/* copy pvclock gtod data */
2360 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2361 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2362 	vdata->clock.mask		= tk->tkr_mono.mask;
2363 	vdata->clock.mult		= tk->tkr_mono.mult;
2364 	vdata->clock.shift		= tk->tkr_mono.shift;
2365 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2366 	vdata->clock.offset		= tk->tkr_mono.base;
2367 
2368 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2369 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2370 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2371 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2372 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2373 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2374 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2375 
2376 	vdata->wall_time_sec            = tk->xtime_sec;
2377 
2378 	vdata->offs_boot		= tk->offs_boot;
2379 
2380 	write_seqcount_end(&vdata->seq);
2381 }
2382 
get_kvmclock_base_ns(void)2383 static s64 get_kvmclock_base_ns(void)
2384 {
2385 	/* Count up from boot time, but with the frequency of the raw clock.  */
2386 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2387 }
2388 #else
get_kvmclock_base_ns(void)2389 static s64 get_kvmclock_base_ns(void)
2390 {
2391 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2392 	return ktime_get_boottime_ns();
2393 }
2394 #endif
2395 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2396 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2397 {
2398 	int version;
2399 	int r;
2400 	struct pvclock_wall_clock wc;
2401 	u32 wc_sec_hi;
2402 	u64 wall_nsec;
2403 
2404 	if (!wall_clock)
2405 		return;
2406 
2407 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2408 	if (r)
2409 		return;
2410 
2411 	if (version & 1)
2412 		++version;  /* first time write, random junk */
2413 
2414 	++version;
2415 
2416 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2417 		return;
2418 
2419 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
2420 
2421 	wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2422 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2423 	wc.version = version;
2424 
2425 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2426 
2427 	if (sec_hi_ofs) {
2428 		wc_sec_hi = wall_nsec >> 32;
2429 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2430 				&wc_sec_hi, sizeof(wc_sec_hi));
2431 	}
2432 
2433 	version++;
2434 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2435 }
2436 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2437 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2438 				  bool old_msr, bool host_initiated)
2439 {
2440 	struct kvm_arch *ka = &vcpu->kvm->arch;
2441 
2442 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2443 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2444 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2445 
2446 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2447 	}
2448 
2449 	vcpu->arch.time = system_time;
2450 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2451 
2452 	/* we verify if the enable bit is set... */
2453 	if (system_time & 1)
2454 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2455 				 sizeof(struct pvclock_vcpu_time_info));
2456 	else
2457 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
2458 
2459 	return;
2460 }
2461 
div_frac(uint32_t dividend,uint32_t divisor)2462 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2463 {
2464 	do_shl32_div32(dividend, divisor);
2465 	return dividend;
2466 }
2467 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2468 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2469 			       s8 *pshift, u32 *pmultiplier)
2470 {
2471 	uint64_t scaled64;
2472 	int32_t  shift = 0;
2473 	uint64_t tps64;
2474 	uint32_t tps32;
2475 
2476 	tps64 = base_hz;
2477 	scaled64 = scaled_hz;
2478 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2479 		tps64 >>= 1;
2480 		shift--;
2481 	}
2482 
2483 	tps32 = (uint32_t)tps64;
2484 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2485 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2486 			scaled64 >>= 1;
2487 		else
2488 			tps32 <<= 1;
2489 		shift++;
2490 	}
2491 
2492 	*pshift = shift;
2493 	*pmultiplier = div_frac(scaled64, tps32);
2494 }
2495 
2496 #ifdef CONFIG_X86_64
2497 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2498 #endif
2499 
2500 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2501 static unsigned long max_tsc_khz;
2502 
adjust_tsc_khz(u32 khz,s32 ppm)2503 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2504 {
2505 	u64 v = (u64)khz * (1000000 + ppm);
2506 	do_div(v, 1000000);
2507 	return v;
2508 }
2509 
2510 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2511 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2512 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2513 {
2514 	u64 ratio;
2515 
2516 	/* Guest TSC same frequency as host TSC? */
2517 	if (!scale) {
2518 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2519 		return 0;
2520 	}
2521 
2522 	/* TSC scaling supported? */
2523 	if (!kvm_caps.has_tsc_control) {
2524 		if (user_tsc_khz > tsc_khz) {
2525 			vcpu->arch.tsc_catchup = 1;
2526 			vcpu->arch.tsc_always_catchup = 1;
2527 			return 0;
2528 		} else {
2529 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2530 			return -1;
2531 		}
2532 	}
2533 
2534 	/* TSC scaling required  - calculate ratio */
2535 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2536 				user_tsc_khz, tsc_khz);
2537 
2538 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2539 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2540 			            user_tsc_khz);
2541 		return -1;
2542 	}
2543 
2544 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2545 	return 0;
2546 }
2547 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2548 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2549 {
2550 	u32 thresh_lo, thresh_hi;
2551 	int use_scaling = 0;
2552 
2553 	/* tsc_khz can be zero if TSC calibration fails */
2554 	if (user_tsc_khz == 0) {
2555 		/* set tsc_scaling_ratio to a safe value */
2556 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2557 		return -1;
2558 	}
2559 
2560 	/* Compute a scale to convert nanoseconds in TSC cycles */
2561 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2562 			   &vcpu->arch.virtual_tsc_shift,
2563 			   &vcpu->arch.virtual_tsc_mult);
2564 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2565 
2566 	/*
2567 	 * Compute the variation in TSC rate which is acceptable
2568 	 * within the range of tolerance and decide if the
2569 	 * rate being applied is within that bounds of the hardware
2570 	 * rate.  If so, no scaling or compensation need be done.
2571 	 */
2572 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2573 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2574 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2575 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2576 			 user_tsc_khz, thresh_lo, thresh_hi);
2577 		use_scaling = 1;
2578 	}
2579 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2580 }
2581 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2582 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2583 {
2584 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2585 				      vcpu->arch.virtual_tsc_mult,
2586 				      vcpu->arch.virtual_tsc_shift);
2587 	tsc += vcpu->arch.this_tsc_write;
2588 	return tsc;
2589 }
2590 
2591 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2592 static inline bool gtod_is_based_on_tsc(int mode)
2593 {
2594 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2595 }
2596 #endif
2597 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2598 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2599 {
2600 #ifdef CONFIG_X86_64
2601 	struct kvm_arch *ka = &vcpu->kvm->arch;
2602 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2603 
2604 	/*
2605 	 * To use the masterclock, the host clocksource must be based on TSC
2606 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
2607 	 * vCPUs doesn't include the reference vCPU, hence "+1".
2608 	 */
2609 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2610 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
2611 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2612 
2613 	/*
2614 	 * Request a masterclock update if the masterclock needs to be toggled
2615 	 * on/off, or when starting a new generation and the masterclock is
2616 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2617 	 * taken _after_ the new generation is created).
2618 	 */
2619 	if ((ka->use_master_clock && new_generation) ||
2620 	    (ka->use_master_clock != use_master_clock))
2621 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2622 
2623 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2624 			    atomic_read(&vcpu->kvm->online_vcpus),
2625 		            ka->use_master_clock, gtod->clock.vclock_mode);
2626 #endif
2627 }
2628 
2629 /*
2630  * Multiply tsc by a fixed point number represented by ratio.
2631  *
2632  * The most significant 64-N bits (mult) of ratio represent the
2633  * integral part of the fixed point number; the remaining N bits
2634  * (frac) represent the fractional part, ie. ratio represents a fixed
2635  * point number (mult + frac * 2^(-N)).
2636  *
2637  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2638  */
__scale_tsc(u64 ratio,u64 tsc)2639 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2640 {
2641 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2642 }
2643 
kvm_scale_tsc(u64 tsc,u64 ratio)2644 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2645 {
2646 	u64 _tsc = tsc;
2647 
2648 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
2649 		_tsc = __scale_tsc(ratio, tsc);
2650 
2651 	return _tsc;
2652 }
2653 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2654 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2655 {
2656 	u64 tsc;
2657 
2658 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2659 
2660 	return target_tsc - tsc;
2661 }
2662 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2663 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2664 {
2665 	return vcpu->arch.l1_tsc_offset +
2666 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2667 }
2668 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
2669 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2670 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2671 {
2672 	u64 nested_offset;
2673 
2674 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2675 		nested_offset = l1_offset;
2676 	else
2677 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2678 						kvm_caps.tsc_scaling_ratio_frac_bits);
2679 
2680 	nested_offset += l2_offset;
2681 	return nested_offset;
2682 }
2683 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
2684 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2685 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2686 {
2687 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2688 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2689 				       kvm_caps.tsc_scaling_ratio_frac_bits);
2690 
2691 	return l1_multiplier;
2692 }
2693 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
2694 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2695 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2696 {
2697 	if (vcpu->arch.guest_tsc_protected)
2698 		return;
2699 
2700 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2701 				   vcpu->arch.l1_tsc_offset,
2702 				   l1_offset);
2703 
2704 	vcpu->arch.l1_tsc_offset = l1_offset;
2705 
2706 	/*
2707 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2708 	 * according to the spec this should set L1's TSC (as opposed to
2709 	 * setting L1's offset for L2).
2710 	 */
2711 	if (is_guest_mode(vcpu))
2712 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2713 			l1_offset,
2714 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
2715 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2716 	else
2717 		vcpu->arch.tsc_offset = l1_offset;
2718 
2719 	kvm_x86_call(write_tsc_offset)(vcpu);
2720 }
2721 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2722 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2723 {
2724 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2725 
2726 	/* Userspace is changing the multiplier while L2 is active */
2727 	if (is_guest_mode(vcpu))
2728 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2729 			l1_multiplier,
2730 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2731 	else
2732 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2733 
2734 	if (kvm_caps.has_tsc_control)
2735 		kvm_x86_call(write_tsc_multiplier)(vcpu);
2736 }
2737 
kvm_check_tsc_unstable(void)2738 static inline bool kvm_check_tsc_unstable(void)
2739 {
2740 #ifdef CONFIG_X86_64
2741 	/*
2742 	 * TSC is marked unstable when we're running on Hyper-V,
2743 	 * 'TSC page' clocksource is good.
2744 	 */
2745 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2746 		return false;
2747 #endif
2748 	return check_tsc_unstable();
2749 }
2750 
2751 /*
2752  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2753  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2754  * participates in.
2755  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2756 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2757 				  u64 ns, bool matched, bool user_set_tsc)
2758 {
2759 	struct kvm *kvm = vcpu->kvm;
2760 
2761 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2762 
2763 	if (vcpu->arch.guest_tsc_protected)
2764 		return;
2765 
2766 	if (user_set_tsc)
2767 		vcpu->kvm->arch.user_set_tsc = true;
2768 
2769 	/*
2770 	 * We also track th most recent recorded KHZ, write and time to
2771 	 * allow the matching interval to be extended at each write.
2772 	 */
2773 	kvm->arch.last_tsc_nsec = ns;
2774 	kvm->arch.last_tsc_write = tsc;
2775 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2776 	kvm->arch.last_tsc_offset = offset;
2777 
2778 	vcpu->arch.last_guest_tsc = tsc;
2779 
2780 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2781 
2782 	if (!matched) {
2783 		/*
2784 		 * We split periods of matched TSC writes into generations.
2785 		 * For each generation, we track the original measured
2786 		 * nanosecond time, offset, and write, so if TSCs are in
2787 		 * sync, we can match exact offset, and if not, we can match
2788 		 * exact software computation in compute_guest_tsc()
2789 		 *
2790 		 * These values are tracked in kvm->arch.cur_xxx variables.
2791 		 */
2792 		kvm->arch.cur_tsc_generation++;
2793 		kvm->arch.cur_tsc_nsec = ns;
2794 		kvm->arch.cur_tsc_write = tsc;
2795 		kvm->arch.cur_tsc_offset = offset;
2796 		kvm->arch.nr_vcpus_matched_tsc = 0;
2797 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2798 		kvm->arch.nr_vcpus_matched_tsc++;
2799 	}
2800 
2801 	/* Keep track of which generation this VCPU has synchronized to */
2802 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2803 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2804 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2805 
2806 	kvm_track_tsc_matching(vcpu, !matched);
2807 }
2808 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2809 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2810 {
2811 	u64 data = user_value ? *user_value : 0;
2812 	struct kvm *kvm = vcpu->kvm;
2813 	u64 offset, ns, elapsed;
2814 	unsigned long flags;
2815 	bool matched = false;
2816 	bool synchronizing = false;
2817 
2818 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2819 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2820 	ns = get_kvmclock_base_ns();
2821 	elapsed = ns - kvm->arch.last_tsc_nsec;
2822 
2823 	if (vcpu->arch.virtual_tsc_khz) {
2824 		if (data == 0) {
2825 			/*
2826 			 * Force synchronization when creating a vCPU, or when
2827 			 * userspace explicitly writes a zero value.
2828 			 */
2829 			synchronizing = true;
2830 		} else if (kvm->arch.user_set_tsc) {
2831 			u64 tsc_exp = kvm->arch.last_tsc_write +
2832 						nsec_to_cycles(vcpu, elapsed);
2833 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2834 			/*
2835 			 * Here lies UAPI baggage: when a user-initiated TSC write has
2836 			 * a small delta (1 second) of virtual cycle time against the
2837 			 * previously set vCPU, we assume that they were intended to be
2838 			 * in sync and the delta was only due to the racy nature of the
2839 			 * legacy API.
2840 			 *
2841 			 * This trick falls down when restoring a guest which genuinely
2842 			 * has been running for less time than the 1 second of imprecision
2843 			 * which we allow for in the legacy API. In this case, the first
2844 			 * value written by userspace (on any vCPU) should not be subject
2845 			 * to this 'correction' to make it sync up with values that only
2846 			 * come from the kernel's default vCPU creation. Make the 1-second
2847 			 * slop hack only trigger if the user_set_tsc flag is already set.
2848 			 */
2849 			synchronizing = data < tsc_exp + tsc_hz &&
2850 					data + tsc_hz > tsc_exp;
2851 		}
2852 	}
2853 
2854 
2855 	/*
2856 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2857 	 * TSC, we add elapsed time in this computation.  We could let the
2858 	 * compensation code attempt to catch up if we fall behind, but
2859 	 * it's better to try to match offsets from the beginning.
2860          */
2861 	if (synchronizing &&
2862 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2863 		if (!kvm_check_tsc_unstable()) {
2864 			offset = kvm->arch.cur_tsc_offset;
2865 		} else {
2866 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2867 			data += delta;
2868 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2869 		}
2870 		matched = true;
2871 	}
2872 
2873 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2874 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2875 }
2876 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2877 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2878 					   s64 adjustment)
2879 {
2880 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2881 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2882 }
2883 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2884 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2885 {
2886 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2887 		WARN_ON(adjustment < 0);
2888 	adjustment = kvm_scale_tsc((u64) adjustment,
2889 				   vcpu->arch.l1_tsc_scaling_ratio);
2890 	adjust_tsc_offset_guest(vcpu, adjustment);
2891 }
2892 
2893 #ifdef CONFIG_X86_64
2894 
read_tsc(void)2895 static u64 read_tsc(void)
2896 {
2897 	u64 ret = (u64)rdtsc_ordered();
2898 	u64 last = pvclock_gtod_data.clock.cycle_last;
2899 
2900 	if (likely(ret >= last))
2901 		return ret;
2902 
2903 	/*
2904 	 * GCC likes to generate cmov here, but this branch is extremely
2905 	 * predictable (it's just a function of time and the likely is
2906 	 * very likely) and there's a data dependence, so force GCC
2907 	 * to generate a branch instead.  I don't barrier() because
2908 	 * we don't actually need a barrier, and if this function
2909 	 * ever gets inlined it will generate worse code.
2910 	 */
2911 	asm volatile ("");
2912 	return last;
2913 }
2914 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2915 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2916 			  int *mode)
2917 {
2918 	u64 tsc_pg_val;
2919 	long v;
2920 
2921 	switch (clock->vclock_mode) {
2922 	case VDSO_CLOCKMODE_HVCLOCK:
2923 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2924 					 tsc_timestamp, &tsc_pg_val)) {
2925 			/* TSC page valid */
2926 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2927 			v = (tsc_pg_val - clock->cycle_last) &
2928 				clock->mask;
2929 		} else {
2930 			/* TSC page invalid */
2931 			*mode = VDSO_CLOCKMODE_NONE;
2932 		}
2933 		break;
2934 	case VDSO_CLOCKMODE_TSC:
2935 		*mode = VDSO_CLOCKMODE_TSC;
2936 		*tsc_timestamp = read_tsc();
2937 		v = (*tsc_timestamp - clock->cycle_last) &
2938 			clock->mask;
2939 		break;
2940 	default:
2941 		*mode = VDSO_CLOCKMODE_NONE;
2942 	}
2943 
2944 	if (*mode == VDSO_CLOCKMODE_NONE)
2945 		*tsc_timestamp = v = 0;
2946 
2947 	return v * clock->mult;
2948 }
2949 
2950 /*
2951  * As with get_kvmclock_base_ns(), this counts from boot time, at the
2952  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2953  */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2954 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2955 {
2956 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2957 	unsigned long seq;
2958 	int mode;
2959 	u64 ns;
2960 
2961 	do {
2962 		seq = read_seqcount_begin(&gtod->seq);
2963 		ns = gtod->raw_clock.base_cycles;
2964 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2965 		ns >>= gtod->raw_clock.shift;
2966 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2967 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2968 	*t = ns;
2969 
2970 	return mode;
2971 }
2972 
2973 /*
2974  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2975  * no boot time offset.
2976  */
do_monotonic(s64 * t,u64 * tsc_timestamp)2977 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2978 {
2979 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2980 	unsigned long seq;
2981 	int mode;
2982 	u64 ns;
2983 
2984 	do {
2985 		seq = read_seqcount_begin(&gtod->seq);
2986 		ns = gtod->clock.base_cycles;
2987 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2988 		ns >>= gtod->clock.shift;
2989 		ns += ktime_to_ns(gtod->clock.offset);
2990 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2991 	*t = ns;
2992 
2993 	return mode;
2994 }
2995 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2996 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2997 {
2998 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2999 	unsigned long seq;
3000 	int mode;
3001 	u64 ns;
3002 
3003 	do {
3004 		seq = read_seqcount_begin(&gtod->seq);
3005 		ts->tv_sec = gtod->wall_time_sec;
3006 		ns = gtod->clock.base_cycles;
3007 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
3008 		ns >>= gtod->clock.shift;
3009 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
3010 
3011 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
3012 	ts->tv_nsec = ns;
3013 
3014 	return mode;
3015 }
3016 
3017 /*
3018  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
3019  * reports the TSC value from which it do so. Returns true if host is
3020  * using TSC based clocksource.
3021  */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3022 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3023 {
3024 	/* checked again under seqlock below */
3025 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3026 		return false;
3027 
3028 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
3029 						     tsc_timestamp));
3030 }
3031 
3032 /*
3033  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
3034  * so. Returns true if host is using TSC based clocksource.
3035  */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3036 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3037 {
3038 	/* checked again under seqlock below */
3039 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3040 		return false;
3041 
3042 	return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
3043 						 tsc_timestamp));
3044 }
3045 
3046 /*
3047  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
3048  * so. Returns true if host is using TSC based clocksource.
3049  *
3050  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
3051  * for that.
3052  */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)3053 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
3054 					   u64 *tsc_timestamp)
3055 {
3056 	/* checked again under seqlock below */
3057 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3058 		return false;
3059 
3060 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
3061 }
3062 #endif
3063 
3064 /*
3065  *
3066  * Assuming a stable TSC across physical CPUS, and a stable TSC
3067  * across virtual CPUs, the following condition is possible.
3068  * Each numbered line represents an event visible to both
3069  * CPUs at the next numbered event.
3070  *
3071  * "timespecX" represents host monotonic time. "tscX" represents
3072  * RDTSC value.
3073  *
3074  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
3075  *
3076  * 1.  read timespec0,tsc0
3077  * 2.					| timespec1 = timespec0 + N
3078  * 					| tsc1 = tsc0 + M
3079  * 3. transition to guest		| transition to guest
3080  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
3081  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
3082  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
3083  *
3084  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3085  *
3086  * 	- ret0 < ret1
3087  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3088  *		...
3089  *	- 0 < N - M => M < N
3090  *
3091  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3092  * always the case (the difference between two distinct xtime instances
3093  * might be smaller then the difference between corresponding TSC reads,
3094  * when updating guest vcpus pvclock areas).
3095  *
3096  * To avoid that problem, do not allow visibility of distinct
3097  * system_timestamp/tsc_timestamp values simultaneously: use a master
3098  * copy of host monotonic time values. Update that master copy
3099  * in lockstep.
3100  *
3101  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3102  *
3103  */
3104 
pvclock_update_vm_gtod_copy(struct kvm * kvm)3105 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3106 {
3107 #ifdef CONFIG_X86_64
3108 	struct kvm_arch *ka = &kvm->arch;
3109 	int vclock_mode;
3110 	bool host_tsc_clocksource, vcpus_matched;
3111 
3112 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
3113 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3114 			atomic_read(&kvm->online_vcpus));
3115 
3116 	/*
3117 	 * If the host uses TSC clock, then passthrough TSC as stable
3118 	 * to the guest.
3119 	 */
3120 	host_tsc_clocksource = kvm_get_time_and_clockread(
3121 					&ka->master_kernel_ns,
3122 					&ka->master_cycle_now);
3123 
3124 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3125 				&& !ka->backwards_tsc_observed
3126 				&& !ka->boot_vcpu_runs_old_kvmclock;
3127 
3128 	if (ka->use_master_clock)
3129 		atomic_set(&kvm_guest_has_master_clock, 1);
3130 
3131 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3132 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3133 					vcpus_matched);
3134 #endif
3135 }
3136 
kvm_make_mclock_inprogress_request(struct kvm * kvm)3137 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3138 {
3139 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3140 }
3141 
__kvm_start_pvclock_update(struct kvm * kvm)3142 static void __kvm_start_pvclock_update(struct kvm *kvm)
3143 {
3144 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3145 	write_seqcount_begin(&kvm->arch.pvclock_sc);
3146 }
3147 
kvm_start_pvclock_update(struct kvm * kvm)3148 static void kvm_start_pvclock_update(struct kvm *kvm)
3149 {
3150 	kvm_make_mclock_inprogress_request(kvm);
3151 
3152 	/* no guest entries from this point */
3153 	__kvm_start_pvclock_update(kvm);
3154 }
3155 
kvm_end_pvclock_update(struct kvm * kvm)3156 static void kvm_end_pvclock_update(struct kvm *kvm)
3157 {
3158 	struct kvm_arch *ka = &kvm->arch;
3159 	struct kvm_vcpu *vcpu;
3160 	unsigned long i;
3161 
3162 	write_seqcount_end(&ka->pvclock_sc);
3163 	raw_spin_unlock_irq(&ka->tsc_write_lock);
3164 	kvm_for_each_vcpu(i, vcpu, kvm)
3165 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3166 
3167 	/* guest entries allowed */
3168 	kvm_for_each_vcpu(i, vcpu, kvm)
3169 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3170 }
3171 
kvm_update_masterclock(struct kvm * kvm)3172 static void kvm_update_masterclock(struct kvm *kvm)
3173 {
3174 	kvm_hv_request_tsc_page_update(kvm);
3175 	kvm_start_pvclock_update(kvm);
3176 	pvclock_update_vm_gtod_copy(kvm);
3177 	kvm_end_pvclock_update(kvm);
3178 }
3179 
3180 /*
3181  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3182  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
3183  * can change during boot even if the TSC is constant, as it's possible for KVM
3184  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
3185  * notification when calibration completes, but practically speaking calibration
3186  * will complete before userspace is alive enough to create VMs.
3187  */
get_cpu_tsc_khz(void)3188 static unsigned long get_cpu_tsc_khz(void)
3189 {
3190 	if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3191 		return tsc_khz;
3192 	else
3193 		return __this_cpu_read(cpu_tsc_khz);
3194 }
3195 
3196 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3197 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3198 {
3199 	struct kvm_arch *ka = &kvm->arch;
3200 	struct pvclock_vcpu_time_info hv_clock;
3201 
3202 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
3203 	get_cpu();
3204 
3205 	data->flags = 0;
3206 	if (ka->use_master_clock &&
3207 	    (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3208 #ifdef CONFIG_X86_64
3209 		struct timespec64 ts;
3210 
3211 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3212 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3213 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3214 		} else
3215 #endif
3216 		data->host_tsc = rdtsc();
3217 
3218 		data->flags |= KVM_CLOCK_TSC_STABLE;
3219 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3220 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3221 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3222 				   &hv_clock.tsc_shift,
3223 				   &hv_clock.tsc_to_system_mul);
3224 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3225 	} else {
3226 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3227 	}
3228 
3229 	put_cpu();
3230 }
3231 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3232 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3233 {
3234 	struct kvm_arch *ka = &kvm->arch;
3235 	unsigned seq;
3236 
3237 	do {
3238 		seq = read_seqcount_begin(&ka->pvclock_sc);
3239 		__get_kvmclock(kvm, data);
3240 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3241 }
3242 
get_kvmclock_ns(struct kvm * kvm)3243 u64 get_kvmclock_ns(struct kvm *kvm)
3244 {
3245 	struct kvm_clock_data data;
3246 
3247 	get_kvmclock(kvm, &data);
3248 	return data.clock;
3249 }
3250 
kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info * ref_hv_clock,struct kvm_vcpu * vcpu,struct gfn_to_pfn_cache * gpc,unsigned int offset)3251 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3252 				    struct kvm_vcpu *vcpu,
3253 				    struct gfn_to_pfn_cache *gpc,
3254 				    unsigned int offset)
3255 {
3256 	struct pvclock_vcpu_time_info *guest_hv_clock;
3257 	struct pvclock_vcpu_time_info hv_clock;
3258 	unsigned long flags;
3259 
3260 	memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3261 
3262 	read_lock_irqsave(&gpc->lock, flags);
3263 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3264 		read_unlock_irqrestore(&gpc->lock, flags);
3265 
3266 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3267 			return;
3268 
3269 		read_lock_irqsave(&gpc->lock, flags);
3270 	}
3271 
3272 	guest_hv_clock = (void *)(gpc->khva + offset);
3273 
3274 	/*
3275 	 * This VCPU is paused, but it's legal for a guest to read another
3276 	 * VCPU's kvmclock, so we really have to follow the specification where
3277 	 * it says that version is odd if data is being modified, and even after
3278 	 * it is consistent.
3279 	 */
3280 
3281 	guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3282 	smp_wmb();
3283 
3284 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3285 	hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3286 
3287 	memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3288 
3289 	smp_wmb();
3290 
3291 	guest_hv_clock->version = ++hv_clock.version;
3292 
3293 	kvm_gpc_mark_dirty_in_slot(gpc);
3294 	read_unlock_irqrestore(&gpc->lock, flags);
3295 
3296 	trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3297 }
3298 
kvm_guest_time_update(struct kvm_vcpu * v)3299 int kvm_guest_time_update(struct kvm_vcpu *v)
3300 {
3301 	struct pvclock_vcpu_time_info hv_clock = {};
3302 	unsigned long flags, tgt_tsc_khz;
3303 	unsigned seq;
3304 	struct kvm_vcpu_arch *vcpu = &v->arch;
3305 	struct kvm_arch *ka = &v->kvm->arch;
3306 	s64 kernel_ns;
3307 	u64 tsc_timestamp, host_tsc;
3308 	bool use_master_clock;
3309 
3310 	kernel_ns = 0;
3311 	host_tsc = 0;
3312 
3313 	/*
3314 	 * If the host uses TSC clock, then passthrough TSC as stable
3315 	 * to the guest.
3316 	 */
3317 	do {
3318 		seq = read_seqcount_begin(&ka->pvclock_sc);
3319 		use_master_clock = ka->use_master_clock;
3320 		if (use_master_clock) {
3321 			host_tsc = ka->master_cycle_now;
3322 			kernel_ns = ka->master_kernel_ns;
3323 		}
3324 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3325 
3326 	/* Keep irq disabled to prevent changes to the clock */
3327 	local_irq_save(flags);
3328 	tgt_tsc_khz = get_cpu_tsc_khz();
3329 	if (unlikely(tgt_tsc_khz == 0)) {
3330 		local_irq_restore(flags);
3331 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3332 		return 1;
3333 	}
3334 	if (!use_master_clock) {
3335 		host_tsc = rdtsc();
3336 		kernel_ns = get_kvmclock_base_ns();
3337 	}
3338 
3339 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3340 
3341 	/*
3342 	 * We may have to catch up the TSC to match elapsed wall clock
3343 	 * time for two reasons, even if kvmclock is used.
3344 	 *   1) CPU could have been running below the maximum TSC rate
3345 	 *   2) Broken TSC compensation resets the base at each VCPU
3346 	 *      entry to avoid unknown leaps of TSC even when running
3347 	 *      again on the same CPU.  This may cause apparent elapsed
3348 	 *      time to disappear, and the guest to stand still or run
3349 	 *	very slowly.
3350 	 */
3351 	if (vcpu->tsc_catchup) {
3352 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3353 		if (tsc > tsc_timestamp) {
3354 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3355 			tsc_timestamp = tsc;
3356 		}
3357 	}
3358 
3359 	local_irq_restore(flags);
3360 
3361 	/* With all the info we got, fill in the values */
3362 
3363 	if (kvm_caps.has_tsc_control) {
3364 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3365 					    v->arch.l1_tsc_scaling_ratio);
3366 		tgt_tsc_khz = tgt_tsc_khz ? : 1;
3367 	}
3368 
3369 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3370 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3371 				   &vcpu->pvclock_tsc_shift,
3372 				   &vcpu->pvclock_tsc_mul);
3373 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3374 	}
3375 
3376 	hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3377 	hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3378 	hv_clock.tsc_timestamp = tsc_timestamp;
3379 	hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3380 	vcpu->last_guest_tsc = tsc_timestamp;
3381 
3382 	/* If the host uses TSC clocksource, then it is stable */
3383 	hv_clock.flags = 0;
3384 	if (use_master_clock)
3385 		hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3386 
3387 	if (vcpu->pv_time.active) {
3388 		/*
3389 		 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3390 		 * historic behavior is to only process the request if kvmclock
3391 		 * is active/enabled.
3392 		 */
3393 		if (vcpu->pvclock_set_guest_stopped_request) {
3394 			hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3395 			vcpu->pvclock_set_guest_stopped_request = false;
3396 		}
3397 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3398 
3399 		hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3400 	}
3401 
3402 	kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3403 
3404 #ifdef CONFIG_KVM_XEN
3405 	/*
3406 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3407 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3408 	 * This default behaviour led to bugs in some guest kernels which cause
3409 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3410 	 *
3411 	 * Note!  Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3412 	 */
3413 	if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3414 		hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3415 
3416 	if (vcpu->xen.vcpu_info_cache.active)
3417 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3418 					offsetof(struct compat_vcpu_info, time));
3419 	if (vcpu->xen.vcpu_time_info_cache.active)
3420 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3421 #endif
3422 	return 0;
3423 }
3424 
3425 /*
3426  * The pvclock_wall_clock ABI tells the guest the wall clock time at
3427  * which it started (i.e. its epoch, when its kvmclock was zero).
3428  *
3429  * In fact those clocks are subtly different; wall clock frequency is
3430  * adjusted by NTP and has leap seconds, while the kvmclock is a
3431  * simple function of the TSC without any such adjustment.
3432  *
3433  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3434  * that and kvmclock, but even that would be subject to change over
3435  * time.
3436  *
3437  * Attempt to calculate the epoch at a given moment using the *same*
3438  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3439  * wallclock and kvmclock times, and subtracting one from the other.
3440  *
3441  * Fall back to using their values at slightly different moments by
3442  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3443  */
kvm_get_wall_clock_epoch(struct kvm * kvm)3444 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3445 {
3446 #ifdef CONFIG_X86_64
3447 	struct pvclock_vcpu_time_info hv_clock;
3448 	struct kvm_arch *ka = &kvm->arch;
3449 	unsigned long seq, local_tsc_khz;
3450 	struct timespec64 ts;
3451 	uint64_t host_tsc;
3452 
3453 	do {
3454 		seq = read_seqcount_begin(&ka->pvclock_sc);
3455 
3456 		local_tsc_khz = 0;
3457 		if (!ka->use_master_clock)
3458 			break;
3459 
3460 		/*
3461 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
3462 		 * on the same CPU.
3463 		 */
3464 		get_cpu();
3465 
3466 		local_tsc_khz = get_cpu_tsc_khz();
3467 
3468 		if (local_tsc_khz &&
3469 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3470 			local_tsc_khz = 0; /* Fall back to old method */
3471 
3472 		put_cpu();
3473 
3474 		/*
3475 		 * These values must be snapshotted within the seqcount loop.
3476 		 * After that, it's just mathematics which can happen on any
3477 		 * CPU at any time.
3478 		 */
3479 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3480 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3481 
3482 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3483 
3484 	/*
3485 	 * If the conditions were right, and obtaining the wallclock+TSC was
3486 	 * successful, calculate the KVM clock at the corresponding time and
3487 	 * subtract one from the other to get the guest's epoch in nanoseconds
3488 	 * since 1970-01-01.
3489 	 */
3490 	if (local_tsc_khz) {
3491 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3492 				   &hv_clock.tsc_shift,
3493 				   &hv_clock.tsc_to_system_mul);
3494 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3495 			__pvclock_read_cycles(&hv_clock, host_tsc);
3496 	}
3497 #endif
3498 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3499 }
3500 
3501 /*
3502  * kvmclock updates which are isolated to a given vcpu, such as
3503  * vcpu->cpu migration, should not allow system_timestamp from
3504  * the rest of the vcpus to remain static.
3505  *
3506  * So in those cases, request a kvmclock update for all vcpus.
3507  * The worst case for a remote vcpu to update its kvmclock
3508  * is then bounded by maximum nohz sleep latency.
3509  */
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3510 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3511 {
3512 	unsigned long i;
3513 	struct kvm_vcpu *vcpu;
3514 	struct kvm *kvm = v->kvm;
3515 
3516 	kvm_for_each_vcpu(i, vcpu, kvm) {
3517 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3518 		kvm_vcpu_kick(vcpu);
3519 	}
3520 }
3521 
3522 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3523 static bool is_mci_control_msr(u32 msr)
3524 {
3525 	return (msr & 3) == 0;
3526 }
is_mci_status_msr(u32 msr)3527 static bool is_mci_status_msr(u32 msr)
3528 {
3529 	return (msr & 3) == 1;
3530 }
3531 
3532 /*
3533  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3534  */
can_set_mci_status(struct kvm_vcpu * vcpu)3535 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3536 {
3537 	/* McStatusWrEn enabled? */
3538 	if (guest_cpuid_is_amd_compatible(vcpu))
3539 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3540 
3541 	return false;
3542 }
3543 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3544 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3545 {
3546 	u64 mcg_cap = vcpu->arch.mcg_cap;
3547 	unsigned bank_num = mcg_cap & 0xff;
3548 	u32 msr = msr_info->index;
3549 	u64 data = msr_info->data;
3550 	u32 offset, last_msr;
3551 
3552 	switch (msr) {
3553 	case MSR_IA32_MCG_STATUS:
3554 		vcpu->arch.mcg_status = data;
3555 		break;
3556 	case MSR_IA32_MCG_CTL:
3557 		if (!(mcg_cap & MCG_CTL_P) &&
3558 		    (data || !msr_info->host_initiated))
3559 			return 1;
3560 		if (data != 0 && data != ~(u64)0)
3561 			return 1;
3562 		vcpu->arch.mcg_ctl = data;
3563 		break;
3564 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3565 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3566 		if (msr > last_msr)
3567 			return 1;
3568 
3569 		if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3570 			return 1;
3571 		/* An attempt to write a 1 to a reserved bit raises #GP */
3572 		if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3573 			return 1;
3574 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3575 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
3576 		vcpu->arch.mci_ctl2_banks[offset] = data;
3577 		break;
3578 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3579 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3580 		if (msr > last_msr)
3581 			return 1;
3582 
3583 		/*
3584 		 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3585 		 * values are architecturally undefined.  But, some Linux
3586 		 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3587 		 * issue on AMD K8s, allow bit 10 to be clear when setting all
3588 		 * other bits in order to avoid an uncaught #GP in the guest.
3589 		 *
3590 		 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3591 		 * single-bit ECC data errors.
3592 		 */
3593 		if (is_mci_control_msr(msr) &&
3594 		    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3595 			return 1;
3596 
3597 		/*
3598 		 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3599 		 * AMD-based CPUs allow non-zero values, but if and only if
3600 		 * HWCR[McStatusWrEn] is set.
3601 		 */
3602 		if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3603 		    data != 0 && !can_set_mci_status(vcpu))
3604 			return 1;
3605 
3606 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3607 					    last_msr + 1 - MSR_IA32_MC0_CTL);
3608 		vcpu->arch.mce_banks[offset] = data;
3609 		break;
3610 	default:
3611 		return 1;
3612 	}
3613 	return 0;
3614 }
3615 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3616 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3617 {
3618 	gpa_t gpa = data & ~0x3f;
3619 
3620 	/* Bits 4:5 are reserved, Should be zero */
3621 	if (data & 0x30)
3622 		return 1;
3623 
3624 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3625 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3626 		return 1;
3627 
3628 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3629 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3630 		return 1;
3631 
3632 	if (!lapic_in_kernel(vcpu))
3633 		return data ? 1 : 0;
3634 
3635 	vcpu->arch.apf.msr_en_val = data;
3636 
3637 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3638 		kvm_clear_async_pf_completion_queue(vcpu);
3639 		kvm_async_pf_hash_reset(vcpu);
3640 		return 0;
3641 	}
3642 
3643 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3644 					sizeof(u64)))
3645 		return 1;
3646 
3647 	vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3648 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3649 
3650 	kvm_async_pf_wakeup_all(vcpu);
3651 
3652 	return 0;
3653 }
3654 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3655 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3656 {
3657 	/* Bits 8-63 are reserved */
3658 	if (data >> 8)
3659 		return 1;
3660 
3661 	if (!lapic_in_kernel(vcpu))
3662 		return 1;
3663 
3664 	vcpu->arch.apf.msr_int_val = data;
3665 
3666 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3667 
3668 	return 0;
3669 }
3670 
kvmclock_reset(struct kvm_vcpu * vcpu)3671 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3672 {
3673 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
3674 	vcpu->arch.time = 0;
3675 }
3676 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3677 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3678 {
3679 	++vcpu->stat.tlb_flush;
3680 	kvm_x86_call(flush_tlb_all)(vcpu);
3681 
3682 	/* Flushing all ASIDs flushes the current ASID... */
3683 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3684 }
3685 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3686 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3687 {
3688 	++vcpu->stat.tlb_flush;
3689 
3690 	if (!tdp_enabled) {
3691 		/*
3692 		 * A TLB flush on behalf of the guest is equivalent to
3693 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3694 		 * a forced sync of the shadow page tables.  Ensure all the
3695 		 * roots are synced and the guest TLB in hardware is clean.
3696 		 */
3697 		kvm_mmu_sync_roots(vcpu);
3698 		kvm_mmu_sync_prev_roots(vcpu);
3699 	}
3700 
3701 	kvm_x86_call(flush_tlb_guest)(vcpu);
3702 
3703 	/*
3704 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3705 	 * grained flushing.
3706 	 */
3707 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
3708 }
3709 
3710 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3711 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3712 {
3713 	++vcpu->stat.tlb_flush;
3714 	kvm_x86_call(flush_tlb_current)(vcpu);
3715 }
3716 
3717 /*
3718  * Service "local" TLB flush requests, which are specific to the current MMU
3719  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3720  * TLB flushes that are targeted at an MMU context also need to be serviced
3721  * prior before nested VM-Enter/VM-Exit.
3722  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3723 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3724 {
3725 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3726 		kvm_vcpu_flush_tlb_current(vcpu);
3727 
3728 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3729 		kvm_vcpu_flush_tlb_guest(vcpu);
3730 }
3731 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
3732 
record_steal_time(struct kvm_vcpu * vcpu)3733 static void record_steal_time(struct kvm_vcpu *vcpu)
3734 {
3735 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3736 	struct kvm_steal_time __user *st;
3737 	struct kvm_memslots *slots;
3738 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3739 	u64 steal;
3740 	u32 version;
3741 
3742 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3743 		kvm_xen_runstate_set_running(vcpu);
3744 		return;
3745 	}
3746 
3747 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3748 		return;
3749 
3750 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3751 		return;
3752 
3753 	slots = kvm_memslots(vcpu->kvm);
3754 
3755 	if (unlikely(slots->generation != ghc->generation ||
3756 		     gpa != ghc->gpa ||
3757 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3758 		/* We rely on the fact that it fits in a single page. */
3759 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3760 
3761 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3762 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3763 			return;
3764 	}
3765 
3766 	st = (struct kvm_steal_time __user *)ghc->hva;
3767 	/*
3768 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3769 	 * expensive IPIs.
3770 	 */
3771 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3772 		u8 st_preempted = 0;
3773 		int err = -EFAULT;
3774 
3775 		if (!user_access_begin(st, sizeof(*st)))
3776 			return;
3777 
3778 		asm volatile("1: xchgb %0, %2\n"
3779 			     "xor %1, %1\n"
3780 			     "2:\n"
3781 			     _ASM_EXTABLE_UA(1b, 2b)
3782 			     : "+q" (st_preempted),
3783 			       "+&r" (err),
3784 			       "+m" (st->preempted));
3785 		if (err)
3786 			goto out;
3787 
3788 		user_access_end();
3789 
3790 		vcpu->arch.st.preempted = 0;
3791 
3792 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3793 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3794 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3795 			kvm_vcpu_flush_tlb_guest(vcpu);
3796 
3797 		if (!user_access_begin(st, sizeof(*st)))
3798 			goto dirty;
3799 	} else {
3800 		if (!user_access_begin(st, sizeof(*st)))
3801 			return;
3802 
3803 		unsafe_put_user(0, &st->preempted, out);
3804 		vcpu->arch.st.preempted = 0;
3805 	}
3806 
3807 	unsafe_get_user(version, &st->version, out);
3808 	if (version & 1)
3809 		version += 1;  /* first time write, random junk */
3810 
3811 	version += 1;
3812 	unsafe_put_user(version, &st->version, out);
3813 
3814 	smp_wmb();
3815 
3816 	unsafe_get_user(steal, &st->steal, out);
3817 	steal += current->sched_info.run_delay -
3818 		vcpu->arch.st.last_steal;
3819 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3820 	unsafe_put_user(steal, &st->steal, out);
3821 
3822 	version += 1;
3823 	unsafe_put_user(version, &st->version, out);
3824 
3825  out:
3826 	user_access_end();
3827  dirty:
3828 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3829 }
3830 
3831 /*
3832  * Returns true if the MSR in question is managed via XSTATE, i.e. is context
3833  * switched with the rest of guest FPU state.
3834  *
3835  * Note, S_CET is _not_ saved/restored via XSAVES/XRSTORS.
3836  */
is_xstate_managed_msr(struct kvm_vcpu * vcpu,u32 msr)3837 static bool is_xstate_managed_msr(struct kvm_vcpu *vcpu, u32 msr)
3838 {
3839 	if (!vcpu)
3840 		return false;
3841 
3842 	switch (msr) {
3843 	case MSR_IA32_U_CET:
3844 		return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ||
3845 		       guest_cpu_cap_has(vcpu, X86_FEATURE_IBT);
3846 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
3847 		return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
3848 	default:
3849 		return false;
3850 	}
3851 }
3852 
3853 /*
3854  * Lock (and if necessary, re-load) the guest FPU, i.e. XSTATE, and access an
3855  * MSR that is managed via XSTATE.  Note, the caller is responsible for doing
3856  * the initial FPU load, this helper only ensures that guest state is resident
3857  * in hardware (the kernel can load its FPU state in IRQ context).
3858  *
3859  * Note, loading guest values for U_CET and PL[0-3]_SSP while executing in the
3860  * kernel is safe, as U_CET is specific to userspace, and PL[0-3]_SSP are only
3861  * consumed when transitioning to lower privilege levels, i.e. are effectively
3862  * only consumed by userspace as well.
3863  */
kvm_access_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info,int access)3864 static __always_inline void kvm_access_xstate_msr(struct kvm_vcpu *vcpu,
3865 						  struct msr_data *msr_info,
3866 						  int access)
3867 {
3868 	BUILD_BUG_ON(access != MSR_TYPE_R && access != MSR_TYPE_W);
3869 
3870 	KVM_BUG_ON(!is_xstate_managed_msr(vcpu, msr_info->index), vcpu->kvm);
3871 	KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm);
3872 
3873 	kvm_fpu_get();
3874 	if (access == MSR_TYPE_R)
3875 		rdmsrq(msr_info->index, msr_info->data);
3876 	else
3877 		wrmsrq(msr_info->index, msr_info->data);
3878 	kvm_fpu_put();
3879 }
3880 
kvm_set_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3881 static void kvm_set_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3882 {
3883 	kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_W);
3884 }
3885 
kvm_get_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3886 static void kvm_get_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3887 {
3888 	kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_R);
3889 }
3890 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3891 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3892 {
3893 	u32 msr = msr_info->index;
3894 	u64 data = msr_info->data;
3895 
3896 	/*
3897 	 * Do not allow host-initiated writes to trigger the Xen hypercall
3898 	 * page setup; it could incur locking paths which are not expected
3899 	 * if userspace sets the MSR in an unusual location.
3900 	 */
3901 	if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3902 	    !msr_info->host_initiated)
3903 		return kvm_xen_write_hypercall_page(vcpu, data);
3904 
3905 	switch (msr) {
3906 	case MSR_AMD64_NB_CFG:
3907 	case MSR_IA32_UCODE_WRITE:
3908 	case MSR_VM_HSAVE_PA:
3909 	case MSR_AMD64_PATCH_LOADER:
3910 	case MSR_AMD64_BU_CFG2:
3911 	case MSR_AMD64_DC_CFG:
3912 	case MSR_AMD64_TW_CFG:
3913 	case MSR_F15H_EX_CFG:
3914 		break;
3915 
3916 	case MSR_IA32_UCODE_REV:
3917 		if (msr_info->host_initiated)
3918 			vcpu->arch.microcode_version = data;
3919 		break;
3920 	case MSR_IA32_ARCH_CAPABILITIES:
3921 		if (!msr_info->host_initiated ||
3922 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3923 			return KVM_MSR_RET_UNSUPPORTED;
3924 		vcpu->arch.arch_capabilities = data;
3925 		break;
3926 	case MSR_IA32_PERF_CAPABILITIES:
3927 		if (!msr_info->host_initiated ||
3928 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3929 			return KVM_MSR_RET_UNSUPPORTED;
3930 
3931 		if (data & ~kvm_caps.supported_perf_cap)
3932 			return 1;
3933 
3934 		/*
3935 		 * Note, this is not just a performance optimization!  KVM
3936 		 * disallows changing feature MSRs after the vCPU has run; PMU
3937 		 * refresh will bug the VM if called after the vCPU has run.
3938 		 */
3939 		if (vcpu->arch.perf_capabilities == data)
3940 			break;
3941 
3942 		vcpu->arch.perf_capabilities = data;
3943 		kvm_pmu_refresh(vcpu);
3944 		break;
3945 	case MSR_IA32_PRED_CMD: {
3946 		u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3947 
3948 		if (!msr_info->host_initiated) {
3949 			if ((!guest_has_pred_cmd_msr(vcpu)))
3950 				return 1;
3951 
3952 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3953 			    !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3954 				reserved_bits |= PRED_CMD_IBPB;
3955 
3956 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3957 				reserved_bits |= PRED_CMD_SBPB;
3958 		}
3959 
3960 		if (!boot_cpu_has(X86_FEATURE_IBPB))
3961 			reserved_bits |= PRED_CMD_IBPB;
3962 
3963 		if (!boot_cpu_has(X86_FEATURE_SBPB))
3964 			reserved_bits |= PRED_CMD_SBPB;
3965 
3966 		if (data & reserved_bits)
3967 			return 1;
3968 
3969 		if (!data)
3970 			break;
3971 
3972 		wrmsrq(MSR_IA32_PRED_CMD, data);
3973 		break;
3974 	}
3975 	case MSR_IA32_FLUSH_CMD:
3976 		if (!msr_info->host_initiated &&
3977 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3978 			return 1;
3979 
3980 		if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3981 			return 1;
3982 		if (!data)
3983 			break;
3984 
3985 		wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3986 		break;
3987 	case MSR_EFER:
3988 		return set_efer(vcpu, msr_info);
3989 	case MSR_K7_HWCR:
3990 		data &= ~(u64)0x40;	/* ignore flush filter disable */
3991 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
3992 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
3993 
3994 		/*
3995 		 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3996 		 * through at least v6.6 whine if TscFreqSel is clear,
3997 		 * depending on F/M/S.
3998 		 */
3999 		if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
4000 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4001 			return 1;
4002 		}
4003 		vcpu->arch.msr_hwcr = data;
4004 		break;
4005 	case MSR_FAM10H_MMIO_CONF_BASE:
4006 		if (data != 0) {
4007 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4008 			return 1;
4009 		}
4010 		break;
4011 	case MSR_IA32_CR_PAT:
4012 		if (!kvm_pat_valid(data))
4013 			return 1;
4014 
4015 		vcpu->arch.pat = data;
4016 		break;
4017 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4018 	case MSR_MTRRdefType:
4019 		return kvm_mtrr_set_msr(vcpu, msr, data);
4020 	case MSR_IA32_APICBASE:
4021 		return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
4022 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4023 		return kvm_x2apic_msr_write(vcpu, msr, data);
4024 	case MSR_IA32_TSC_DEADLINE:
4025 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
4026 		break;
4027 	case MSR_IA32_TSC_ADJUST:
4028 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
4029 			if (!msr_info->host_initiated) {
4030 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
4031 				adjust_tsc_offset_guest(vcpu, adj);
4032 				/* Before back to guest, tsc_timestamp must be adjusted
4033 				 * as well, otherwise guest's percpu pvclock time could jump.
4034 				 */
4035 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4036 			}
4037 			vcpu->arch.ia32_tsc_adjust_msr = data;
4038 		}
4039 		break;
4040 	case MSR_IA32_MISC_ENABLE: {
4041 		u64 old_val = vcpu->arch.ia32_misc_enable_msr;
4042 
4043 		if (!msr_info->host_initiated) {
4044 			/* RO bits */
4045 			if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
4046 				return 1;
4047 
4048 			/* R bits, i.e. writes are ignored, but don't fault. */
4049 			data = data & ~MSR_IA32_MISC_ENABLE_EMON;
4050 			data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
4051 		}
4052 
4053 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
4054 		    ((old_val ^ data)  & MSR_IA32_MISC_ENABLE_MWAIT)) {
4055 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
4056 				return 1;
4057 			vcpu->arch.ia32_misc_enable_msr = data;
4058 			vcpu->arch.cpuid_dynamic_bits_dirty = true;
4059 		} else {
4060 			vcpu->arch.ia32_misc_enable_msr = data;
4061 		}
4062 		break;
4063 	}
4064 	case MSR_IA32_SMBASE:
4065 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4066 			return 1;
4067 		vcpu->arch.smbase = data;
4068 		break;
4069 	case MSR_IA32_POWER_CTL:
4070 		vcpu->arch.msr_ia32_power_ctl = data;
4071 		break;
4072 	case MSR_IA32_TSC:
4073 		if (msr_info->host_initiated) {
4074 			kvm_synchronize_tsc(vcpu, &data);
4075 		} else if (!vcpu->arch.guest_tsc_protected) {
4076 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
4077 			adjust_tsc_offset_guest(vcpu, adj);
4078 			vcpu->arch.ia32_tsc_adjust_msr += adj;
4079 		}
4080 		break;
4081 	case MSR_IA32_XSS:
4082 		if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4083 			return KVM_MSR_RET_UNSUPPORTED;
4084 
4085 		if (data & ~vcpu->arch.guest_supported_xss)
4086 			return 1;
4087 		if (vcpu->arch.ia32_xss == data)
4088 			break;
4089 		vcpu->arch.ia32_xss = data;
4090 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
4091 		break;
4092 	case MSR_SMI_COUNT:
4093 		if (!msr_info->host_initiated)
4094 			return 1;
4095 		vcpu->arch.smi_count = data;
4096 		break;
4097 	case MSR_KVM_WALL_CLOCK_NEW:
4098 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4099 			return 1;
4100 
4101 		vcpu->kvm->arch.wall_clock = data;
4102 		kvm_write_wall_clock(vcpu->kvm, data, 0);
4103 		break;
4104 	case MSR_KVM_WALL_CLOCK:
4105 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4106 			return 1;
4107 
4108 		vcpu->kvm->arch.wall_clock = data;
4109 		kvm_write_wall_clock(vcpu->kvm, data, 0);
4110 		break;
4111 	case MSR_KVM_SYSTEM_TIME_NEW:
4112 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4113 			return 1;
4114 
4115 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4116 		break;
4117 	case MSR_KVM_SYSTEM_TIME:
4118 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4119 			return 1;
4120 
4121 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
4122 		break;
4123 	case MSR_KVM_ASYNC_PF_EN:
4124 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4125 			return 1;
4126 
4127 		if (kvm_pv_enable_async_pf(vcpu, data))
4128 			return 1;
4129 		break;
4130 	case MSR_KVM_ASYNC_PF_INT:
4131 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4132 			return 1;
4133 
4134 		if (kvm_pv_enable_async_pf_int(vcpu, data))
4135 			return 1;
4136 		break;
4137 	case MSR_KVM_ASYNC_PF_ACK:
4138 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4139 			return 1;
4140 		if (data & 0x1) {
4141 			/*
4142 			 * Pairs with the smp_mb__after_atomic() in
4143 			 * kvm_arch_async_page_present_queued().
4144 			 */
4145 			smp_store_mb(vcpu->arch.apf.pageready_pending, false);
4146 
4147 			kvm_check_async_pf_completion(vcpu);
4148 		}
4149 		break;
4150 	case MSR_KVM_STEAL_TIME:
4151 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4152 			return 1;
4153 
4154 		if (unlikely(!sched_info_on()))
4155 			return 1;
4156 
4157 		if (data & KVM_STEAL_RESERVED_MASK)
4158 			return 1;
4159 
4160 		vcpu->arch.st.msr_val = data;
4161 
4162 		if (!(data & KVM_MSR_ENABLED))
4163 			break;
4164 
4165 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4166 
4167 		break;
4168 	case MSR_KVM_PV_EOI_EN:
4169 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4170 			return 1;
4171 
4172 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4173 			return 1;
4174 		break;
4175 
4176 	case MSR_KVM_POLL_CONTROL:
4177 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4178 			return 1;
4179 
4180 		/* only enable bit supported */
4181 		if (data & (-1ULL << 1))
4182 			return 1;
4183 
4184 		vcpu->arch.msr_kvm_poll_control = data;
4185 		break;
4186 
4187 	case MSR_IA32_MCG_CTL:
4188 	case MSR_IA32_MCG_STATUS:
4189 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4190 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4191 		return set_msr_mce(vcpu, msr_info);
4192 
4193 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4194 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4195 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4196 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4197 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4198 			return kvm_pmu_set_msr(vcpu, msr_info);
4199 
4200 		if (data)
4201 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4202 		break;
4203 	case MSR_K7_CLK_CTL:
4204 		/*
4205 		 * Ignore all writes to this no longer documented MSR.
4206 		 * Writes are only relevant for old K7 processors,
4207 		 * all pre-dating SVM, but a recommended workaround from
4208 		 * AMD for these chips. It is possible to specify the
4209 		 * affected processor models on the command line, hence
4210 		 * the need to ignore the workaround.
4211 		 */
4212 		break;
4213 #ifdef CONFIG_KVM_HYPERV
4214 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4215 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4216 	case HV_X64_MSR_SYNDBG_OPTIONS:
4217 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4218 	case HV_X64_MSR_CRASH_CTL:
4219 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4220 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4221 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4222 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4223 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4224 		return kvm_hv_set_msr_common(vcpu, msr, data,
4225 					     msr_info->host_initiated);
4226 #endif
4227 	case MSR_IA32_BBL_CR_CTL3:
4228 		/* Drop writes to this legacy MSR -- see rdmsr
4229 		 * counterpart for further detail.
4230 		 */
4231 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4232 		break;
4233 	case MSR_AMD64_OSVW_ID_LENGTH:
4234 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4235 			return 1;
4236 		vcpu->arch.osvw.length = data;
4237 		break;
4238 	case MSR_AMD64_OSVW_STATUS:
4239 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4240 			return 1;
4241 		vcpu->arch.osvw.status = data;
4242 		break;
4243 	case MSR_PLATFORM_INFO:
4244 		if (!msr_info->host_initiated)
4245 			return 1;
4246 		vcpu->arch.msr_platform_info = data;
4247 		break;
4248 	case MSR_MISC_FEATURES_ENABLES:
4249 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4250 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4251 		     !supports_cpuid_fault(vcpu)))
4252 			return 1;
4253 		vcpu->arch.msr_misc_features_enables = data;
4254 		break;
4255 #ifdef CONFIG_X86_64
4256 	case MSR_IA32_XFD:
4257 		if (!msr_info->host_initiated &&
4258 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4259 			return 1;
4260 
4261 		if (data & ~kvm_guest_supported_xfd(vcpu))
4262 			return 1;
4263 
4264 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4265 		break;
4266 	case MSR_IA32_XFD_ERR:
4267 		if (!msr_info->host_initiated &&
4268 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4269 			return 1;
4270 
4271 		if (data & ~kvm_guest_supported_xfd(vcpu))
4272 			return 1;
4273 
4274 		vcpu->arch.guest_fpu.xfd_err = data;
4275 		break;
4276 #endif
4277 	case MSR_IA32_U_CET:
4278 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4279 		kvm_set_xstate_msr(vcpu, msr_info);
4280 		break;
4281 	default:
4282 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4283 			return kvm_pmu_set_msr(vcpu, msr_info);
4284 
4285 		return KVM_MSR_RET_UNSUPPORTED;
4286 	}
4287 	return 0;
4288 }
4289 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_msr_common);
4290 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4291 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4292 {
4293 	u64 data;
4294 	u64 mcg_cap = vcpu->arch.mcg_cap;
4295 	unsigned bank_num = mcg_cap & 0xff;
4296 	u32 offset, last_msr;
4297 
4298 	switch (msr) {
4299 	case MSR_IA32_P5_MC_ADDR:
4300 	case MSR_IA32_P5_MC_TYPE:
4301 		data = 0;
4302 		break;
4303 	case MSR_IA32_MCG_CAP:
4304 		data = vcpu->arch.mcg_cap;
4305 		break;
4306 	case MSR_IA32_MCG_CTL:
4307 		if (!(mcg_cap & MCG_CTL_P) && !host)
4308 			return 1;
4309 		data = vcpu->arch.mcg_ctl;
4310 		break;
4311 	case MSR_IA32_MCG_STATUS:
4312 		data = vcpu->arch.mcg_status;
4313 		break;
4314 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4315 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4316 		if (msr > last_msr)
4317 			return 1;
4318 
4319 		if (!(mcg_cap & MCG_CMCI_P) && !host)
4320 			return 1;
4321 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4322 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
4323 		data = vcpu->arch.mci_ctl2_banks[offset];
4324 		break;
4325 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4326 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4327 		if (msr > last_msr)
4328 			return 1;
4329 
4330 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4331 					    last_msr + 1 - MSR_IA32_MC0_CTL);
4332 		data = vcpu->arch.mce_banks[offset];
4333 		break;
4334 	default:
4335 		return 1;
4336 	}
4337 	*pdata = data;
4338 	return 0;
4339 }
4340 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4341 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4342 {
4343 	switch (msr_info->index) {
4344 	case MSR_IA32_PLATFORM_ID:
4345 	case MSR_IA32_EBL_CR_POWERON:
4346 	case MSR_IA32_LASTBRANCHFROMIP:
4347 	case MSR_IA32_LASTBRANCHTOIP:
4348 	case MSR_IA32_LASTINTFROMIP:
4349 	case MSR_IA32_LASTINTTOIP:
4350 	case MSR_AMD64_SYSCFG:
4351 	case MSR_K8_TSEG_ADDR:
4352 	case MSR_K8_TSEG_MASK:
4353 	case MSR_VM_HSAVE_PA:
4354 	case MSR_K8_INT_PENDING_MSG:
4355 	case MSR_AMD64_NB_CFG:
4356 	case MSR_FAM10H_MMIO_CONF_BASE:
4357 	case MSR_AMD64_BU_CFG2:
4358 	case MSR_IA32_PERF_CTL:
4359 	case MSR_AMD64_DC_CFG:
4360 	case MSR_AMD64_TW_CFG:
4361 	case MSR_F15H_EX_CFG:
4362 	/*
4363 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4364 	 * limit) MSRs. Just return 0, as we do not want to expose the host
4365 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
4366 	 * so for existing CPU-specific MSRs.
4367 	 */
4368 	case MSR_RAPL_POWER_UNIT:
4369 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
4370 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
4371 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
4372 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
4373 		msr_info->data = 0;
4374 		break;
4375 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4376 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4377 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4378 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4379 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4380 			return kvm_pmu_get_msr(vcpu, msr_info);
4381 		msr_info->data = 0;
4382 		break;
4383 	case MSR_IA32_UCODE_REV:
4384 		msr_info->data = vcpu->arch.microcode_version;
4385 		break;
4386 	case MSR_IA32_ARCH_CAPABILITIES:
4387 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4388 			return KVM_MSR_RET_UNSUPPORTED;
4389 		msr_info->data = vcpu->arch.arch_capabilities;
4390 		break;
4391 	case MSR_IA32_PERF_CAPABILITIES:
4392 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4393 			return KVM_MSR_RET_UNSUPPORTED;
4394 		msr_info->data = vcpu->arch.perf_capabilities;
4395 		break;
4396 	case MSR_IA32_POWER_CTL:
4397 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4398 		break;
4399 	case MSR_IA32_TSC: {
4400 		/*
4401 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4402 		 * even when not intercepted. AMD manual doesn't explicitly
4403 		 * state this but appears to behave the same.
4404 		 *
4405 		 * On userspace reads and writes, however, we unconditionally
4406 		 * return L1's TSC value to ensure backwards-compatible
4407 		 * behavior for migration.
4408 		 */
4409 		u64 offset, ratio;
4410 
4411 		if (msr_info->host_initiated) {
4412 			offset = vcpu->arch.l1_tsc_offset;
4413 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
4414 		} else {
4415 			offset = vcpu->arch.tsc_offset;
4416 			ratio = vcpu->arch.tsc_scaling_ratio;
4417 		}
4418 
4419 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4420 		break;
4421 	}
4422 	case MSR_IA32_CR_PAT:
4423 		msr_info->data = vcpu->arch.pat;
4424 		break;
4425 	case MSR_MTRRcap:
4426 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4427 	case MSR_MTRRdefType:
4428 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4429 	case 0xcd: /* fsb frequency */
4430 		msr_info->data = 3;
4431 		break;
4432 		/*
4433 		 * MSR_EBC_FREQUENCY_ID
4434 		 * Conservative value valid for even the basic CPU models.
4435 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4436 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4437 		 * and 266MHz for model 3, or 4. Set Core Clock
4438 		 * Frequency to System Bus Frequency Ratio to 1 (bits
4439 		 * 31:24) even though these are only valid for CPU
4440 		 * models > 2, however guests may end up dividing or
4441 		 * multiplying by zero otherwise.
4442 		 */
4443 	case MSR_EBC_FREQUENCY_ID:
4444 		msr_info->data = 1 << 24;
4445 		break;
4446 	case MSR_IA32_APICBASE:
4447 		msr_info->data = vcpu->arch.apic_base;
4448 		break;
4449 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4450 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4451 	case MSR_IA32_TSC_DEADLINE:
4452 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4453 		break;
4454 	case MSR_IA32_TSC_ADJUST:
4455 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4456 		break;
4457 	case MSR_IA32_MISC_ENABLE:
4458 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4459 		break;
4460 	case MSR_IA32_SMBASE:
4461 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4462 			return 1;
4463 		msr_info->data = vcpu->arch.smbase;
4464 		break;
4465 	case MSR_SMI_COUNT:
4466 		msr_info->data = vcpu->arch.smi_count;
4467 		break;
4468 	case MSR_IA32_PERF_STATUS:
4469 		/* TSC increment by tick */
4470 		msr_info->data = 1000ULL;
4471 		/* CPU multiplier */
4472 		msr_info->data |= (((uint64_t)4ULL) << 40);
4473 		break;
4474 	case MSR_EFER:
4475 		msr_info->data = vcpu->arch.efer;
4476 		break;
4477 	case MSR_KVM_WALL_CLOCK:
4478 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4479 			return 1;
4480 
4481 		msr_info->data = vcpu->kvm->arch.wall_clock;
4482 		break;
4483 	case MSR_KVM_WALL_CLOCK_NEW:
4484 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4485 			return 1;
4486 
4487 		msr_info->data = vcpu->kvm->arch.wall_clock;
4488 		break;
4489 	case MSR_KVM_SYSTEM_TIME:
4490 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4491 			return 1;
4492 
4493 		msr_info->data = vcpu->arch.time;
4494 		break;
4495 	case MSR_KVM_SYSTEM_TIME_NEW:
4496 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4497 			return 1;
4498 
4499 		msr_info->data = vcpu->arch.time;
4500 		break;
4501 	case MSR_KVM_ASYNC_PF_EN:
4502 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4503 			return 1;
4504 
4505 		msr_info->data = vcpu->arch.apf.msr_en_val;
4506 		break;
4507 	case MSR_KVM_ASYNC_PF_INT:
4508 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4509 			return 1;
4510 
4511 		msr_info->data = vcpu->arch.apf.msr_int_val;
4512 		break;
4513 	case MSR_KVM_ASYNC_PF_ACK:
4514 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4515 			return 1;
4516 
4517 		msr_info->data = 0;
4518 		break;
4519 	case MSR_KVM_STEAL_TIME:
4520 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4521 			return 1;
4522 
4523 		msr_info->data = vcpu->arch.st.msr_val;
4524 		break;
4525 	case MSR_KVM_PV_EOI_EN:
4526 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4527 			return 1;
4528 
4529 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4530 		break;
4531 	case MSR_KVM_POLL_CONTROL:
4532 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4533 			return 1;
4534 
4535 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4536 		break;
4537 	case MSR_IA32_P5_MC_ADDR:
4538 	case MSR_IA32_P5_MC_TYPE:
4539 	case MSR_IA32_MCG_CAP:
4540 	case MSR_IA32_MCG_CTL:
4541 	case MSR_IA32_MCG_STATUS:
4542 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4543 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4544 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4545 				   msr_info->host_initiated);
4546 	case MSR_IA32_XSS:
4547 		if (!msr_info->host_initiated &&
4548 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4549 			return 1;
4550 		msr_info->data = vcpu->arch.ia32_xss;
4551 		break;
4552 	case MSR_K7_CLK_CTL:
4553 		/*
4554 		 * Provide expected ramp-up count for K7. All other
4555 		 * are set to zero, indicating minimum divisors for
4556 		 * every field.
4557 		 *
4558 		 * This prevents guest kernels on AMD host with CPU
4559 		 * type 6, model 8 and higher from exploding due to
4560 		 * the rdmsr failing.
4561 		 */
4562 		msr_info->data = 0x20000000;
4563 		break;
4564 #ifdef CONFIG_KVM_HYPERV
4565 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4566 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4567 	case HV_X64_MSR_SYNDBG_OPTIONS:
4568 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4569 	case HV_X64_MSR_CRASH_CTL:
4570 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4571 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4572 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4573 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4574 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4575 		return kvm_hv_get_msr_common(vcpu,
4576 					     msr_info->index, &msr_info->data,
4577 					     msr_info->host_initiated);
4578 #endif
4579 	case MSR_IA32_BBL_CR_CTL3:
4580 		/* This legacy MSR exists but isn't fully documented in current
4581 		 * silicon.  It is however accessed by winxp in very narrow
4582 		 * scenarios where it sets bit #19, itself documented as
4583 		 * a "reserved" bit.  Best effort attempt to source coherent
4584 		 * read data here should the balance of the register be
4585 		 * interpreted by the guest:
4586 		 *
4587 		 * L2 cache control register 3: 64GB range, 256KB size,
4588 		 * enabled, latency 0x1, configured
4589 		 */
4590 		msr_info->data = 0xbe702111;
4591 		break;
4592 	case MSR_AMD64_OSVW_ID_LENGTH:
4593 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4594 			return 1;
4595 		msr_info->data = vcpu->arch.osvw.length;
4596 		break;
4597 	case MSR_AMD64_OSVW_STATUS:
4598 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4599 			return 1;
4600 		msr_info->data = vcpu->arch.osvw.status;
4601 		break;
4602 	case MSR_PLATFORM_INFO:
4603 		if (!msr_info->host_initiated &&
4604 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4605 			return 1;
4606 		msr_info->data = vcpu->arch.msr_platform_info;
4607 		break;
4608 	case MSR_MISC_FEATURES_ENABLES:
4609 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4610 		break;
4611 	case MSR_K7_HWCR:
4612 		msr_info->data = vcpu->arch.msr_hwcr;
4613 		break;
4614 #ifdef CONFIG_X86_64
4615 	case MSR_IA32_XFD:
4616 		if (!msr_info->host_initiated &&
4617 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4618 			return 1;
4619 
4620 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4621 		break;
4622 	case MSR_IA32_XFD_ERR:
4623 		if (!msr_info->host_initiated &&
4624 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4625 			return 1;
4626 
4627 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4628 		break;
4629 #endif
4630 	case MSR_IA32_U_CET:
4631 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4632 		kvm_get_xstate_msr(vcpu, msr_info);
4633 		break;
4634 	default:
4635 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4636 			return kvm_pmu_get_msr(vcpu, msr_info);
4637 
4638 		return KVM_MSR_RET_UNSUPPORTED;
4639 	}
4640 	return 0;
4641 }
4642 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_msr_common);
4643 
4644 /*
4645  * Read or write a bunch of msrs. All parameters are kernel addresses.
4646  *
4647  * @return number of msrs set successfully.
4648  */
__msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs * msrs,struct kvm_msr_entry * entries,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data))4649 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4650 		    struct kvm_msr_entry *entries,
4651 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4652 				  unsigned index, u64 *data))
4653 {
4654 	bool fpu_loaded = false;
4655 	int i;
4656 
4657 	for (i = 0; i < msrs->nmsrs; ++i) {
4658 		/*
4659 		 * If userspace is accessing one or more XSTATE-managed MSRs,
4660 		 * temporarily load the guest's FPU state so that the guest's
4661 		 * MSR value(s) is resident in hardware and thus can be accessed
4662 		 * via RDMSR/WRMSR.
4663 		 */
4664 		if (!fpu_loaded && is_xstate_managed_msr(vcpu, entries[i].index)) {
4665 			kvm_load_guest_fpu(vcpu);
4666 			fpu_loaded = true;
4667 		}
4668 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4669 			break;
4670 	}
4671 	if (fpu_loaded)
4672 		kvm_put_guest_fpu(vcpu);
4673 
4674 	return i;
4675 }
4676 
4677 /*
4678  * Read or write a bunch of msrs. Parameters are user addresses.
4679  *
4680  * @return number of msrs set successfully.
4681  */
msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs __user * user_msrs,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data),int writeback)4682 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4683 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4684 				unsigned index, u64 *data),
4685 		  int writeback)
4686 {
4687 	struct kvm_msrs msrs;
4688 	struct kvm_msr_entry *entries;
4689 	unsigned size;
4690 	int r;
4691 
4692 	r = -EFAULT;
4693 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4694 		goto out;
4695 
4696 	r = -E2BIG;
4697 	if (msrs.nmsrs >= MAX_IO_MSRS)
4698 		goto out;
4699 
4700 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4701 	entries = memdup_user(user_msrs->entries, size);
4702 	if (IS_ERR(entries)) {
4703 		r = PTR_ERR(entries);
4704 		goto out;
4705 	}
4706 
4707 	r = __msr_io(vcpu, &msrs, entries, do_msr);
4708 
4709 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4710 		r = -EFAULT;
4711 
4712 	kfree(entries);
4713 out:
4714 	return r;
4715 }
4716 
kvm_can_mwait_in_guest(void)4717 static inline bool kvm_can_mwait_in_guest(void)
4718 {
4719 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4720 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4721 		boot_cpu_has(X86_FEATURE_ARAT);
4722 }
4723 
kvm_get_allowed_disable_exits(void)4724 static u64 kvm_get_allowed_disable_exits(void)
4725 {
4726 	u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4727 
4728 	if (boot_cpu_has(X86_FEATURE_APERFMPERF))
4729 		r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
4730 
4731 	if (!mitigate_smt_rsb) {
4732 		r |= KVM_X86_DISABLE_EXITS_HLT |
4733 			KVM_X86_DISABLE_EXITS_CSTATE;
4734 
4735 		if (kvm_can_mwait_in_guest())
4736 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
4737 	}
4738 	return r;
4739 }
4740 
4741 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4742 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4743 					    struct kvm_cpuid2 __user *cpuid_arg)
4744 {
4745 	struct kvm_cpuid2 cpuid;
4746 	int r;
4747 
4748 	r = -EFAULT;
4749 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4750 		return r;
4751 
4752 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4753 	if (r)
4754 		return r;
4755 
4756 	r = -EFAULT;
4757 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4758 		return r;
4759 
4760 	return 0;
4761 }
4762 #endif
4763 
kvm_is_vm_type_supported(unsigned long type)4764 static bool kvm_is_vm_type_supported(unsigned long type)
4765 {
4766 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4767 }
4768 
kvm_sync_valid_fields(struct kvm * kvm)4769 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4770 {
4771 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4772 }
4773 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4774 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4775 {
4776 	int r = 0;
4777 
4778 	switch (ext) {
4779 	case KVM_CAP_IRQCHIP:
4780 	case KVM_CAP_HLT:
4781 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4782 	case KVM_CAP_SET_TSS_ADDR:
4783 	case KVM_CAP_EXT_CPUID:
4784 	case KVM_CAP_EXT_EMUL_CPUID:
4785 	case KVM_CAP_CLOCKSOURCE:
4786 #ifdef CONFIG_KVM_IOAPIC
4787 	case KVM_CAP_PIT:
4788 	case KVM_CAP_PIT2:
4789 	case KVM_CAP_PIT_STATE2:
4790 	case KVM_CAP_REINJECT_CONTROL:
4791 #endif
4792 	case KVM_CAP_NOP_IO_DELAY:
4793 	case KVM_CAP_MP_STATE:
4794 	case KVM_CAP_SYNC_MMU:
4795 	case KVM_CAP_USER_NMI:
4796 	case KVM_CAP_IRQ_INJECT_STATUS:
4797 	case KVM_CAP_IOEVENTFD:
4798 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4799 
4800 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4801 	case KVM_CAP_VCPU_EVENTS:
4802 #ifdef CONFIG_KVM_HYPERV
4803 	case KVM_CAP_HYPERV:
4804 	case KVM_CAP_HYPERV_VAPIC:
4805 	case KVM_CAP_HYPERV_SPIN:
4806 	case KVM_CAP_HYPERV_TIME:
4807 	case KVM_CAP_HYPERV_SYNIC:
4808 	case KVM_CAP_HYPERV_SYNIC2:
4809 	case KVM_CAP_HYPERV_VP_INDEX:
4810 	case KVM_CAP_HYPERV_EVENTFD:
4811 	case KVM_CAP_HYPERV_TLBFLUSH:
4812 	case KVM_CAP_HYPERV_SEND_IPI:
4813 	case KVM_CAP_HYPERV_CPUID:
4814 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4815 	case KVM_CAP_SYS_HYPERV_CPUID:
4816 #endif
4817 	case KVM_CAP_PCI_SEGMENT:
4818 	case KVM_CAP_DEBUGREGS:
4819 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4820 	case KVM_CAP_XSAVE:
4821 	case KVM_CAP_ASYNC_PF:
4822 	case KVM_CAP_ASYNC_PF_INT:
4823 	case KVM_CAP_GET_TSC_KHZ:
4824 	case KVM_CAP_KVMCLOCK_CTRL:
4825 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4826 	case KVM_CAP_TSC_DEADLINE_TIMER:
4827 	case KVM_CAP_DISABLE_QUIRKS:
4828 	case KVM_CAP_SET_BOOT_CPU_ID:
4829  	case KVM_CAP_SPLIT_IRQCHIP:
4830 	case KVM_CAP_IMMEDIATE_EXIT:
4831 	case KVM_CAP_PMU_EVENT_FILTER:
4832 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4833 	case KVM_CAP_GET_MSR_FEATURES:
4834 	case KVM_CAP_MSR_PLATFORM_INFO:
4835 	case KVM_CAP_EXCEPTION_PAYLOAD:
4836 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4837 	case KVM_CAP_SET_GUEST_DEBUG:
4838 	case KVM_CAP_LAST_CPU:
4839 	case KVM_CAP_X86_USER_SPACE_MSR:
4840 	case KVM_CAP_X86_MSR_FILTER:
4841 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4842 #ifdef CONFIG_X86_SGX_KVM
4843 	case KVM_CAP_SGX_ATTRIBUTE:
4844 #endif
4845 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4846 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4847 	case KVM_CAP_SREGS2:
4848 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4849 	case KVM_CAP_VCPU_ATTRIBUTES:
4850 	case KVM_CAP_SYS_ATTRIBUTES:
4851 	case KVM_CAP_VAPIC:
4852 	case KVM_CAP_ENABLE_CAP:
4853 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4854 	case KVM_CAP_IRQFD_RESAMPLE:
4855 	case KVM_CAP_MEMORY_FAULT_INFO:
4856 	case KVM_CAP_X86_GUEST_MODE:
4857 	case KVM_CAP_ONE_REG:
4858 		r = 1;
4859 		break;
4860 	case KVM_CAP_PRE_FAULT_MEMORY:
4861 		r = tdp_enabled;
4862 		break;
4863 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4864 		r = APIC_BUS_CYCLE_NS_DEFAULT;
4865 		break;
4866 	case KVM_CAP_EXIT_HYPERCALL:
4867 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4868 		break;
4869 	case KVM_CAP_SET_GUEST_DEBUG2:
4870 		return KVM_GUESTDBG_VALID_MASK;
4871 #ifdef CONFIG_KVM_XEN
4872 	case KVM_CAP_XEN_HVM:
4873 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4874 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4875 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4876 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4877 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4878 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4879 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4880 		if (sched_info_on())
4881 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4882 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4883 		break;
4884 #endif
4885 	case KVM_CAP_SYNC_REGS:
4886 		r = kvm_sync_valid_fields(kvm);
4887 		break;
4888 	case KVM_CAP_ADJUST_CLOCK:
4889 		r = KVM_CLOCK_VALID_FLAGS;
4890 		break;
4891 	case KVM_CAP_X86_DISABLE_EXITS:
4892 		r = kvm_get_allowed_disable_exits();
4893 		break;
4894 	case KVM_CAP_X86_SMM:
4895 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4896 			break;
4897 
4898 		/* SMBASE is usually relocated above 1M on modern chipsets,
4899 		 * and SMM handlers might indeed rely on 4G segment limits,
4900 		 * so do not report SMM to be available if real mode is
4901 		 * emulated via vm86 mode.  Still, do not go to great lengths
4902 		 * to avoid userspace's usage of the feature, because it is a
4903 		 * fringe case that is not enabled except via specific settings
4904 		 * of the module parameters.
4905 		 */
4906 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4907 		break;
4908 	case KVM_CAP_NR_VCPUS:
4909 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4910 		break;
4911 	case KVM_CAP_MAX_VCPUS:
4912 		r = KVM_MAX_VCPUS;
4913 		if (kvm)
4914 			r = kvm->max_vcpus;
4915 		break;
4916 	case KVM_CAP_MAX_VCPU_ID:
4917 		r = KVM_MAX_VCPU_IDS;
4918 		break;
4919 	case KVM_CAP_PV_MMU:	/* obsolete */
4920 		r = 0;
4921 		break;
4922 	case KVM_CAP_MCE:
4923 		r = KVM_MAX_MCE_BANKS;
4924 		break;
4925 	case KVM_CAP_XCRS:
4926 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4927 		break;
4928 	case KVM_CAP_TSC_CONTROL:
4929 	case KVM_CAP_VM_TSC_CONTROL:
4930 		r = kvm_caps.has_tsc_control;
4931 		break;
4932 	case KVM_CAP_X2APIC_API:
4933 		r = KVM_X2APIC_API_VALID_FLAGS;
4934 		break;
4935 	case KVM_CAP_NESTED_STATE:
4936 		r = kvm_x86_ops.nested_ops->get_state ?
4937 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4938 		break;
4939 #ifdef CONFIG_KVM_HYPERV
4940 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4941 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4942 		break;
4943 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4944 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4945 		break;
4946 #endif
4947 	case KVM_CAP_SMALLER_MAXPHYADDR:
4948 		r = (int) allow_smaller_maxphyaddr;
4949 		break;
4950 	case KVM_CAP_STEAL_TIME:
4951 		r = sched_info_on();
4952 		break;
4953 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4954 		if (kvm_caps.has_bus_lock_exit)
4955 			r = KVM_BUS_LOCK_DETECTION_OFF |
4956 			    KVM_BUS_LOCK_DETECTION_EXIT;
4957 		else
4958 			r = 0;
4959 		break;
4960 	case KVM_CAP_XSAVE2: {
4961 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4962 		if (r < sizeof(struct kvm_xsave))
4963 			r = sizeof(struct kvm_xsave);
4964 		break;
4965 	}
4966 	case KVM_CAP_PMU_CAPABILITY:
4967 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4968 		break;
4969 	case KVM_CAP_DISABLE_QUIRKS2:
4970 		r = kvm_caps.supported_quirks;
4971 		break;
4972 	case KVM_CAP_X86_NOTIFY_VMEXIT:
4973 		r = kvm_caps.has_notify_vmexit;
4974 		break;
4975 	case KVM_CAP_VM_TYPES:
4976 		r = kvm_caps.supported_vm_types;
4977 		break;
4978 	case KVM_CAP_READONLY_MEM:
4979 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4980 		break;
4981 	default:
4982 		break;
4983 	}
4984 	return r;
4985 }
4986 
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4987 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4988 {
4989 	if (attr->group) {
4990 		if (kvm_x86_ops.dev_get_attr)
4991 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4992 		return -ENXIO;
4993 	}
4994 
4995 	switch (attr->attr) {
4996 	case KVM_X86_XCOMP_GUEST_SUPP:
4997 		*val = kvm_caps.supported_xcr0;
4998 		return 0;
4999 	default:
5000 		return -ENXIO;
5001 	}
5002 }
5003 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)5004 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
5005 {
5006 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5007 	int r;
5008 	u64 val;
5009 
5010 	r = __kvm_x86_dev_get_attr(attr, &val);
5011 	if (r < 0)
5012 		return r;
5013 
5014 	if (put_user(val, uaddr))
5015 		return -EFAULT;
5016 
5017 	return 0;
5018 }
5019 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)5020 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
5021 {
5022 	u64 val;
5023 
5024 	return __kvm_x86_dev_get_attr(attr, &val);
5025 }
5026 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5027 long kvm_arch_dev_ioctl(struct file *filp,
5028 			unsigned int ioctl, unsigned long arg)
5029 {
5030 	void __user *argp = (void __user *)arg;
5031 	long r;
5032 
5033 	switch (ioctl) {
5034 	case KVM_GET_MSR_INDEX_LIST: {
5035 		struct kvm_msr_list __user *user_msr_list = argp;
5036 		struct kvm_msr_list msr_list;
5037 		unsigned n;
5038 
5039 		r = -EFAULT;
5040 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5041 			goto out;
5042 		n = msr_list.nmsrs;
5043 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
5044 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5045 			goto out;
5046 		r = -E2BIG;
5047 		if (n < msr_list.nmsrs)
5048 			goto out;
5049 		r = -EFAULT;
5050 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
5051 				 num_msrs_to_save * sizeof(u32)))
5052 			goto out;
5053 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
5054 				 &emulated_msrs,
5055 				 num_emulated_msrs * sizeof(u32)))
5056 			goto out;
5057 		r = 0;
5058 		break;
5059 	}
5060 	case KVM_GET_SUPPORTED_CPUID:
5061 	case KVM_GET_EMULATED_CPUID: {
5062 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5063 		struct kvm_cpuid2 cpuid;
5064 
5065 		r = -EFAULT;
5066 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5067 			goto out;
5068 
5069 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
5070 					    ioctl);
5071 		if (r)
5072 			goto out;
5073 
5074 		r = -EFAULT;
5075 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5076 			goto out;
5077 		r = 0;
5078 		break;
5079 	}
5080 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
5081 		r = -EFAULT;
5082 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
5083 				 sizeof(kvm_caps.supported_mce_cap)))
5084 			goto out;
5085 		r = 0;
5086 		break;
5087 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
5088 		struct kvm_msr_list __user *user_msr_list = argp;
5089 		struct kvm_msr_list msr_list;
5090 		unsigned int n;
5091 
5092 		r = -EFAULT;
5093 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5094 			goto out;
5095 		n = msr_list.nmsrs;
5096 		msr_list.nmsrs = num_msr_based_features;
5097 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5098 			goto out;
5099 		r = -E2BIG;
5100 		if (n < msr_list.nmsrs)
5101 			goto out;
5102 		r = -EFAULT;
5103 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
5104 				 num_msr_based_features * sizeof(u32)))
5105 			goto out;
5106 		r = 0;
5107 		break;
5108 	}
5109 	case KVM_GET_MSRS:
5110 		r = msr_io(NULL, argp, do_get_feature_msr, 1);
5111 		break;
5112 #ifdef CONFIG_KVM_HYPERV
5113 	case KVM_GET_SUPPORTED_HV_CPUID:
5114 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
5115 		break;
5116 #endif
5117 	case KVM_GET_DEVICE_ATTR: {
5118 		struct kvm_device_attr attr;
5119 		r = -EFAULT;
5120 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5121 			break;
5122 		r = kvm_x86_dev_get_attr(&attr);
5123 		break;
5124 	}
5125 	case KVM_HAS_DEVICE_ATTR: {
5126 		struct kvm_device_attr attr;
5127 		r = -EFAULT;
5128 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5129 			break;
5130 		r = kvm_x86_dev_has_attr(&attr);
5131 		break;
5132 	}
5133 	default:
5134 		r = -EINVAL;
5135 		break;
5136 	}
5137 out:
5138 	return r;
5139 }
5140 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)5141 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5142 {
5143 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5144 }
5145 
5146 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
5147 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)5148 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5149 {
5150 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5151 
5152 	kvm_request_l1tf_flush_l1d();
5153 
5154 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5155 		pmu->need_cleanup = true;
5156 		kvm_make_request(KVM_REQ_PMU, vcpu);
5157 	}
5158 
5159 	/* Address WBINVD may be executed by guest */
5160 	if (need_emulate_wbinvd(vcpu)) {
5161 		if (kvm_x86_call(has_wbinvd_exit)())
5162 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5163 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5164 			wbinvd_on_cpu(vcpu->cpu);
5165 	}
5166 
5167 	kvm_x86_call(vcpu_load)(vcpu, cpu);
5168 
5169 	if (vcpu != per_cpu(last_vcpu, cpu)) {
5170 		/*
5171 		 * Flush the branch predictor when switching vCPUs on the same
5172 		 * physical CPU, as each vCPU needs its own branch prediction
5173 		 * domain.  No IBPB is needed when switching between L1 and L2
5174 		 * on the same vCPU unless IBRS is advertised to the vCPU; that
5175 		 * is handled on the nested VM-Exit path.
5176 		 */
5177 		if (static_branch_likely(&switch_vcpu_ibpb))
5178 			indirect_branch_prediction_barrier();
5179 		per_cpu(last_vcpu, cpu) = vcpu;
5180 	}
5181 
5182 	/* Save host pkru register if supported */
5183 	vcpu->arch.host_pkru = read_pkru();
5184 
5185 	/* Apply any externally detected TSC adjustments (due to suspend) */
5186 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5187 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5188 		vcpu->arch.tsc_offset_adjustment = 0;
5189 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5190 	}
5191 
5192 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5193 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5194 				rdtsc() - vcpu->arch.last_host_tsc;
5195 		if (tsc_delta < 0)
5196 			mark_tsc_unstable("KVM discovered backwards TSC");
5197 
5198 		if (kvm_check_tsc_unstable()) {
5199 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5200 						vcpu->arch.last_guest_tsc);
5201 			kvm_vcpu_write_tsc_offset(vcpu, offset);
5202 			if (!vcpu->arch.guest_tsc_protected)
5203 				vcpu->arch.tsc_catchup = 1;
5204 		}
5205 
5206 		if (kvm_lapic_hv_timer_in_use(vcpu))
5207 			kvm_lapic_restart_hv_timer(vcpu);
5208 
5209 		/*
5210 		 * On a host with synchronized TSC, there is no need to update
5211 		 * kvmclock on vcpu->cpu migration
5212 		 */
5213 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5214 			kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5215 		if (vcpu->cpu != cpu)
5216 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5217 		vcpu->cpu = cpu;
5218 	}
5219 
5220 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5221 }
5222 
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5223 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5224 {
5225 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5226 	struct kvm_steal_time __user *st;
5227 	struct kvm_memslots *slots;
5228 	static const u8 preempted = KVM_VCPU_PREEMPTED;
5229 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5230 
5231 	/*
5232 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
5233 	 * an instruction boundary and will not trigger guest emulation of any
5234 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
5235 	 * when this is true, for example allowing the vCPU to be marked
5236 	 * preempted if and only if the VM-Exit was due to a host interrupt.
5237 	 */
5238 	if (!vcpu->arch.at_instruction_boundary) {
5239 		vcpu->stat.preemption_other++;
5240 		return;
5241 	}
5242 
5243 	vcpu->stat.preemption_reported++;
5244 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5245 		return;
5246 
5247 	if (vcpu->arch.st.preempted)
5248 		return;
5249 
5250 	/* This happens on process exit */
5251 	if (unlikely(current->mm != vcpu->kvm->mm))
5252 		return;
5253 
5254 	slots = kvm_memslots(vcpu->kvm);
5255 
5256 	if (unlikely(slots->generation != ghc->generation ||
5257 		     gpa != ghc->gpa ||
5258 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5259 		return;
5260 
5261 	st = (struct kvm_steal_time __user *)ghc->hva;
5262 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5263 
5264 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5265 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5266 
5267 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5268 }
5269 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5270 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5271 {
5272 	int idx;
5273 
5274 	if (vcpu->preempted) {
5275 		/*
5276 		 * Assume protected guests are in-kernel.  Inefficient yielding
5277 		 * due to false positives is preferable to never yielding due
5278 		 * to false negatives.
5279 		 */
5280 		vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5281 						 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5282 
5283 		/*
5284 		 * Take the srcu lock as memslots will be accessed to check the gfn
5285 		 * cache generation against the memslots generation.
5286 		 */
5287 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5288 		if (kvm_xen_msr_enabled(vcpu->kvm))
5289 			kvm_xen_runstate_set_preempted(vcpu);
5290 		else
5291 			kvm_steal_time_set_preempted(vcpu);
5292 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5293 	}
5294 
5295 	kvm_x86_call(vcpu_put)(vcpu);
5296 	vcpu->arch.last_host_tsc = rdtsc();
5297 }
5298 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5299 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5300 				    struct kvm_lapic_state *s)
5301 {
5302 	if (vcpu->arch.apic->guest_apic_protected)
5303 		return -EINVAL;
5304 
5305 	kvm_x86_call(sync_pir_to_irr)(vcpu);
5306 
5307 	return kvm_apic_get_state(vcpu, s);
5308 }
5309 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5310 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5311 				    struct kvm_lapic_state *s)
5312 {
5313 	int r;
5314 
5315 	if (vcpu->arch.apic->guest_apic_protected)
5316 		return -EINVAL;
5317 
5318 	r = kvm_apic_set_state(vcpu, s);
5319 	if (r)
5320 		return r;
5321 	update_cr8_intercept(vcpu);
5322 
5323 	return 0;
5324 }
5325 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5326 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5327 {
5328 	/*
5329 	 * We can accept userspace's request for interrupt injection
5330 	 * as long as we have a place to store the interrupt number.
5331 	 * The actual injection will happen when the CPU is able to
5332 	 * deliver the interrupt.
5333 	 */
5334 	if (kvm_cpu_has_extint(vcpu))
5335 		return false;
5336 
5337 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
5338 	return (!lapic_in_kernel(vcpu) ||
5339 		kvm_apic_accept_pic_intr(vcpu));
5340 }
5341 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5342 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5343 {
5344 	/*
5345 	 * Do not cause an interrupt window exit if an exception
5346 	 * is pending or an event needs reinjection; userspace
5347 	 * might want to inject the interrupt manually using KVM_SET_REGS
5348 	 * or KVM_SET_SREGS.  For that to work, we must be at an
5349 	 * instruction boundary and with no events half-injected.
5350 	 */
5351 	return (kvm_arch_interrupt_allowed(vcpu) &&
5352 		kvm_cpu_accept_dm_intr(vcpu) &&
5353 		!kvm_event_needs_reinjection(vcpu) &&
5354 		!kvm_is_exception_pending(vcpu));
5355 }
5356 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5357 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5358 				    struct kvm_interrupt *irq)
5359 {
5360 	if (irq->irq >= KVM_NR_INTERRUPTS)
5361 		return -EINVAL;
5362 
5363 	if (!irqchip_in_kernel(vcpu->kvm)) {
5364 		kvm_queue_interrupt(vcpu, irq->irq, false);
5365 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5366 		return 0;
5367 	}
5368 
5369 	/*
5370 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5371 	 * fail for in-kernel 8259.
5372 	 */
5373 	if (pic_in_kernel(vcpu->kvm))
5374 		return -ENXIO;
5375 
5376 	if (vcpu->arch.pending_external_vector != -1)
5377 		return -EEXIST;
5378 
5379 	vcpu->arch.pending_external_vector = irq->irq;
5380 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5381 	return 0;
5382 }
5383 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5384 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5385 {
5386 	kvm_inject_nmi(vcpu);
5387 
5388 	return 0;
5389 }
5390 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5391 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5392 					   struct kvm_tpr_access_ctl *tac)
5393 {
5394 	if (tac->flags)
5395 		return -EINVAL;
5396 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
5397 	return 0;
5398 }
5399 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5400 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5401 					u64 mcg_cap)
5402 {
5403 	int r;
5404 	unsigned bank_num = mcg_cap & 0xff, bank;
5405 
5406 	r = -EINVAL;
5407 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5408 		goto out;
5409 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5410 		goto out;
5411 	r = 0;
5412 	vcpu->arch.mcg_cap = mcg_cap;
5413 	/* Init IA32_MCG_CTL to all 1s */
5414 	if (mcg_cap & MCG_CTL_P)
5415 		vcpu->arch.mcg_ctl = ~(u64)0;
5416 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5417 	for (bank = 0; bank < bank_num; bank++) {
5418 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5419 		if (mcg_cap & MCG_CMCI_P)
5420 			vcpu->arch.mci_ctl2_banks[bank] = 0;
5421 	}
5422 
5423 	kvm_apic_after_set_mcg_cap(vcpu);
5424 
5425 	kvm_x86_call(setup_mce)(vcpu);
5426 out:
5427 	return r;
5428 }
5429 
5430 /*
5431  * Validate this is an UCNA (uncorrectable no action) error by checking the
5432  * MCG_STATUS and MCi_STATUS registers:
5433  * - none of the bits for Machine Check Exceptions are set
5434  * - both the VAL (valid) and UC (uncorrectable) bits are set
5435  * MCI_STATUS_PCC - Processor Context Corrupted
5436  * MCI_STATUS_S - Signaled as a Machine Check Exception
5437  * MCI_STATUS_AR - Software recoverable Action Required
5438  */
is_ucna(struct kvm_x86_mce * mce)5439 static bool is_ucna(struct kvm_x86_mce *mce)
5440 {
5441 	return	!mce->mcg_status &&
5442 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5443 		(mce->status & MCI_STATUS_VAL) &&
5444 		(mce->status & MCI_STATUS_UC);
5445 }
5446 
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5447 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5448 {
5449 	u64 mcg_cap = vcpu->arch.mcg_cap;
5450 
5451 	banks[1] = mce->status;
5452 	banks[2] = mce->addr;
5453 	banks[3] = mce->misc;
5454 	vcpu->arch.mcg_status = mce->mcg_status;
5455 
5456 	if (!(mcg_cap & MCG_CMCI_P) ||
5457 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5458 		return 0;
5459 
5460 	if (lapic_in_kernel(vcpu))
5461 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5462 
5463 	return 0;
5464 }
5465 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5466 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5467 				      struct kvm_x86_mce *mce)
5468 {
5469 	u64 mcg_cap = vcpu->arch.mcg_cap;
5470 	unsigned bank_num = mcg_cap & 0xff;
5471 	u64 *banks = vcpu->arch.mce_banks;
5472 
5473 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5474 		return -EINVAL;
5475 
5476 	banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5477 
5478 	if (is_ucna(mce))
5479 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5480 
5481 	/*
5482 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5483 	 * reporting is disabled
5484 	 */
5485 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5486 	    vcpu->arch.mcg_ctl != ~(u64)0)
5487 		return 0;
5488 	/*
5489 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5490 	 * reporting is disabled for the bank
5491 	 */
5492 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5493 		return 0;
5494 	if (mce->status & MCI_STATUS_UC) {
5495 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5496 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5497 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5498 			return 0;
5499 		}
5500 		if (banks[1] & MCI_STATUS_VAL)
5501 			mce->status |= MCI_STATUS_OVER;
5502 		banks[2] = mce->addr;
5503 		banks[3] = mce->misc;
5504 		vcpu->arch.mcg_status = mce->mcg_status;
5505 		banks[1] = mce->status;
5506 		kvm_queue_exception(vcpu, MC_VECTOR);
5507 	} else if (!(banks[1] & MCI_STATUS_VAL)
5508 		   || !(banks[1] & MCI_STATUS_UC)) {
5509 		if (banks[1] & MCI_STATUS_VAL)
5510 			mce->status |= MCI_STATUS_OVER;
5511 		banks[2] = mce->addr;
5512 		banks[3] = mce->misc;
5513 		banks[1] = mce->status;
5514 	} else
5515 		banks[1] |= MCI_STATUS_OVER;
5516 	return 0;
5517 }
5518 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5519 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5520 					       struct kvm_vcpu_events *events)
5521 {
5522 	struct kvm_queued_exception *ex;
5523 
5524 	process_nmi(vcpu);
5525 
5526 #ifdef CONFIG_KVM_SMM
5527 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
5528 		process_smi(vcpu);
5529 #endif
5530 
5531 	/*
5532 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
5533 	 * the only time there can be two queued exceptions is if there's a
5534 	 * non-exiting _injected_ exception, and a pending exiting exception.
5535 	 * In that case, ignore the VM-Exiting exception as it's an extension
5536 	 * of the injected exception.
5537 	 */
5538 	if (vcpu->arch.exception_vmexit.pending &&
5539 	    !vcpu->arch.exception.pending &&
5540 	    !vcpu->arch.exception.injected)
5541 		ex = &vcpu->arch.exception_vmexit;
5542 	else
5543 		ex = &vcpu->arch.exception;
5544 
5545 	/*
5546 	 * In guest mode, payload delivery should be deferred if the exception
5547 	 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5548 	 * intercepts #PF, ditto for DR6 and #DBs.  If the per-VM capability,
5549 	 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5550 	 * propagate the payload and so it cannot be safely deferred.  Deliver
5551 	 * the payload if the capability hasn't been requested.
5552 	 */
5553 	if (!vcpu->kvm->arch.exception_payload_enabled &&
5554 	    ex->pending && ex->has_payload)
5555 		kvm_deliver_exception_payload(vcpu, ex);
5556 
5557 	memset(events, 0, sizeof(*events));
5558 
5559 	/*
5560 	 * The API doesn't provide the instruction length for software
5561 	 * exceptions, so don't report them. As long as the guest RIP
5562 	 * isn't advanced, we should expect to encounter the exception
5563 	 * again.
5564 	 */
5565 	if (!kvm_exception_is_soft(ex->vector)) {
5566 		events->exception.injected = ex->injected;
5567 		events->exception.pending = ex->pending;
5568 		/*
5569 		 * For ABI compatibility, deliberately conflate
5570 		 * pending and injected exceptions when
5571 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5572 		 */
5573 		if (!vcpu->kvm->arch.exception_payload_enabled)
5574 			events->exception.injected |= ex->pending;
5575 	}
5576 	events->exception.nr = ex->vector;
5577 	events->exception.has_error_code = ex->has_error_code;
5578 	events->exception.error_code = ex->error_code;
5579 	events->exception_has_payload = ex->has_payload;
5580 	events->exception_payload = ex->payload;
5581 
5582 	events->interrupt.injected =
5583 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5584 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5585 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5586 
5587 	events->nmi.injected = vcpu->arch.nmi_injected;
5588 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5589 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5590 
5591 	/* events->sipi_vector is never valid when reporting to user space */
5592 
5593 #ifdef CONFIG_KVM_SMM
5594 	events->smi.smm = is_smm(vcpu);
5595 	events->smi.pending = vcpu->arch.smi_pending;
5596 	events->smi.smm_inside_nmi =
5597 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5598 #endif
5599 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5600 
5601 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5602 			 | KVM_VCPUEVENT_VALID_SHADOW
5603 			 | KVM_VCPUEVENT_VALID_SMM);
5604 	if (vcpu->kvm->arch.exception_payload_enabled)
5605 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5606 	if (vcpu->kvm->arch.triple_fault_event) {
5607 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5608 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5609 	}
5610 }
5611 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5612 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5613 					      struct kvm_vcpu_events *events)
5614 {
5615 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5616 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5617 			      | KVM_VCPUEVENT_VALID_SHADOW
5618 			      | KVM_VCPUEVENT_VALID_SMM
5619 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5620 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5621 		return -EINVAL;
5622 
5623 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5624 		if (!vcpu->kvm->arch.exception_payload_enabled)
5625 			return -EINVAL;
5626 		if (events->exception.pending)
5627 			events->exception.injected = 0;
5628 		else
5629 			events->exception_has_payload = 0;
5630 	} else {
5631 		events->exception.pending = 0;
5632 		events->exception_has_payload = 0;
5633 	}
5634 
5635 	if ((events->exception.injected || events->exception.pending) &&
5636 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5637 		return -EINVAL;
5638 
5639 	process_nmi(vcpu);
5640 
5641 	/*
5642 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5643 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5644 	 * pending exceptions, already-injected exceptions are not subject to
5645 	 * intercpetion.  Note, userspace that conflates pending and injected
5646 	 * is hosed, and will incorrectly convert an injected exception into a
5647 	 * pending exception, which in turn may cause a spurious VM-Exit.
5648 	 */
5649 	vcpu->arch.exception_from_userspace = events->exception.pending;
5650 
5651 	vcpu->arch.exception_vmexit.pending = false;
5652 
5653 	vcpu->arch.exception.injected = events->exception.injected;
5654 	vcpu->arch.exception.pending = events->exception.pending;
5655 	vcpu->arch.exception.vector = events->exception.nr;
5656 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5657 	vcpu->arch.exception.error_code = events->exception.error_code;
5658 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5659 	vcpu->arch.exception.payload = events->exception_payload;
5660 
5661 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5662 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5663 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5664 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5665 		kvm_x86_call(set_interrupt_shadow)(vcpu,
5666 						   events->interrupt.shadow);
5667 
5668 	vcpu->arch.nmi_injected = events->nmi.injected;
5669 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5670 		vcpu->arch.nmi_pending = 0;
5671 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5672 		if (events->nmi.pending)
5673 			kvm_make_request(KVM_REQ_NMI, vcpu);
5674 	}
5675 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5676 
5677 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5678 	    lapic_in_kernel(vcpu))
5679 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5680 
5681 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5682 #ifdef CONFIG_KVM_SMM
5683 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5684 			kvm_leave_nested(vcpu);
5685 			kvm_smm_changed(vcpu, events->smi.smm);
5686 		}
5687 
5688 		vcpu->arch.smi_pending = events->smi.pending;
5689 
5690 		if (events->smi.smm) {
5691 			if (events->smi.smm_inside_nmi)
5692 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5693 			else
5694 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5695 		}
5696 
5697 #else
5698 		if (events->smi.smm || events->smi.pending ||
5699 		    events->smi.smm_inside_nmi)
5700 			return -EINVAL;
5701 #endif
5702 
5703 		if (lapic_in_kernel(vcpu)) {
5704 			if (events->smi.latched_init)
5705 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5706 			else
5707 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5708 		}
5709 	}
5710 
5711 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5712 		if (!vcpu->kvm->arch.triple_fault_event)
5713 			return -EINVAL;
5714 		if (events->triple_fault.pending)
5715 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5716 		else
5717 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5718 	}
5719 
5720 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5721 
5722 	return 0;
5723 }
5724 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5725 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5726 					    struct kvm_debugregs *dbgregs)
5727 {
5728 	unsigned int i;
5729 
5730 	if (vcpu->kvm->arch.has_protected_state &&
5731 	    vcpu->arch.guest_state_protected)
5732 		return -EINVAL;
5733 
5734 	memset(dbgregs, 0, sizeof(*dbgregs));
5735 
5736 	BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5737 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5738 		dbgregs->db[i] = vcpu->arch.db[i];
5739 
5740 	dbgregs->dr6 = vcpu->arch.dr6;
5741 	dbgregs->dr7 = vcpu->arch.dr7;
5742 	return 0;
5743 }
5744 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5745 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5746 					    struct kvm_debugregs *dbgregs)
5747 {
5748 	unsigned int i;
5749 
5750 	if (vcpu->kvm->arch.has_protected_state &&
5751 	    vcpu->arch.guest_state_protected)
5752 		return -EINVAL;
5753 
5754 	if (dbgregs->flags)
5755 		return -EINVAL;
5756 
5757 	if (!kvm_dr6_valid(dbgregs->dr6))
5758 		return -EINVAL;
5759 	if (!kvm_dr7_valid(dbgregs->dr7))
5760 		return -EINVAL;
5761 
5762 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5763 		vcpu->arch.db[i] = dbgregs->db[i];
5764 
5765 	kvm_update_dr0123(vcpu);
5766 	vcpu->arch.dr6 = dbgregs->dr6;
5767 	vcpu->arch.dr7 = dbgregs->dr7;
5768 	kvm_update_dr7(vcpu);
5769 
5770 	return 0;
5771 }
5772 
5773 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5774 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5775 					 u8 *state, unsigned int size)
5776 {
5777 	/*
5778 	 * Only copy state for features that are enabled for the guest.  The
5779 	 * state itself isn't problematic, but setting bits in the header for
5780 	 * features that are supported in *this* host but not exposed to the
5781 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5782 	 * compatible host without the features that are NOT exposed to the
5783 	 * guest.
5784 	 *
5785 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5786 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5787 	 * supported by the host.
5788 	 */
5789 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5790 			     XFEATURE_MASK_FPSSE;
5791 
5792 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5793 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5794 
5795 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5796 				       supported_xcr0, vcpu->arch.pkru);
5797 	return 0;
5798 }
5799 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5800 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5801 					struct kvm_xsave *guest_xsave)
5802 {
5803 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5804 					     sizeof(guest_xsave->region));
5805 }
5806 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5807 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5808 					struct kvm_xsave *guest_xsave)
5809 {
5810 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5811 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5812 
5813 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5814 					      guest_xsave->region,
5815 					      kvm_caps.supported_xcr0,
5816 					      &vcpu->arch.pkru);
5817 }
5818 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5819 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5820 				       struct kvm_xcrs *guest_xcrs)
5821 {
5822 	if (vcpu->kvm->arch.has_protected_state &&
5823 	    vcpu->arch.guest_state_protected)
5824 		return -EINVAL;
5825 
5826 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5827 		guest_xcrs->nr_xcrs = 0;
5828 		return 0;
5829 	}
5830 
5831 	guest_xcrs->nr_xcrs = 1;
5832 	guest_xcrs->flags = 0;
5833 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5834 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5835 	return 0;
5836 }
5837 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5838 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5839 				       struct kvm_xcrs *guest_xcrs)
5840 {
5841 	int i, r = 0;
5842 
5843 	if (vcpu->kvm->arch.has_protected_state &&
5844 	    vcpu->arch.guest_state_protected)
5845 		return -EINVAL;
5846 
5847 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5848 		return -EINVAL;
5849 
5850 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5851 		return -EINVAL;
5852 
5853 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5854 		/* Only support XCR0 currently */
5855 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5856 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5857 				guest_xcrs->xcrs[i].value);
5858 			break;
5859 		}
5860 	if (r)
5861 		r = -EINVAL;
5862 	return r;
5863 }
5864 
5865 /*
5866  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5867  * stopped by the hypervisor.  This function will be called from the host only.
5868  * EINVAL is returned when the host attempts to set the flag for a guest that
5869  * does not support pv clocks.
5870  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5871 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5872 {
5873 	if (!vcpu->arch.pv_time.active)
5874 		return -EINVAL;
5875 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5876 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5877 	return 0;
5878 }
5879 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5880 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5881 				 struct kvm_device_attr *attr)
5882 {
5883 	int r;
5884 
5885 	switch (attr->attr) {
5886 	case KVM_VCPU_TSC_OFFSET:
5887 		r = 0;
5888 		break;
5889 	default:
5890 		r = -ENXIO;
5891 	}
5892 
5893 	return r;
5894 }
5895 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5896 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5897 				 struct kvm_device_attr *attr)
5898 {
5899 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5900 	int r;
5901 
5902 	switch (attr->attr) {
5903 	case KVM_VCPU_TSC_OFFSET:
5904 		r = -EFAULT;
5905 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5906 			break;
5907 		r = 0;
5908 		break;
5909 	default:
5910 		r = -ENXIO;
5911 	}
5912 
5913 	return r;
5914 }
5915 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5916 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5917 				 struct kvm_device_attr *attr)
5918 {
5919 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5920 	struct kvm *kvm = vcpu->kvm;
5921 	int r;
5922 
5923 	switch (attr->attr) {
5924 	case KVM_VCPU_TSC_OFFSET: {
5925 		u64 offset, tsc, ns;
5926 		unsigned long flags;
5927 		bool matched;
5928 
5929 		r = -EFAULT;
5930 		if (get_user(offset, uaddr))
5931 			break;
5932 
5933 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5934 
5935 		matched = (vcpu->arch.virtual_tsc_khz &&
5936 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5937 			   kvm->arch.last_tsc_offset == offset);
5938 
5939 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5940 		ns = get_kvmclock_base_ns();
5941 
5942 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5943 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5944 
5945 		r = 0;
5946 		break;
5947 	}
5948 	default:
5949 		r = -ENXIO;
5950 	}
5951 
5952 	return r;
5953 }
5954 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5955 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5956 				      unsigned int ioctl,
5957 				      void __user *argp)
5958 {
5959 	struct kvm_device_attr attr;
5960 	int r;
5961 
5962 	if (copy_from_user(&attr, argp, sizeof(attr)))
5963 		return -EFAULT;
5964 
5965 	if (attr.group != KVM_VCPU_TSC_CTRL)
5966 		return -ENXIO;
5967 
5968 	switch (ioctl) {
5969 	case KVM_HAS_DEVICE_ATTR:
5970 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5971 		break;
5972 	case KVM_GET_DEVICE_ATTR:
5973 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5974 		break;
5975 	case KVM_SET_DEVICE_ATTR:
5976 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5977 		break;
5978 	}
5979 
5980 	return r;
5981 }
5982 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5983 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5984 				     struct kvm_enable_cap *cap)
5985 {
5986 	if (cap->flags)
5987 		return -EINVAL;
5988 
5989 	switch (cap->cap) {
5990 #ifdef CONFIG_KVM_HYPERV
5991 	case KVM_CAP_HYPERV_SYNIC2:
5992 		if (cap->args[0])
5993 			return -EINVAL;
5994 		fallthrough;
5995 
5996 	case KVM_CAP_HYPERV_SYNIC:
5997 		if (!irqchip_in_kernel(vcpu->kvm))
5998 			return -EINVAL;
5999 		return kvm_hv_activate_synic(vcpu, cap->cap ==
6000 					     KVM_CAP_HYPERV_SYNIC2);
6001 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
6002 		{
6003 			int r;
6004 			uint16_t vmcs_version;
6005 			void __user *user_ptr;
6006 
6007 			if (!kvm_x86_ops.nested_ops->enable_evmcs)
6008 				return -ENOTTY;
6009 			r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
6010 			if (!r) {
6011 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
6012 				if (copy_to_user(user_ptr, &vmcs_version,
6013 						 sizeof(vmcs_version)))
6014 					r = -EFAULT;
6015 			}
6016 			return r;
6017 		}
6018 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
6019 		if (!kvm_x86_ops.enable_l2_tlb_flush)
6020 			return -ENOTTY;
6021 
6022 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
6023 
6024 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
6025 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
6026 #endif
6027 
6028 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
6029 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
6030 		return 0;
6031 	default:
6032 		return -EINVAL;
6033 	}
6034 }
6035 
6036 struct kvm_x86_reg_id {
6037 	__u32 index;
6038 	__u8  type;
6039 	__u8  rsvd1;
6040 	__u8  rsvd2:4;
6041 	__u8  size:4;
6042 	__u8  x86;
6043 };
6044 
kvm_translate_kvm_reg(struct kvm_vcpu * vcpu,struct kvm_x86_reg_id * reg)6045 static int kvm_translate_kvm_reg(struct kvm_vcpu *vcpu,
6046 				 struct kvm_x86_reg_id *reg)
6047 {
6048 	switch (reg->index) {
6049 	case KVM_REG_GUEST_SSP:
6050 		/*
6051 		 * FIXME: If host-initiated accesses are ever exempted from
6052 		 * ignore_msrs (in kvm_do_msr_access()), drop this manual check
6053 		 * and rely on KVM's standard checks to reject accesses to regs
6054 		 * that don't exist.
6055 		 */
6056 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
6057 			return -EINVAL;
6058 
6059 		reg->type = KVM_X86_REG_TYPE_MSR;
6060 		reg->index = MSR_KVM_INTERNAL_GUEST_SSP;
6061 		break;
6062 	default:
6063 		return -EINVAL;
6064 	}
6065 	return 0;
6066 }
6067 
kvm_get_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6068 static int kvm_get_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6069 {
6070 	u64 val;
6071 
6072 	if (do_get_msr(vcpu, msr, &val))
6073 		return -EINVAL;
6074 
6075 	if (put_user(val, user_val))
6076 		return -EFAULT;
6077 
6078 	return 0;
6079 }
6080 
kvm_set_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6081 static int kvm_set_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6082 {
6083 	u64 val;
6084 
6085 	if (get_user(val, user_val))
6086 		return -EFAULT;
6087 
6088 	if (do_set_msr(vcpu, msr, &val))
6089 		return -EINVAL;
6090 
6091 	return 0;
6092 }
6093 
kvm_get_set_one_reg(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6094 static int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
6095 			       void __user *argp)
6096 {
6097 	struct kvm_one_reg one_reg;
6098 	struct kvm_x86_reg_id *reg;
6099 	u64 __user *user_val;
6100 	bool load_fpu;
6101 	int r;
6102 
6103 	if (copy_from_user(&one_reg, argp, sizeof(one_reg)))
6104 		return -EFAULT;
6105 
6106 	if ((one_reg.id & KVM_REG_ARCH_MASK) != KVM_REG_X86)
6107 		return -EINVAL;
6108 
6109 	reg = (struct kvm_x86_reg_id *)&one_reg.id;
6110 	if (reg->rsvd1 || reg->rsvd2)
6111 		return -EINVAL;
6112 
6113 	if (reg->type == KVM_X86_REG_TYPE_KVM) {
6114 		r = kvm_translate_kvm_reg(vcpu, reg);
6115 		if (r)
6116 			return r;
6117 	}
6118 
6119 	if (reg->type != KVM_X86_REG_TYPE_MSR)
6120 		return -EINVAL;
6121 
6122 	if ((one_reg.id & KVM_REG_SIZE_MASK) != KVM_REG_SIZE_U64)
6123 		return -EINVAL;
6124 
6125 	guard(srcu)(&vcpu->kvm->srcu);
6126 
6127 	load_fpu = is_xstate_managed_msr(vcpu, reg->index);
6128 	if (load_fpu)
6129 		kvm_load_guest_fpu(vcpu);
6130 
6131 	user_val = u64_to_user_ptr(one_reg.addr);
6132 	if (ioctl == KVM_GET_ONE_REG)
6133 		r = kvm_get_one_msr(vcpu, reg->index, user_val);
6134 	else
6135 		r = kvm_set_one_msr(vcpu, reg->index, user_val);
6136 
6137 	if (load_fpu)
6138 		kvm_put_guest_fpu(vcpu);
6139 	return r;
6140 }
6141 
kvm_get_reg_list(struct kvm_vcpu * vcpu,struct kvm_reg_list __user * user_list)6142 static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
6143 			    struct kvm_reg_list __user *user_list)
6144 {
6145 	u64 nr_regs = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ? 1 : 0;
6146 	u64 user_nr_regs;
6147 
6148 	if (get_user(user_nr_regs, &user_list->n))
6149 		return -EFAULT;
6150 
6151 	if (put_user(nr_regs, &user_list->n))
6152 		return -EFAULT;
6153 
6154 	if (user_nr_regs < nr_regs)
6155 		return -E2BIG;
6156 
6157 	if (nr_regs &&
6158 	    put_user(KVM_X86_REG_KVM(KVM_REG_GUEST_SSP), &user_list->reg[0]))
6159 		return -EFAULT;
6160 
6161 	return 0;
6162 }
6163 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6164 long kvm_arch_vcpu_ioctl(struct file *filp,
6165 			 unsigned int ioctl, unsigned long arg)
6166 {
6167 	struct kvm_vcpu *vcpu = filp->private_data;
6168 	void __user *argp = (void __user *)arg;
6169 	int r;
6170 	union {
6171 		struct kvm_sregs2 *sregs2;
6172 		struct kvm_lapic_state *lapic;
6173 		struct kvm_xsave *xsave;
6174 		struct kvm_xcrs *xcrs;
6175 		void *buffer;
6176 	} u;
6177 
6178 	vcpu_load(vcpu);
6179 
6180 	u.buffer = NULL;
6181 	switch (ioctl) {
6182 	case KVM_GET_LAPIC: {
6183 		r = -EINVAL;
6184 		if (!lapic_in_kernel(vcpu))
6185 			goto out;
6186 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
6187 
6188 		r = -ENOMEM;
6189 		if (!u.lapic)
6190 			goto out;
6191 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
6192 		if (r)
6193 			goto out;
6194 		r = -EFAULT;
6195 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
6196 			goto out;
6197 		r = 0;
6198 		break;
6199 	}
6200 	case KVM_SET_LAPIC: {
6201 		r = -EINVAL;
6202 		if (!lapic_in_kernel(vcpu))
6203 			goto out;
6204 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
6205 		if (IS_ERR(u.lapic)) {
6206 			r = PTR_ERR(u.lapic);
6207 			goto out_nofree;
6208 		}
6209 
6210 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
6211 		break;
6212 	}
6213 	case KVM_INTERRUPT: {
6214 		struct kvm_interrupt irq;
6215 
6216 		r = -EFAULT;
6217 		if (copy_from_user(&irq, argp, sizeof(irq)))
6218 			goto out;
6219 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
6220 		break;
6221 	}
6222 	case KVM_NMI: {
6223 		r = kvm_vcpu_ioctl_nmi(vcpu);
6224 		break;
6225 	}
6226 	case KVM_SMI: {
6227 		r = kvm_inject_smi(vcpu);
6228 		break;
6229 	}
6230 	case KVM_SET_CPUID: {
6231 		struct kvm_cpuid __user *cpuid_arg = argp;
6232 		struct kvm_cpuid cpuid;
6233 
6234 		r = -EFAULT;
6235 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6236 			goto out;
6237 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
6238 		break;
6239 	}
6240 	case KVM_SET_CPUID2: {
6241 		struct kvm_cpuid2 __user *cpuid_arg = argp;
6242 		struct kvm_cpuid2 cpuid;
6243 
6244 		r = -EFAULT;
6245 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6246 			goto out;
6247 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
6248 					      cpuid_arg->entries);
6249 		break;
6250 	}
6251 	case KVM_GET_CPUID2: {
6252 		struct kvm_cpuid2 __user *cpuid_arg = argp;
6253 		struct kvm_cpuid2 cpuid;
6254 
6255 		r = -EFAULT;
6256 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6257 			goto out;
6258 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
6259 					      cpuid_arg->entries);
6260 		if (r)
6261 			goto out;
6262 		r = -EFAULT;
6263 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
6264 			goto out;
6265 		r = 0;
6266 		break;
6267 	}
6268 	case KVM_GET_MSRS: {
6269 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
6270 		r = msr_io(vcpu, argp, do_get_msr, 1);
6271 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6272 		break;
6273 	}
6274 	case KVM_SET_MSRS: {
6275 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
6276 		r = msr_io(vcpu, argp, do_set_msr, 0);
6277 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6278 		break;
6279 	}
6280 	case KVM_GET_ONE_REG:
6281 	case KVM_SET_ONE_REG:
6282 		r = kvm_get_set_one_reg(vcpu, ioctl, argp);
6283 		break;
6284 	case KVM_GET_REG_LIST:
6285 		r = kvm_get_reg_list(vcpu, argp);
6286 		break;
6287 	case KVM_TPR_ACCESS_REPORTING: {
6288 		struct kvm_tpr_access_ctl tac;
6289 
6290 		r = -EFAULT;
6291 		if (copy_from_user(&tac, argp, sizeof(tac)))
6292 			goto out;
6293 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6294 		if (r)
6295 			goto out;
6296 		r = -EFAULT;
6297 		if (copy_to_user(argp, &tac, sizeof(tac)))
6298 			goto out;
6299 		r = 0;
6300 		break;
6301 	};
6302 	case KVM_SET_VAPIC_ADDR: {
6303 		struct kvm_vapic_addr va;
6304 		int idx;
6305 
6306 		r = -EINVAL;
6307 		if (!lapic_in_kernel(vcpu))
6308 			goto out;
6309 		r = -EFAULT;
6310 		if (copy_from_user(&va, argp, sizeof(va)))
6311 			goto out;
6312 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6313 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6314 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6315 		break;
6316 	}
6317 	case KVM_X86_SETUP_MCE: {
6318 		u64 mcg_cap;
6319 
6320 		r = -EFAULT;
6321 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6322 			goto out;
6323 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6324 		break;
6325 	}
6326 	case KVM_X86_SET_MCE: {
6327 		struct kvm_x86_mce mce;
6328 
6329 		r = -EFAULT;
6330 		if (copy_from_user(&mce, argp, sizeof(mce)))
6331 			goto out;
6332 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6333 		break;
6334 	}
6335 	case KVM_GET_VCPU_EVENTS: {
6336 		struct kvm_vcpu_events events;
6337 
6338 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6339 
6340 		r = -EFAULT;
6341 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6342 			break;
6343 		r = 0;
6344 		break;
6345 	}
6346 	case KVM_SET_VCPU_EVENTS: {
6347 		struct kvm_vcpu_events events;
6348 
6349 		r = -EFAULT;
6350 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6351 			break;
6352 
6353 		kvm_vcpu_srcu_read_lock(vcpu);
6354 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6355 		kvm_vcpu_srcu_read_unlock(vcpu);
6356 		break;
6357 	}
6358 	case KVM_GET_DEBUGREGS: {
6359 		struct kvm_debugregs dbgregs;
6360 
6361 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6362 		if (r < 0)
6363 			break;
6364 
6365 		r = -EFAULT;
6366 		if (copy_to_user(argp, &dbgregs,
6367 				 sizeof(struct kvm_debugregs)))
6368 			break;
6369 		r = 0;
6370 		break;
6371 	}
6372 	case KVM_SET_DEBUGREGS: {
6373 		struct kvm_debugregs dbgregs;
6374 
6375 		r = -EFAULT;
6376 		if (copy_from_user(&dbgregs, argp,
6377 				   sizeof(struct kvm_debugregs)))
6378 			break;
6379 
6380 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6381 		break;
6382 	}
6383 	case KVM_GET_XSAVE: {
6384 		r = -EINVAL;
6385 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6386 			break;
6387 
6388 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6389 		r = -ENOMEM;
6390 		if (!u.xsave)
6391 			break;
6392 
6393 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6394 		if (r < 0)
6395 			break;
6396 
6397 		r = -EFAULT;
6398 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6399 			break;
6400 		r = 0;
6401 		break;
6402 	}
6403 	case KVM_SET_XSAVE: {
6404 		int size = vcpu->arch.guest_fpu.uabi_size;
6405 
6406 		u.xsave = memdup_user(argp, size);
6407 		if (IS_ERR(u.xsave)) {
6408 			r = PTR_ERR(u.xsave);
6409 			goto out_nofree;
6410 		}
6411 
6412 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6413 		break;
6414 	}
6415 
6416 	case KVM_GET_XSAVE2: {
6417 		int size = vcpu->arch.guest_fpu.uabi_size;
6418 
6419 		u.xsave = kzalloc(size, GFP_KERNEL);
6420 		r = -ENOMEM;
6421 		if (!u.xsave)
6422 			break;
6423 
6424 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6425 		if (r < 0)
6426 			break;
6427 
6428 		r = -EFAULT;
6429 		if (copy_to_user(argp, u.xsave, size))
6430 			break;
6431 
6432 		r = 0;
6433 		break;
6434 	}
6435 
6436 	case KVM_GET_XCRS: {
6437 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6438 		r = -ENOMEM;
6439 		if (!u.xcrs)
6440 			break;
6441 
6442 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6443 		if (r < 0)
6444 			break;
6445 
6446 		r = -EFAULT;
6447 		if (copy_to_user(argp, u.xcrs,
6448 				 sizeof(struct kvm_xcrs)))
6449 			break;
6450 		r = 0;
6451 		break;
6452 	}
6453 	case KVM_SET_XCRS: {
6454 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6455 		if (IS_ERR(u.xcrs)) {
6456 			r = PTR_ERR(u.xcrs);
6457 			goto out_nofree;
6458 		}
6459 
6460 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6461 		break;
6462 	}
6463 	case KVM_SET_TSC_KHZ: {
6464 		u32 user_tsc_khz;
6465 
6466 		r = -EINVAL;
6467 
6468 		if (vcpu->arch.guest_tsc_protected)
6469 			goto out;
6470 
6471 		user_tsc_khz = (u32)arg;
6472 
6473 		if (kvm_caps.has_tsc_control &&
6474 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6475 			goto out;
6476 
6477 		if (user_tsc_khz == 0)
6478 			user_tsc_khz = tsc_khz;
6479 
6480 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6481 			r = 0;
6482 
6483 		goto out;
6484 	}
6485 	case KVM_GET_TSC_KHZ: {
6486 		r = vcpu->arch.virtual_tsc_khz;
6487 		goto out;
6488 	}
6489 	case KVM_KVMCLOCK_CTRL: {
6490 		r = kvm_set_guest_paused(vcpu);
6491 		goto out;
6492 	}
6493 	case KVM_ENABLE_CAP: {
6494 		struct kvm_enable_cap cap;
6495 
6496 		r = -EFAULT;
6497 		if (copy_from_user(&cap, argp, sizeof(cap)))
6498 			goto out;
6499 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6500 		break;
6501 	}
6502 	case KVM_GET_NESTED_STATE: {
6503 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6504 		u32 user_data_size;
6505 
6506 		r = -EINVAL;
6507 		if (!kvm_x86_ops.nested_ops->get_state)
6508 			break;
6509 
6510 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6511 		r = -EFAULT;
6512 		if (get_user(user_data_size, &user_kvm_nested_state->size))
6513 			break;
6514 
6515 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6516 						     user_data_size);
6517 		if (r < 0)
6518 			break;
6519 
6520 		if (r > user_data_size) {
6521 			if (put_user(r, &user_kvm_nested_state->size))
6522 				r = -EFAULT;
6523 			else
6524 				r = -E2BIG;
6525 			break;
6526 		}
6527 
6528 		r = 0;
6529 		break;
6530 	}
6531 	case KVM_SET_NESTED_STATE: {
6532 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6533 		struct kvm_nested_state kvm_state;
6534 		int idx;
6535 
6536 		r = -EINVAL;
6537 		if (!kvm_x86_ops.nested_ops->set_state)
6538 			break;
6539 
6540 		r = -EFAULT;
6541 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6542 			break;
6543 
6544 		r = -EINVAL;
6545 		if (kvm_state.size < sizeof(kvm_state))
6546 			break;
6547 
6548 		if (kvm_state.flags &
6549 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6550 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6551 		      | KVM_STATE_NESTED_GIF_SET))
6552 			break;
6553 
6554 		/* nested_run_pending implies guest_mode.  */
6555 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6556 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6557 			break;
6558 
6559 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6560 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6561 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6562 		break;
6563 	}
6564 #ifdef CONFIG_KVM_HYPERV
6565 	case KVM_GET_SUPPORTED_HV_CPUID:
6566 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6567 		break;
6568 #endif
6569 #ifdef CONFIG_KVM_XEN
6570 	case KVM_XEN_VCPU_GET_ATTR: {
6571 		struct kvm_xen_vcpu_attr xva;
6572 
6573 		r = -EFAULT;
6574 		if (copy_from_user(&xva, argp, sizeof(xva)))
6575 			goto out;
6576 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6577 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6578 			r = -EFAULT;
6579 		break;
6580 	}
6581 	case KVM_XEN_VCPU_SET_ATTR: {
6582 		struct kvm_xen_vcpu_attr xva;
6583 
6584 		r = -EFAULT;
6585 		if (copy_from_user(&xva, argp, sizeof(xva)))
6586 			goto out;
6587 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6588 		break;
6589 	}
6590 #endif
6591 	case KVM_GET_SREGS2: {
6592 		r = -EINVAL;
6593 		if (vcpu->kvm->arch.has_protected_state &&
6594 		    vcpu->arch.guest_state_protected)
6595 			goto out;
6596 
6597 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6598 		r = -ENOMEM;
6599 		if (!u.sregs2)
6600 			goto out;
6601 		__get_sregs2(vcpu, u.sregs2);
6602 		r = -EFAULT;
6603 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6604 			goto out;
6605 		r = 0;
6606 		break;
6607 	}
6608 	case KVM_SET_SREGS2: {
6609 		r = -EINVAL;
6610 		if (vcpu->kvm->arch.has_protected_state &&
6611 		    vcpu->arch.guest_state_protected)
6612 			goto out;
6613 
6614 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6615 		if (IS_ERR(u.sregs2)) {
6616 			r = PTR_ERR(u.sregs2);
6617 			u.sregs2 = NULL;
6618 			goto out;
6619 		}
6620 		r = __set_sregs2(vcpu, u.sregs2);
6621 		break;
6622 	}
6623 	case KVM_HAS_DEVICE_ATTR:
6624 	case KVM_GET_DEVICE_ATTR:
6625 	case KVM_SET_DEVICE_ATTR:
6626 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6627 		break;
6628 	case KVM_MEMORY_ENCRYPT_OP:
6629 		r = -ENOTTY;
6630 		if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6631 			goto out;
6632 		r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6633 		break;
6634 	default:
6635 		r = -EINVAL;
6636 	}
6637 out:
6638 	kfree(u.buffer);
6639 out_nofree:
6640 	vcpu_put(vcpu);
6641 	return r;
6642 }
6643 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6644 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6645 {
6646 	return VM_FAULT_SIGBUS;
6647 }
6648 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6649 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6650 {
6651 	int ret;
6652 
6653 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
6654 		return -EINVAL;
6655 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6656 	return ret;
6657 }
6658 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6659 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6660 					      u64 ident_addr)
6661 {
6662 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6663 }
6664 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6665 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6666 					 unsigned long kvm_nr_mmu_pages)
6667 {
6668 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6669 		return -EINVAL;
6670 
6671 	mutex_lock(&kvm->slots_lock);
6672 
6673 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6674 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6675 
6676 	mutex_unlock(&kvm->slots_lock);
6677 	return 0;
6678 }
6679 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6680 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6681 {
6682 
6683 	/*
6684 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6685 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6686 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6687 	 * VM-Exit.
6688 	 */
6689 	struct kvm_vcpu *vcpu;
6690 	unsigned long i;
6691 
6692 	if (!kvm->arch.cpu_dirty_log_size)
6693 		return;
6694 
6695 	kvm_for_each_vcpu(i, vcpu, kvm)
6696 		kvm_vcpu_kick(vcpu);
6697 }
6698 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6699 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6700 			    struct kvm_enable_cap *cap)
6701 {
6702 	int r;
6703 
6704 	if (cap->flags)
6705 		return -EINVAL;
6706 
6707 	switch (cap->cap) {
6708 	case KVM_CAP_DISABLE_QUIRKS2:
6709 		r = -EINVAL;
6710 		if (cap->args[0] & ~kvm_caps.supported_quirks)
6711 			break;
6712 		fallthrough;
6713 	case KVM_CAP_DISABLE_QUIRKS:
6714 		kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6715 		r = 0;
6716 		break;
6717 	case KVM_CAP_SPLIT_IRQCHIP: {
6718 		mutex_lock(&kvm->lock);
6719 		r = -EINVAL;
6720 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6721 			goto split_irqchip_unlock;
6722 		r = -EEXIST;
6723 		if (irqchip_in_kernel(kvm))
6724 			goto split_irqchip_unlock;
6725 		if (kvm->created_vcpus)
6726 			goto split_irqchip_unlock;
6727 		/* Pairs with irqchip_in_kernel. */
6728 		smp_wmb();
6729 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6730 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6731 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6732 		r = 0;
6733 split_irqchip_unlock:
6734 		mutex_unlock(&kvm->lock);
6735 		break;
6736 	}
6737 	case KVM_CAP_X2APIC_API:
6738 		r = -EINVAL;
6739 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6740 			break;
6741 
6742 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6743 			kvm->arch.x2apic_format = true;
6744 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6745 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6746 
6747 		r = 0;
6748 		break;
6749 	case KVM_CAP_X86_DISABLE_EXITS:
6750 		r = -EINVAL;
6751 		if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6752 			break;
6753 
6754 		mutex_lock(&kvm->lock);
6755 		if (kvm->created_vcpus)
6756 			goto disable_exits_unlock;
6757 
6758 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6759 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6760 
6761 		if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6762 		    cpu_smt_possible() &&
6763 		    (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
6764 				      KVM_X86_DISABLE_EXITS_APERFMPERF)))
6765 			pr_warn_once(SMT_RSB_MSG);
6766 
6767 		kvm_disable_exits(kvm, cap->args[0]);
6768 		r = 0;
6769 disable_exits_unlock:
6770 		mutex_unlock(&kvm->lock);
6771 		break;
6772 	case KVM_CAP_MSR_PLATFORM_INFO:
6773 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6774 		r = 0;
6775 		break;
6776 	case KVM_CAP_EXCEPTION_PAYLOAD:
6777 		kvm->arch.exception_payload_enabled = cap->args[0];
6778 		r = 0;
6779 		break;
6780 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6781 		kvm->arch.triple_fault_event = cap->args[0];
6782 		r = 0;
6783 		break;
6784 	case KVM_CAP_X86_USER_SPACE_MSR:
6785 		r = -EINVAL;
6786 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6787 			break;
6788 		kvm->arch.user_space_msr_mask = cap->args[0];
6789 		r = 0;
6790 		break;
6791 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6792 		r = -EINVAL;
6793 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6794 			break;
6795 
6796 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6797 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6798 			break;
6799 
6800 		if (kvm_caps.has_bus_lock_exit &&
6801 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6802 			kvm->arch.bus_lock_detection_enabled = true;
6803 		r = 0;
6804 		break;
6805 #ifdef CONFIG_X86_SGX_KVM
6806 	case KVM_CAP_SGX_ATTRIBUTE: {
6807 		unsigned long allowed_attributes = 0;
6808 
6809 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6810 		if (r)
6811 			break;
6812 
6813 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6814 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6815 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6816 			kvm->arch.sgx_provisioning_allowed = true;
6817 		else
6818 			r = -EINVAL;
6819 		break;
6820 	}
6821 #endif
6822 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6823 		r = -EINVAL;
6824 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6825 			break;
6826 
6827 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6828 		break;
6829 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6830 		r = -EINVAL;
6831 		if (!kvm_x86_ops.vm_move_enc_context_from)
6832 			break;
6833 
6834 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6835 		break;
6836 	case KVM_CAP_EXIT_HYPERCALL:
6837 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6838 			r = -EINVAL;
6839 			break;
6840 		}
6841 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6842 		r = 0;
6843 		break;
6844 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6845 		r = -EINVAL;
6846 		if (cap->args[0] & ~1)
6847 			break;
6848 		kvm->arch.exit_on_emulation_error = cap->args[0];
6849 		r = 0;
6850 		break;
6851 	case KVM_CAP_PMU_CAPABILITY:
6852 		r = -EINVAL;
6853 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6854 			break;
6855 
6856 		mutex_lock(&kvm->lock);
6857 		if (!kvm->created_vcpus) {
6858 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6859 			r = 0;
6860 		}
6861 		mutex_unlock(&kvm->lock);
6862 		break;
6863 	case KVM_CAP_MAX_VCPU_ID:
6864 		r = -EINVAL;
6865 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6866 			break;
6867 
6868 		mutex_lock(&kvm->lock);
6869 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6870 			;
6871 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6872 			r = 0;
6873 		} else if (!kvm->arch.max_vcpu_ids) {
6874 			kvm->arch.max_vcpu_ids = cap->args[0];
6875 			r = 0;
6876 		}
6877 		mutex_unlock(&kvm->lock);
6878 		break;
6879 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6880 		r = -EINVAL;
6881 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6882 			break;
6883 		if (!kvm_caps.has_notify_vmexit)
6884 			break;
6885 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6886 			break;
6887 		mutex_lock(&kvm->lock);
6888 		if (!kvm->created_vcpus) {
6889 			kvm->arch.notify_window = cap->args[0] >> 32;
6890 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6891 			r = 0;
6892 		}
6893 		mutex_unlock(&kvm->lock);
6894 		break;
6895 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6896 		r = -EINVAL;
6897 
6898 		/*
6899 		 * Since the risk of disabling NX hugepages is a guest crashing
6900 		 * the system, ensure the userspace process has permission to
6901 		 * reboot the system.
6902 		 *
6903 		 * Note that unlike the reboot() syscall, the process must have
6904 		 * this capability in the root namespace because exposing
6905 		 * /dev/kvm into a container does not limit the scope of the
6906 		 * iTLB multihit bug to that container. In other words,
6907 		 * this must use capable(), not ns_capable().
6908 		 */
6909 		if (!capable(CAP_SYS_BOOT)) {
6910 			r = -EPERM;
6911 			break;
6912 		}
6913 
6914 		if (cap->args[0])
6915 			break;
6916 
6917 		mutex_lock(&kvm->lock);
6918 		if (!kvm->created_vcpus) {
6919 			kvm->arch.disable_nx_huge_pages = true;
6920 			r = 0;
6921 		}
6922 		mutex_unlock(&kvm->lock);
6923 		break;
6924 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6925 		u64 bus_cycle_ns = cap->args[0];
6926 		u64 unused;
6927 
6928 		/*
6929 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
6930 		 * divide value that can be programmed in APIC_TDCR.
6931 		 */
6932 		r = -EINVAL;
6933 		if (!bus_cycle_ns ||
6934 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6935 			break;
6936 
6937 		r = 0;
6938 		mutex_lock(&kvm->lock);
6939 		if (!irqchip_in_kernel(kvm))
6940 			r = -ENXIO;
6941 		else if (kvm->created_vcpus)
6942 			r = -EINVAL;
6943 		else
6944 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6945 		mutex_unlock(&kvm->lock);
6946 		break;
6947 	}
6948 	default:
6949 		r = -EINVAL;
6950 		break;
6951 	}
6952 	return r;
6953 }
6954 
kvm_alloc_msr_filter(bool default_allow)6955 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6956 {
6957 	struct kvm_x86_msr_filter *msr_filter;
6958 
6959 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6960 	if (!msr_filter)
6961 		return NULL;
6962 
6963 	msr_filter->default_allow = default_allow;
6964 	return msr_filter;
6965 }
6966 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6967 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6968 {
6969 	u32 i;
6970 
6971 	if (!msr_filter)
6972 		return;
6973 
6974 	for (i = 0; i < msr_filter->count; i++)
6975 		kfree(msr_filter->ranges[i].bitmap);
6976 
6977 	kfree(msr_filter);
6978 }
6979 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6980 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6981 			      struct kvm_msr_filter_range *user_range)
6982 {
6983 	unsigned long *bitmap;
6984 	size_t bitmap_size;
6985 
6986 	if (!user_range->nmsrs)
6987 		return 0;
6988 
6989 	if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6990 		return -EINVAL;
6991 
6992 	if (!user_range->flags)
6993 		return -EINVAL;
6994 
6995 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6996 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6997 		return -EINVAL;
6998 
6999 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
7000 	if (IS_ERR(bitmap))
7001 		return PTR_ERR(bitmap);
7002 
7003 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
7004 		.flags = user_range->flags,
7005 		.base = user_range->base,
7006 		.nmsrs = user_range->nmsrs,
7007 		.bitmap = bitmap,
7008 	};
7009 
7010 	msr_filter->count++;
7011 	return 0;
7012 }
7013 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)7014 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
7015 				       struct kvm_msr_filter *filter)
7016 {
7017 	struct kvm_x86_msr_filter *new_filter, *old_filter;
7018 	bool default_allow;
7019 	bool empty = true;
7020 	int r;
7021 	u32 i;
7022 
7023 	if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
7024 		return -EINVAL;
7025 
7026 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
7027 		empty &= !filter->ranges[i].nmsrs;
7028 
7029 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
7030 	if (empty && !default_allow)
7031 		return -EINVAL;
7032 
7033 	new_filter = kvm_alloc_msr_filter(default_allow);
7034 	if (!new_filter)
7035 		return -ENOMEM;
7036 
7037 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
7038 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
7039 		if (r) {
7040 			kvm_free_msr_filter(new_filter);
7041 			return r;
7042 		}
7043 	}
7044 
7045 	mutex_lock(&kvm->lock);
7046 	old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
7047 					 mutex_is_locked(&kvm->lock));
7048 	mutex_unlock(&kvm->lock);
7049 	synchronize_srcu(&kvm->srcu);
7050 
7051 	kvm_free_msr_filter(old_filter);
7052 
7053 	/*
7054 	 * Recalc MSR intercepts as userspace may want to intercept accesses to
7055 	 * MSRs that KVM would otherwise pass through to the guest.
7056 	 */
7057 	kvm_make_all_cpus_request(kvm, KVM_REQ_RECALC_INTERCEPTS);
7058 
7059 	return 0;
7060 }
7061 
7062 #ifdef CONFIG_KVM_COMPAT
7063 /* for KVM_X86_SET_MSR_FILTER */
7064 struct kvm_msr_filter_range_compat {
7065 	__u32 flags;
7066 	__u32 nmsrs;
7067 	__u32 base;
7068 	__u32 bitmap;
7069 };
7070 
7071 struct kvm_msr_filter_compat {
7072 	__u32 flags;
7073 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
7074 };
7075 
7076 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
7077 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7078 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
7079 			      unsigned long arg)
7080 {
7081 	void __user *argp = (void __user *)arg;
7082 	struct kvm *kvm = filp->private_data;
7083 	long r = -ENOTTY;
7084 
7085 	switch (ioctl) {
7086 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
7087 		struct kvm_msr_filter __user *user_msr_filter = argp;
7088 		struct kvm_msr_filter_compat filter_compat;
7089 		struct kvm_msr_filter filter;
7090 		int i;
7091 
7092 		if (copy_from_user(&filter_compat, user_msr_filter,
7093 				   sizeof(filter_compat)))
7094 			return -EFAULT;
7095 
7096 		filter.flags = filter_compat.flags;
7097 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
7098 			struct kvm_msr_filter_range_compat *cr;
7099 
7100 			cr = &filter_compat.ranges[i];
7101 			filter.ranges[i] = (struct kvm_msr_filter_range) {
7102 				.flags = cr->flags,
7103 				.nmsrs = cr->nmsrs,
7104 				.base = cr->base,
7105 				.bitmap = (__u8 *)(ulong)cr->bitmap,
7106 			};
7107 		}
7108 
7109 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7110 		break;
7111 	}
7112 	}
7113 
7114 	return r;
7115 }
7116 #endif
7117 
7118 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)7119 static int kvm_arch_suspend_notifier(struct kvm *kvm)
7120 {
7121 	struct kvm_vcpu *vcpu;
7122 	unsigned long i;
7123 
7124 	/*
7125 	 * Ignore the return, marking the guest paused only "fails" if the vCPU
7126 	 * isn't using kvmclock; continuing on is correct and desirable.
7127 	 */
7128 	kvm_for_each_vcpu(i, vcpu, kvm)
7129 		(void)kvm_set_guest_paused(vcpu);
7130 
7131 	return NOTIFY_DONE;
7132 }
7133 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)7134 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
7135 {
7136 	switch (state) {
7137 	case PM_HIBERNATION_PREPARE:
7138 	case PM_SUSPEND_PREPARE:
7139 		return kvm_arch_suspend_notifier(kvm);
7140 	}
7141 
7142 	return NOTIFY_DONE;
7143 }
7144 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7145 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7146 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7147 {
7148 	struct kvm_clock_data data = { 0 };
7149 
7150 	get_kvmclock(kvm, &data);
7151 	if (copy_to_user(argp, &data, sizeof(data)))
7152 		return -EFAULT;
7153 
7154 	return 0;
7155 }
7156 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7157 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7158 {
7159 	struct kvm_arch *ka = &kvm->arch;
7160 	struct kvm_clock_data data;
7161 	u64 now_raw_ns;
7162 
7163 	if (copy_from_user(&data, argp, sizeof(data)))
7164 		return -EFAULT;
7165 
7166 	/*
7167 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7168 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7169 	 */
7170 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7171 		return -EINVAL;
7172 
7173 	kvm_hv_request_tsc_page_update(kvm);
7174 	kvm_start_pvclock_update(kvm);
7175 	pvclock_update_vm_gtod_copy(kvm);
7176 
7177 	/*
7178 	 * This pairs with kvm_guest_time_update(): when masterclock is
7179 	 * in use, we use master_kernel_ns + kvmclock_offset to set
7180 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7181 	 * is slightly ahead) here we risk going negative on unsigned
7182 	 * 'system_time' when 'data.clock' is very small.
7183 	 */
7184 	if (data.flags & KVM_CLOCK_REALTIME) {
7185 		u64 now_real_ns = ktime_get_real_ns();
7186 
7187 		/*
7188 		 * Avoid stepping the kvmclock backwards.
7189 		 */
7190 		if (now_real_ns > data.realtime)
7191 			data.clock += now_real_ns - data.realtime;
7192 	}
7193 
7194 	if (ka->use_master_clock)
7195 		now_raw_ns = ka->master_kernel_ns;
7196 	else
7197 		now_raw_ns = get_kvmclock_base_ns();
7198 	ka->kvmclock_offset = data.clock - now_raw_ns;
7199 	kvm_end_pvclock_update(kvm);
7200 	return 0;
7201 }
7202 
kvm_arch_vcpu_unlocked_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7203 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
7204 				  unsigned long arg)
7205 {
7206 	struct kvm_vcpu *vcpu = filp->private_data;
7207 	void __user *argp = (void __user *)arg;
7208 
7209 	if (ioctl == KVM_MEMORY_ENCRYPT_OP &&
7210 	    kvm_x86_ops.vcpu_mem_enc_unlocked_ioctl)
7211 		return kvm_x86_call(vcpu_mem_enc_unlocked_ioctl)(vcpu, argp);
7212 
7213 	return -ENOIOCTLCMD;
7214 }
7215 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7216 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7217 {
7218 	struct kvm *kvm = filp->private_data;
7219 	void __user *argp = (void __user *)arg;
7220 	int r = -ENOTTY;
7221 
7222 #ifdef CONFIG_KVM_IOAPIC
7223 	/*
7224 	 * This union makes it completely explicit to gcc-3.x
7225 	 * that these three variables' stack usage should be
7226 	 * combined, not added together.
7227 	 */
7228 	union {
7229 		struct kvm_pit_state ps;
7230 		struct kvm_pit_state2 ps2;
7231 		struct kvm_pit_config pit_config;
7232 	} u;
7233 #endif
7234 
7235 	switch (ioctl) {
7236 	case KVM_SET_TSS_ADDR:
7237 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7238 		break;
7239 	case KVM_SET_IDENTITY_MAP_ADDR: {
7240 		u64 ident_addr;
7241 
7242 		mutex_lock(&kvm->lock);
7243 		r = -EINVAL;
7244 		if (kvm->created_vcpus)
7245 			goto set_identity_unlock;
7246 		r = -EFAULT;
7247 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7248 			goto set_identity_unlock;
7249 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7250 set_identity_unlock:
7251 		mutex_unlock(&kvm->lock);
7252 		break;
7253 	}
7254 	case KVM_SET_NR_MMU_PAGES:
7255 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7256 		break;
7257 #ifdef CONFIG_KVM_IOAPIC
7258 	case KVM_CREATE_IRQCHIP: {
7259 		mutex_lock(&kvm->lock);
7260 
7261 		r = -EEXIST;
7262 		if (irqchip_in_kernel(kvm))
7263 			goto create_irqchip_unlock;
7264 
7265 		/*
7266 		 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
7267 		 * i.e. if KVM can't intercept EOIs and thus can't properly
7268 		 * emulate level-triggered interrupts.
7269 		 */
7270 		r = -ENOTTY;
7271 		if (kvm->arch.has_protected_eoi)
7272 			goto create_irqchip_unlock;
7273 
7274 		r = -EINVAL;
7275 		if (kvm->created_vcpus)
7276 			goto create_irqchip_unlock;
7277 
7278 		r = kvm_pic_init(kvm);
7279 		if (r)
7280 			goto create_irqchip_unlock;
7281 
7282 		r = kvm_ioapic_init(kvm);
7283 		if (r) {
7284 			kvm_pic_destroy(kvm);
7285 			goto create_irqchip_unlock;
7286 		}
7287 
7288 		r = kvm_setup_default_ioapic_and_pic_routing(kvm);
7289 		if (r) {
7290 			kvm_ioapic_destroy(kvm);
7291 			kvm_pic_destroy(kvm);
7292 			goto create_irqchip_unlock;
7293 		}
7294 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7295 		smp_wmb();
7296 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7297 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7298 	create_irqchip_unlock:
7299 		mutex_unlock(&kvm->lock);
7300 		break;
7301 	}
7302 	case KVM_CREATE_PIT:
7303 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7304 		goto create_pit;
7305 	case KVM_CREATE_PIT2:
7306 		r = -EFAULT;
7307 		if (copy_from_user(&u.pit_config, argp,
7308 				   sizeof(struct kvm_pit_config)))
7309 			goto out;
7310 	create_pit:
7311 		mutex_lock(&kvm->lock);
7312 		r = -EEXIST;
7313 		if (kvm->arch.vpit)
7314 			goto create_pit_unlock;
7315 		r = -ENOENT;
7316 		if (!pic_in_kernel(kvm))
7317 			goto create_pit_unlock;
7318 		r = -ENOMEM;
7319 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7320 		if (kvm->arch.vpit)
7321 			r = 0;
7322 	create_pit_unlock:
7323 		mutex_unlock(&kvm->lock);
7324 		break;
7325 	case KVM_GET_IRQCHIP: {
7326 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7327 		struct kvm_irqchip *chip;
7328 
7329 		chip = memdup_user(argp, sizeof(*chip));
7330 		if (IS_ERR(chip)) {
7331 			r = PTR_ERR(chip);
7332 			goto out;
7333 		}
7334 
7335 		r = -ENXIO;
7336 		if (!irqchip_full(kvm))
7337 			goto get_irqchip_out;
7338 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7339 		if (r)
7340 			goto get_irqchip_out;
7341 		r = -EFAULT;
7342 		if (copy_to_user(argp, chip, sizeof(*chip)))
7343 			goto get_irqchip_out;
7344 		r = 0;
7345 	get_irqchip_out:
7346 		kfree(chip);
7347 		break;
7348 	}
7349 	case KVM_SET_IRQCHIP: {
7350 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7351 		struct kvm_irqchip *chip;
7352 
7353 		chip = memdup_user(argp, sizeof(*chip));
7354 		if (IS_ERR(chip)) {
7355 			r = PTR_ERR(chip);
7356 			goto out;
7357 		}
7358 
7359 		r = -ENXIO;
7360 		if (!irqchip_full(kvm))
7361 			goto set_irqchip_out;
7362 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7363 	set_irqchip_out:
7364 		kfree(chip);
7365 		break;
7366 	}
7367 	case KVM_GET_PIT: {
7368 		r = -EFAULT;
7369 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7370 			goto out;
7371 		r = -ENXIO;
7372 		if (!kvm->arch.vpit)
7373 			goto out;
7374 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7375 		if (r)
7376 			goto out;
7377 		r = -EFAULT;
7378 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7379 			goto out;
7380 		r = 0;
7381 		break;
7382 	}
7383 	case KVM_SET_PIT: {
7384 		r = -EFAULT;
7385 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7386 			goto out;
7387 		mutex_lock(&kvm->lock);
7388 		r = -ENXIO;
7389 		if (!kvm->arch.vpit)
7390 			goto set_pit_out;
7391 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7392 set_pit_out:
7393 		mutex_unlock(&kvm->lock);
7394 		break;
7395 	}
7396 	case KVM_GET_PIT2: {
7397 		r = -ENXIO;
7398 		if (!kvm->arch.vpit)
7399 			goto out;
7400 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7401 		if (r)
7402 			goto out;
7403 		r = -EFAULT;
7404 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7405 			goto out;
7406 		r = 0;
7407 		break;
7408 	}
7409 	case KVM_SET_PIT2: {
7410 		r = -EFAULT;
7411 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7412 			goto out;
7413 		mutex_lock(&kvm->lock);
7414 		r = -ENXIO;
7415 		if (!kvm->arch.vpit)
7416 			goto set_pit2_out;
7417 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7418 set_pit2_out:
7419 		mutex_unlock(&kvm->lock);
7420 		break;
7421 	}
7422 	case KVM_REINJECT_CONTROL: {
7423 		struct kvm_reinject_control control;
7424 		r =  -EFAULT;
7425 		if (copy_from_user(&control, argp, sizeof(control)))
7426 			goto out;
7427 		r = -ENXIO;
7428 		if (!kvm->arch.vpit)
7429 			goto out;
7430 		r = kvm_vm_ioctl_reinject(kvm, &control);
7431 		break;
7432 	}
7433 #endif
7434 	case KVM_SET_BOOT_CPU_ID:
7435 		r = 0;
7436 		mutex_lock(&kvm->lock);
7437 		if (kvm->created_vcpus)
7438 			r = -EBUSY;
7439 		else if (arg > KVM_MAX_VCPU_IDS ||
7440 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7441 			r = -EINVAL;
7442 		else
7443 			kvm->arch.bsp_vcpu_id = arg;
7444 		mutex_unlock(&kvm->lock);
7445 		break;
7446 #ifdef CONFIG_KVM_XEN
7447 	case KVM_XEN_HVM_CONFIG: {
7448 		struct kvm_xen_hvm_config xhc;
7449 		r = -EFAULT;
7450 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
7451 			goto out;
7452 		r = kvm_xen_hvm_config(kvm, &xhc);
7453 		break;
7454 	}
7455 	case KVM_XEN_HVM_GET_ATTR: {
7456 		struct kvm_xen_hvm_attr xha;
7457 
7458 		r = -EFAULT;
7459 		if (copy_from_user(&xha, argp, sizeof(xha)))
7460 			goto out;
7461 		r = kvm_xen_hvm_get_attr(kvm, &xha);
7462 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7463 			r = -EFAULT;
7464 		break;
7465 	}
7466 	case KVM_XEN_HVM_SET_ATTR: {
7467 		struct kvm_xen_hvm_attr xha;
7468 
7469 		r = -EFAULT;
7470 		if (copy_from_user(&xha, argp, sizeof(xha)))
7471 			goto out;
7472 		r = kvm_xen_hvm_set_attr(kvm, &xha);
7473 		break;
7474 	}
7475 	case KVM_XEN_HVM_EVTCHN_SEND: {
7476 		struct kvm_irq_routing_xen_evtchn uxe;
7477 
7478 		r = -EFAULT;
7479 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
7480 			goto out;
7481 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7482 		break;
7483 	}
7484 #endif
7485 	case KVM_SET_CLOCK:
7486 		r = kvm_vm_ioctl_set_clock(kvm, argp);
7487 		break;
7488 	case KVM_GET_CLOCK:
7489 		r = kvm_vm_ioctl_get_clock(kvm, argp);
7490 		break;
7491 	case KVM_SET_TSC_KHZ: {
7492 		u32 user_tsc_khz;
7493 
7494 		r = -EINVAL;
7495 		user_tsc_khz = (u32)arg;
7496 
7497 		if (kvm_caps.has_tsc_control &&
7498 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7499 			goto out;
7500 
7501 		if (user_tsc_khz == 0)
7502 			user_tsc_khz = tsc_khz;
7503 
7504 		mutex_lock(&kvm->lock);
7505 		if (!kvm->created_vcpus) {
7506 			WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7507 			r = 0;
7508 		}
7509 		mutex_unlock(&kvm->lock);
7510 		goto out;
7511 	}
7512 	case KVM_GET_TSC_KHZ: {
7513 		r = READ_ONCE(kvm->arch.default_tsc_khz);
7514 		goto out;
7515 	}
7516 	case KVM_MEMORY_ENCRYPT_OP:
7517 		r = -ENOTTY;
7518 		if (!kvm_x86_ops.mem_enc_ioctl)
7519 			goto out;
7520 
7521 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7522 		break;
7523 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
7524 		struct kvm_enc_region region;
7525 
7526 		r = -EFAULT;
7527 		if (copy_from_user(&region, argp, sizeof(region)))
7528 			goto out;
7529 
7530 		r = -ENOTTY;
7531 		if (!kvm_x86_ops.mem_enc_register_region)
7532 			goto out;
7533 
7534 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
7535 		break;
7536 	}
7537 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7538 		struct kvm_enc_region region;
7539 
7540 		r = -EFAULT;
7541 		if (copy_from_user(&region, argp, sizeof(region)))
7542 			goto out;
7543 
7544 		r = -ENOTTY;
7545 		if (!kvm_x86_ops.mem_enc_unregister_region)
7546 			goto out;
7547 
7548 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
7549 		break;
7550 	}
7551 #ifdef CONFIG_KVM_HYPERV
7552 	case KVM_HYPERV_EVENTFD: {
7553 		struct kvm_hyperv_eventfd hvevfd;
7554 
7555 		r = -EFAULT;
7556 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7557 			goto out;
7558 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7559 		break;
7560 	}
7561 #endif
7562 	case KVM_SET_PMU_EVENT_FILTER:
7563 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7564 		break;
7565 	case KVM_X86_SET_MSR_FILTER: {
7566 		struct kvm_msr_filter __user *user_msr_filter = argp;
7567 		struct kvm_msr_filter filter;
7568 
7569 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7570 			return -EFAULT;
7571 
7572 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7573 		break;
7574 	}
7575 	default:
7576 		r = -ENOTTY;
7577 	}
7578 out:
7579 	return r;
7580 }
7581 
kvm_probe_feature_msr(u32 msr_index)7582 static void kvm_probe_feature_msr(u32 msr_index)
7583 {
7584 	u64 data;
7585 
7586 	if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7587 		return;
7588 
7589 	msr_based_features[num_msr_based_features++] = msr_index;
7590 }
7591 
kvm_probe_msr_to_save(u32 msr_index)7592 static void kvm_probe_msr_to_save(u32 msr_index)
7593 {
7594 	u32 dummy[2];
7595 
7596 	if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7597 		return;
7598 
7599 	/*
7600 	 * Even MSRs that are valid in the host may not be exposed to guests in
7601 	 * some cases.
7602 	 */
7603 	switch (msr_index) {
7604 	case MSR_IA32_BNDCFGS:
7605 		if (!kvm_mpx_supported())
7606 			return;
7607 		break;
7608 	case MSR_TSC_AUX:
7609 		if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7610 		    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7611 			return;
7612 		break;
7613 	case MSR_IA32_UMWAIT_CONTROL:
7614 		if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7615 			return;
7616 		break;
7617 	case MSR_IA32_RTIT_CTL:
7618 	case MSR_IA32_RTIT_STATUS:
7619 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7620 			return;
7621 		break;
7622 	case MSR_IA32_RTIT_CR3_MATCH:
7623 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7624 		    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7625 			return;
7626 		break;
7627 	case MSR_IA32_RTIT_OUTPUT_BASE:
7628 	case MSR_IA32_RTIT_OUTPUT_MASK:
7629 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7630 		    (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7631 		     !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7632 			return;
7633 		break;
7634 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7635 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7636 		    (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7637 		     intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7638 			return;
7639 		break;
7640 	case MSR_ARCH_PERFMON_PERFCTR0 ...
7641 	     MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7642 		if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7643 		    kvm_pmu_cap.num_counters_gp)
7644 			return;
7645 		break;
7646 	case MSR_ARCH_PERFMON_EVENTSEL0 ...
7647 	     MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7648 		if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7649 		    kvm_pmu_cap.num_counters_gp)
7650 			return;
7651 		break;
7652 	case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7653 	     MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7654 		if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7655 		    kvm_pmu_cap.num_counters_fixed)
7656 			return;
7657 		break;
7658 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7659 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7660 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7661 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
7662 		if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7663 			return;
7664 		break;
7665 	case MSR_IA32_XFD:
7666 	case MSR_IA32_XFD_ERR:
7667 		if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7668 			return;
7669 		break;
7670 	case MSR_IA32_TSX_CTRL:
7671 		if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7672 			return;
7673 		break;
7674 	case MSR_IA32_XSS:
7675 		if (!kvm_caps.supported_xss)
7676 			return;
7677 		break;
7678 	case MSR_IA32_U_CET:
7679 	case MSR_IA32_S_CET:
7680 		if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7681 		    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7682 			return;
7683 		break;
7684 	case MSR_IA32_INT_SSP_TAB:
7685 		if (!kvm_cpu_cap_has(X86_FEATURE_LM))
7686 			return;
7687 		fallthrough;
7688 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
7689 		if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK))
7690 			return;
7691 		break;
7692 	default:
7693 		break;
7694 	}
7695 
7696 	msrs_to_save[num_msrs_to_save++] = msr_index;
7697 }
7698 
kvm_init_msr_lists(void)7699 static void kvm_init_msr_lists(void)
7700 {
7701 	unsigned i;
7702 
7703 	BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7704 			 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7705 
7706 	num_msrs_to_save = 0;
7707 	num_emulated_msrs = 0;
7708 	num_msr_based_features = 0;
7709 
7710 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7711 		kvm_probe_msr_to_save(msrs_to_save_base[i]);
7712 
7713 	if (enable_pmu) {
7714 		for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7715 			kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7716 	}
7717 
7718 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7719 		if (!kvm_x86_call(has_emulated_msr)(NULL,
7720 						    emulated_msrs_all[i]))
7721 			continue;
7722 
7723 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7724 	}
7725 
7726 	for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7727 		kvm_probe_feature_msr(i);
7728 
7729 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7730 		kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7731 }
7732 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7733 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7734 			   const void *v)
7735 {
7736 	int handled = 0;
7737 	int n;
7738 
7739 	do {
7740 		n = min(len, 8);
7741 		if (!(lapic_in_kernel(vcpu) &&
7742 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7743 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7744 			break;
7745 		handled += n;
7746 		addr += n;
7747 		len -= n;
7748 		v += n;
7749 	} while (len);
7750 
7751 	return handled;
7752 }
7753 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7754 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7755 {
7756 	int handled = 0;
7757 	int n;
7758 
7759 	do {
7760 		n = min(len, 8);
7761 		if (!(lapic_in_kernel(vcpu) &&
7762 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7763 					 addr, n, v))
7764 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7765 			break;
7766 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7767 		handled += n;
7768 		addr += n;
7769 		len -= n;
7770 		v += n;
7771 	} while (len);
7772 
7773 	return handled;
7774 }
7775 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7776 void kvm_set_segment(struct kvm_vcpu *vcpu,
7777 		     struct kvm_segment *var, int seg)
7778 {
7779 	kvm_x86_call(set_segment)(vcpu, var, seg);
7780 }
7781 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7782 void kvm_get_segment(struct kvm_vcpu *vcpu,
7783 		     struct kvm_segment *var, int seg)
7784 {
7785 	kvm_x86_call(get_segment)(vcpu, var, seg);
7786 }
7787 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7788 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7789 			   struct x86_exception *exception)
7790 {
7791 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7792 	gpa_t t_gpa;
7793 
7794 	BUG_ON(!mmu_is_nested(vcpu));
7795 
7796 	/* NPT walks are always user-walks */
7797 	access |= PFERR_USER_MASK;
7798 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7799 
7800 	return t_gpa;
7801 }
7802 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7803 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7804 			      struct x86_exception *exception)
7805 {
7806 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7807 
7808 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7809 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7810 }
7811 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
7812 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7813 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7814 			       struct x86_exception *exception)
7815 {
7816 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7817 
7818 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7819 	access |= PFERR_WRITE_MASK;
7820 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7821 }
7822 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
7823 
7824 /* 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)7825 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7826 				struct x86_exception *exception)
7827 {
7828 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7829 
7830 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7831 }
7832 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7833 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7834 				      struct kvm_vcpu *vcpu, u64 access,
7835 				      struct x86_exception *exception)
7836 {
7837 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7838 	void *data = val;
7839 	int r = X86EMUL_CONTINUE;
7840 
7841 	while (bytes) {
7842 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7843 		unsigned offset = addr & (PAGE_SIZE-1);
7844 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7845 		int ret;
7846 
7847 		if (gpa == INVALID_GPA)
7848 			return X86EMUL_PROPAGATE_FAULT;
7849 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7850 					       offset, toread);
7851 		if (ret < 0) {
7852 			r = X86EMUL_IO_NEEDED;
7853 			goto out;
7854 		}
7855 
7856 		bytes -= toread;
7857 		data += toread;
7858 		addr += toread;
7859 	}
7860 out:
7861 	return r;
7862 }
7863 
7864 /* 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)7865 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7866 				gva_t addr, void *val, unsigned int bytes,
7867 				struct x86_exception *exception)
7868 {
7869 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7870 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7871 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7872 	unsigned offset;
7873 	int ret;
7874 
7875 	/* Inline kvm_read_guest_virt_helper for speed.  */
7876 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7877 				    exception);
7878 	if (unlikely(gpa == INVALID_GPA))
7879 		return X86EMUL_PROPAGATE_FAULT;
7880 
7881 	offset = addr & (PAGE_SIZE-1);
7882 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7883 		bytes = (unsigned)PAGE_SIZE - offset;
7884 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7885 				       offset, bytes);
7886 	if (unlikely(ret < 0))
7887 		return X86EMUL_IO_NEEDED;
7888 
7889 	return X86EMUL_CONTINUE;
7890 }
7891 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7892 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7893 			       gva_t addr, void *val, unsigned int bytes,
7894 			       struct x86_exception *exception)
7895 {
7896 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7897 
7898 	/*
7899 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7900 	 * is returned, but our callers are not ready for that and they blindly
7901 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7902 	 * uninitialized kernel stack memory into cr2 and error code.
7903 	 */
7904 	memset(exception, 0, sizeof(*exception));
7905 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7906 					  exception);
7907 }
7908 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
7909 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7910 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7911 			     gva_t addr, void *val, unsigned int bytes,
7912 			     struct x86_exception *exception, bool system)
7913 {
7914 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7915 	u64 access = 0;
7916 
7917 	if (system)
7918 		access |= PFERR_IMPLICIT_ACCESS;
7919 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7920 		access |= PFERR_USER_MASK;
7921 
7922 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7923 }
7924 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7925 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7926 				      struct kvm_vcpu *vcpu, u64 access,
7927 				      struct x86_exception *exception)
7928 {
7929 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7930 	void *data = val;
7931 	int r = X86EMUL_CONTINUE;
7932 
7933 	while (bytes) {
7934 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7935 		unsigned offset = addr & (PAGE_SIZE-1);
7936 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7937 		int ret;
7938 
7939 		if (gpa == INVALID_GPA)
7940 			return X86EMUL_PROPAGATE_FAULT;
7941 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7942 		if (ret < 0) {
7943 			r = X86EMUL_IO_NEEDED;
7944 			goto out;
7945 		}
7946 
7947 		bytes -= towrite;
7948 		data += towrite;
7949 		addr += towrite;
7950 	}
7951 out:
7952 	return r;
7953 }
7954 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7955 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7956 			      unsigned int bytes, struct x86_exception *exception,
7957 			      bool system)
7958 {
7959 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7960 	u64 access = PFERR_WRITE_MASK;
7961 
7962 	if (system)
7963 		access |= PFERR_IMPLICIT_ACCESS;
7964 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7965 		access |= PFERR_USER_MASK;
7966 
7967 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7968 					   access, exception);
7969 }
7970 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7971 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7972 				unsigned int bytes, struct x86_exception *exception)
7973 {
7974 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7975 	kvm_request_l1tf_flush_l1d();
7976 
7977 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7978 					   PFERR_WRITE_MASK, exception);
7979 }
7980 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
7981 
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7982 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7983 				  void *insn, int insn_len)
7984 {
7985 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7986 						       insn, insn_len);
7987 }
7988 
handle_ud(struct kvm_vcpu * vcpu)7989 int handle_ud(struct kvm_vcpu *vcpu)
7990 {
7991 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7992 	int fep_flags = READ_ONCE(force_emulation_prefix);
7993 	int emul_type = EMULTYPE_TRAP_UD;
7994 	char sig[5]; /* ud2; .ascii "kvm" */
7995 	struct x86_exception e;
7996 	int r;
7997 
7998 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7999 	if (r != X86EMUL_CONTINUE)
8000 		return 1;
8001 
8002 	if (fep_flags &&
8003 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
8004 				sig, sizeof(sig), &e) == 0 &&
8005 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
8006 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
8007 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
8008 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
8009 		emul_type = EMULTYPE_TRAP_UD_FORCED;
8010 	}
8011 
8012 	return kvm_emulate_instruction(vcpu, emul_type);
8013 }
8014 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
8015 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)8016 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8017 			    gpa_t gpa, bool write)
8018 {
8019 	/* For APIC access vmexit */
8020 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8021 		return 1;
8022 
8023 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
8024 		trace_vcpu_match_mmio(gva, gpa, write, true);
8025 		return 1;
8026 	}
8027 
8028 	return 0;
8029 }
8030 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)8031 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8032 				gpa_t *gpa, struct x86_exception *exception,
8033 				bool write)
8034 {
8035 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8036 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
8037 		     | (write ? PFERR_WRITE_MASK : 0);
8038 
8039 	/*
8040 	 * currently PKRU is only applied to ept enabled guest so
8041 	 * there is no pkey in EPT page table for L1 guest or EPT
8042 	 * shadow page table for L2 guest.
8043 	 */
8044 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
8045 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
8046 			      vcpu->arch.mmio_access, 0, access))) {
8047 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
8048 					(gva & (PAGE_SIZE - 1));
8049 		trace_vcpu_match_mmio(gva, *gpa, write, false);
8050 		return 1;
8051 	}
8052 
8053 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
8054 
8055 	if (*gpa == INVALID_GPA)
8056 		return -1;
8057 
8058 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
8059 }
8060 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)8061 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
8062 			const void *val, int bytes)
8063 {
8064 	int ret;
8065 
8066 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
8067 	if (ret < 0)
8068 		return 0;
8069 	kvm_page_track_write(vcpu, gpa, val, bytes);
8070 	return 1;
8071 }
8072 
8073 struct read_write_emulator_ops {
8074 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
8075 				  int bytes);
8076 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
8077 				  void *val, int bytes);
8078 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8079 			       int bytes, void *val);
8080 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8081 				    void *val, int bytes);
8082 	bool write;
8083 };
8084 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)8085 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
8086 {
8087 	if (vcpu->mmio_read_completed) {
8088 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
8089 			       vcpu->mmio_fragments[0].gpa, val);
8090 		vcpu->mmio_read_completed = 0;
8091 		return 1;
8092 	}
8093 
8094 	return 0;
8095 }
8096 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8097 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8098 			void *val, int bytes)
8099 {
8100 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
8101 }
8102 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8103 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8104 			 void *val, int bytes)
8105 {
8106 	return emulator_write_phys(vcpu, gpa, val, bytes);
8107 }
8108 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)8109 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
8110 {
8111 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
8112 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
8113 }
8114 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8115 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8116 			  void *val, int bytes)
8117 {
8118 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
8119 	return X86EMUL_IO_NEEDED;
8120 }
8121 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8122 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8123 			   void *val, int bytes)
8124 {
8125 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
8126 
8127 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
8128 	return X86EMUL_CONTINUE;
8129 }
8130 
8131 static const struct read_write_emulator_ops read_emultor = {
8132 	.read_write_prepare = read_prepare,
8133 	.read_write_emulate = read_emulate,
8134 	.read_write_mmio = vcpu_mmio_read,
8135 	.read_write_exit_mmio = read_exit_mmio,
8136 };
8137 
8138 static const struct read_write_emulator_ops write_emultor = {
8139 	.read_write_emulate = write_emulate,
8140 	.read_write_mmio = write_mmio,
8141 	.read_write_exit_mmio = write_exit_mmio,
8142 	.write = true,
8143 };
8144 
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)8145 static int emulator_read_write_onepage(unsigned long addr, void *val,
8146 				       unsigned int bytes,
8147 				       struct x86_exception *exception,
8148 				       struct kvm_vcpu *vcpu,
8149 				       const struct read_write_emulator_ops *ops)
8150 {
8151 	gpa_t gpa;
8152 	int handled, ret;
8153 	bool write = ops->write;
8154 	struct kvm_mmio_fragment *frag;
8155 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8156 
8157 	/*
8158 	 * If the exit was due to a NPF we may already have a GPA.
8159 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
8160 	 * Note, this cannot be used on string operations since string
8161 	 * operation using rep will only have the initial GPA from the NPF
8162 	 * occurred.
8163 	 */
8164 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
8165 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
8166 		gpa = ctxt->gpa_val;
8167 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
8168 	} else {
8169 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
8170 		if (ret < 0)
8171 			return X86EMUL_PROPAGATE_FAULT;
8172 	}
8173 
8174 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
8175 		return X86EMUL_CONTINUE;
8176 
8177 	/*
8178 	 * Is this MMIO handled locally?
8179 	 */
8180 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
8181 	if (handled == bytes)
8182 		return X86EMUL_CONTINUE;
8183 
8184 	gpa += handled;
8185 	bytes -= handled;
8186 	val += handled;
8187 
8188 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8189 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8190 	frag->gpa = gpa;
8191 	frag->data = val;
8192 	frag->len = bytes;
8193 	return X86EMUL_CONTINUE;
8194 }
8195 
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)8196 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8197 			unsigned long addr,
8198 			void *val, unsigned int bytes,
8199 			struct x86_exception *exception,
8200 			const struct read_write_emulator_ops *ops)
8201 {
8202 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8203 	gpa_t gpa;
8204 	int rc;
8205 
8206 	if (ops->read_write_prepare &&
8207 		  ops->read_write_prepare(vcpu, val, bytes))
8208 		return X86EMUL_CONTINUE;
8209 
8210 	vcpu->mmio_nr_fragments = 0;
8211 
8212 	/* Crossing a page boundary? */
8213 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8214 		int now;
8215 
8216 		now = -addr & ~PAGE_MASK;
8217 		rc = emulator_read_write_onepage(addr, val, now, exception,
8218 						 vcpu, ops);
8219 
8220 		if (rc != X86EMUL_CONTINUE)
8221 			return rc;
8222 		addr += now;
8223 		if (ctxt->mode != X86EMUL_MODE_PROT64)
8224 			addr = (u32)addr;
8225 		val += now;
8226 		bytes -= now;
8227 	}
8228 
8229 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
8230 					 vcpu, ops);
8231 	if (rc != X86EMUL_CONTINUE)
8232 		return rc;
8233 
8234 	if (!vcpu->mmio_nr_fragments)
8235 		return X86EMUL_CONTINUE;
8236 
8237 	gpa = vcpu->mmio_fragments[0].gpa;
8238 
8239 	vcpu->mmio_needed = 1;
8240 	vcpu->mmio_cur_fragment = 0;
8241 
8242 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8243 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8244 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
8245 	vcpu->run->mmio.phys_addr = gpa;
8246 
8247 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8248 }
8249 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8250 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8251 				  unsigned long addr,
8252 				  void *val,
8253 				  unsigned int bytes,
8254 				  struct x86_exception *exception)
8255 {
8256 	return emulator_read_write(ctxt, addr, val, bytes,
8257 				   exception, &read_emultor);
8258 }
8259 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8260 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8261 			    unsigned long addr,
8262 			    const void *val,
8263 			    unsigned int bytes,
8264 			    struct x86_exception *exception)
8265 {
8266 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
8267 				   exception, &write_emultor);
8268 }
8269 
8270 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8271 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8272 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8273 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8274 				     unsigned long addr,
8275 				     const void *old,
8276 				     const void *new,
8277 				     unsigned int bytes,
8278 				     struct x86_exception *exception)
8279 {
8280 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8281 	u64 page_line_mask;
8282 	unsigned long hva;
8283 	gpa_t gpa;
8284 	int r;
8285 
8286 	/* guests cmpxchg8b have to be emulated atomically */
8287 	if (bytes > 8 || (bytes & (bytes - 1)))
8288 		goto emul_write;
8289 
8290 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8291 
8292 	if (gpa == INVALID_GPA ||
8293 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8294 		goto emul_write;
8295 
8296 	/*
8297 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
8298 	 * enabled in the host and the access splits a cache line.
8299 	 */
8300 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8301 		page_line_mask = ~(cache_line_size() - 1);
8302 	else
8303 		page_line_mask = PAGE_MASK;
8304 
8305 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8306 		goto emul_write;
8307 
8308 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8309 	if (kvm_is_error_hva(hva))
8310 		goto emul_write;
8311 
8312 	hva += offset_in_page(gpa);
8313 
8314 	switch (bytes) {
8315 	case 1:
8316 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
8317 		break;
8318 	case 2:
8319 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
8320 		break;
8321 	case 4:
8322 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
8323 		break;
8324 	case 8:
8325 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
8326 		break;
8327 	default:
8328 		BUG();
8329 	}
8330 
8331 	if (r < 0)
8332 		return X86EMUL_UNHANDLEABLE;
8333 
8334 	/*
8335 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8336 	 * successful, as the old value is written back on failure.  Note, for
8337 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
8338 	 * back the original value and the access is atomic, but KVM's ABI is
8339 	 * that all writes are dirty logged, regardless of the value written.
8340 	 */
8341 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8342 
8343 	if (r)
8344 		return X86EMUL_CMPXCHG_FAILED;
8345 
8346 	kvm_page_track_write(vcpu, gpa, new, bytes);
8347 
8348 	return X86EMUL_CONTINUE;
8349 
8350 emul_write:
8351 	pr_warn_once("emulating exchange as write\n");
8352 
8353 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8354 }
8355 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8356 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8357 			       unsigned short port, void *data,
8358 			       unsigned int count, bool in)
8359 {
8360 	unsigned i;
8361 	int r;
8362 
8363 	WARN_ON_ONCE(vcpu->arch.pio.count);
8364 	for (i = 0; i < count; i++) {
8365 		if (in)
8366 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8367 		else
8368 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8369 
8370 		if (r) {
8371 			if (i == 0)
8372 				goto userspace_io;
8373 
8374 			/*
8375 			 * Userspace must have unregistered the device while PIO
8376 			 * was running.  Drop writes / read as 0.
8377 			 */
8378 			if (in)
8379 				memset(data, 0, size * (count - i));
8380 			break;
8381 		}
8382 
8383 		data += size;
8384 	}
8385 	return 1;
8386 
8387 userspace_io:
8388 	vcpu->arch.pio.port = port;
8389 	vcpu->arch.pio.in = in;
8390 	vcpu->arch.pio.count = count;
8391 	vcpu->arch.pio.size = size;
8392 
8393 	if (in)
8394 		memset(vcpu->arch.pio_data, 0, size * count);
8395 	else
8396 		memcpy(vcpu->arch.pio_data, data, size * count);
8397 
8398 	vcpu->run->exit_reason = KVM_EXIT_IO;
8399 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8400 	vcpu->run->io.size = size;
8401 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8402 	vcpu->run->io.count = count;
8403 	vcpu->run->io.port = port;
8404 	return 0;
8405 }
8406 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8407 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8408       			   unsigned short port, void *val, unsigned int count)
8409 {
8410 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8411 	if (r)
8412 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8413 
8414 	return r;
8415 }
8416 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8417 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8418 {
8419 	int size = vcpu->arch.pio.size;
8420 	unsigned int count = vcpu->arch.pio.count;
8421 	memcpy(val, vcpu->arch.pio_data, size * count);
8422 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8423 	vcpu->arch.pio.count = 0;
8424 }
8425 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8426 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8427 				    int size, unsigned short port, void *val,
8428 				    unsigned int count)
8429 {
8430 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8431 	if (vcpu->arch.pio.count) {
8432 		/*
8433 		 * Complete a previous iteration that required userspace I/O.
8434 		 * Note, @count isn't guaranteed to match pio.count as userspace
8435 		 * can modify ECX before rerunning the vCPU.  Ignore any such
8436 		 * shenanigans as KVM doesn't support modifying the rep count,
8437 		 * and the emulator ensures @count doesn't overflow the buffer.
8438 		 */
8439 		complete_emulator_pio_in(vcpu, val);
8440 		return 1;
8441 	}
8442 
8443 	return emulator_pio_in(vcpu, size, port, val, count);
8444 }
8445 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8446 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8447 			    unsigned short port, const void *val,
8448 			    unsigned int count)
8449 {
8450 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8451 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8452 }
8453 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8454 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8455 				     int size, unsigned short port,
8456 				     const void *val, unsigned int count)
8457 {
8458 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8459 }
8460 
get_segment_base(struct kvm_vcpu * vcpu,int seg)8461 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8462 {
8463 	return kvm_x86_call(get_segment_base)(vcpu, seg);
8464 }
8465 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8466 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8467 {
8468 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8469 }
8470 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8471 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8472 {
8473 	if (!need_emulate_wbinvd(vcpu))
8474 		return X86EMUL_CONTINUE;
8475 
8476 	if (kvm_x86_call(has_wbinvd_exit)()) {
8477 		int cpu = get_cpu();
8478 
8479 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8480 		wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
8481 		put_cpu();
8482 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8483 	} else
8484 		wbinvd();
8485 	return X86EMUL_CONTINUE;
8486 }
8487 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8488 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8489 {
8490 	kvm_emulate_wbinvd_noskip(vcpu);
8491 	return kvm_skip_emulated_instruction(vcpu);
8492 }
8493 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
8494 
8495 
8496 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8497 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8498 {
8499 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8500 }
8501 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8502 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8503 {
8504 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8505 }
8506 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8507 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8508 			   unsigned long value)
8509 {
8510 
8511 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8512 }
8513 
mk_cr_64(u64 curr_cr,u32 new_val)8514 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8515 {
8516 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8517 }
8518 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8519 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8520 {
8521 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8522 	unsigned long value;
8523 
8524 	switch (cr) {
8525 	case 0:
8526 		value = kvm_read_cr0(vcpu);
8527 		break;
8528 	case 2:
8529 		value = vcpu->arch.cr2;
8530 		break;
8531 	case 3:
8532 		value = kvm_read_cr3(vcpu);
8533 		break;
8534 	case 4:
8535 		value = kvm_read_cr4(vcpu);
8536 		break;
8537 	case 8:
8538 		value = kvm_get_cr8(vcpu);
8539 		break;
8540 	default:
8541 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8542 		return 0;
8543 	}
8544 
8545 	return value;
8546 }
8547 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8548 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8549 {
8550 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8551 	int res = 0;
8552 
8553 	switch (cr) {
8554 	case 0:
8555 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8556 		break;
8557 	case 2:
8558 		vcpu->arch.cr2 = val;
8559 		break;
8560 	case 3:
8561 		res = kvm_set_cr3(vcpu, val);
8562 		break;
8563 	case 4:
8564 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8565 		break;
8566 	case 8:
8567 		res = kvm_set_cr8(vcpu, val);
8568 		break;
8569 	default:
8570 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8571 		res = -1;
8572 	}
8573 
8574 	return res;
8575 }
8576 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8577 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8578 {
8579 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8580 }
8581 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8582 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8583 {
8584 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8585 }
8586 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8587 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8588 {
8589 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8590 }
8591 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8592 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8593 {
8594 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8595 }
8596 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8597 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8598 {
8599 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8600 }
8601 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8602 static unsigned long emulator_get_cached_segment_base(
8603 	struct x86_emulate_ctxt *ctxt, int seg)
8604 {
8605 	return get_segment_base(emul_to_vcpu(ctxt), seg);
8606 }
8607 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8608 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8609 				 struct desc_struct *desc, u32 *base3,
8610 				 int seg)
8611 {
8612 	struct kvm_segment var;
8613 
8614 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8615 	*selector = var.selector;
8616 
8617 	if (var.unusable) {
8618 		memset(desc, 0, sizeof(*desc));
8619 		if (base3)
8620 			*base3 = 0;
8621 		return false;
8622 	}
8623 
8624 	if (var.g)
8625 		var.limit >>= 12;
8626 	set_desc_limit(desc, var.limit);
8627 	set_desc_base(desc, (unsigned long)var.base);
8628 #ifdef CONFIG_X86_64
8629 	if (base3)
8630 		*base3 = var.base >> 32;
8631 #endif
8632 	desc->type = var.type;
8633 	desc->s = var.s;
8634 	desc->dpl = var.dpl;
8635 	desc->p = var.present;
8636 	desc->avl = var.avl;
8637 	desc->l = var.l;
8638 	desc->d = var.db;
8639 	desc->g = var.g;
8640 
8641 	return true;
8642 }
8643 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8644 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8645 				 struct desc_struct *desc, u32 base3,
8646 				 int seg)
8647 {
8648 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8649 	struct kvm_segment var;
8650 
8651 	var.selector = selector;
8652 	var.base = get_desc_base(desc);
8653 #ifdef CONFIG_X86_64
8654 	var.base |= ((u64)base3) << 32;
8655 #endif
8656 	var.limit = get_desc_limit(desc);
8657 	if (desc->g)
8658 		var.limit = (var.limit << 12) | 0xfff;
8659 	var.type = desc->type;
8660 	var.dpl = desc->dpl;
8661 	var.db = desc->d;
8662 	var.s = desc->s;
8663 	var.l = desc->l;
8664 	var.g = desc->g;
8665 	var.avl = desc->avl;
8666 	var.present = desc->p;
8667 	var.unusable = !var.present;
8668 	var.padding = 0;
8669 
8670 	kvm_set_segment(vcpu, &var, seg);
8671 	return;
8672 }
8673 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8674 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8675 					u32 msr_index, u64 *pdata)
8676 {
8677 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8678 	int r;
8679 
8680 	r = kvm_emulate_msr_read(vcpu, msr_index, pdata);
8681 	if (r < 0)
8682 		return X86EMUL_UNHANDLEABLE;
8683 
8684 	if (r) {
8685 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8686 				       complete_emulated_rdmsr, r))
8687 			return X86EMUL_IO_NEEDED;
8688 
8689 		trace_kvm_msr_read_ex(msr_index);
8690 		return X86EMUL_PROPAGATE_FAULT;
8691 	}
8692 
8693 	trace_kvm_msr_read(msr_index, *pdata);
8694 	return X86EMUL_CONTINUE;
8695 }
8696 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8697 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8698 					u32 msr_index, u64 data)
8699 {
8700 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8701 	int r;
8702 
8703 	r = kvm_emulate_msr_write(vcpu, msr_index, data);
8704 	if (r < 0)
8705 		return X86EMUL_UNHANDLEABLE;
8706 
8707 	if (r) {
8708 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8709 				       complete_emulated_msr_access, r))
8710 			return X86EMUL_IO_NEEDED;
8711 
8712 		trace_kvm_msr_write_ex(msr_index, data);
8713 		return X86EMUL_PROPAGATE_FAULT;
8714 	}
8715 
8716 	trace_kvm_msr_write(msr_index, data);
8717 	return X86EMUL_CONTINUE;
8718 }
8719 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8720 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8721 			    u32 msr_index, u64 *pdata)
8722 {
8723 	/*
8724 	 * Treat emulator accesses to the current shadow stack pointer as host-
8725 	 * initiated, as they aren't true MSR accesses (SSP is a "just a reg"),
8726 	 * and this API is used only for implicit accesses, i.e. not RDMSR, and
8727 	 * so the index is fully KVM-controlled.
8728 	 */
8729 	if (unlikely(msr_index == MSR_KVM_INTERNAL_GUEST_SSP))
8730 		return kvm_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8731 
8732 	return __kvm_emulate_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8733 }
8734 
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8735 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8736 {
8737 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8738 }
8739 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8740 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8741 			     u32 pmc, u64 *pdata)
8742 {
8743 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8744 }
8745 
emulator_halt(struct x86_emulate_ctxt * ctxt)8746 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8747 {
8748 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8749 }
8750 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8751 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8752 			      struct x86_instruction_info *info,
8753 			      enum x86_intercept_stage stage)
8754 {
8755 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8756 					     &ctxt->exception);
8757 }
8758 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8759 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8760 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8761 			      bool exact_only)
8762 {
8763 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8764 }
8765 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8766 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8767 {
8768 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8769 }
8770 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8771 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8772 {
8773 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8774 }
8775 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8776 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8777 {
8778 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8779 }
8780 
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8781 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8782 {
8783 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8784 }
8785 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8786 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8787 {
8788 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8789 }
8790 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8791 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8792 {
8793 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8794 }
8795 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8796 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8797 {
8798 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8799 }
8800 
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8801 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8802 {
8803 	return is_smm(emul_to_vcpu(ctxt));
8804 }
8805 
8806 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8807 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8808 {
8809 	WARN_ON_ONCE(1);
8810 	return X86EMUL_UNHANDLEABLE;
8811 }
8812 #endif
8813 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8814 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8815 {
8816 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8817 }
8818 
emulator_get_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 * xcr)8819 static int emulator_get_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 *xcr)
8820 {
8821 	if (index != XCR_XFEATURE_ENABLED_MASK)
8822 		return 1;
8823 	*xcr = emul_to_vcpu(ctxt)->arch.xcr0;
8824 	return 0;
8825 }
8826 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8827 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8828 {
8829 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8830 }
8831 
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8832 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8833 {
8834 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8835 
8836 	if (!kvm->vm_bugged)
8837 		kvm_vm_bugged(kvm);
8838 }
8839 
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8840 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8841 					gva_t addr, unsigned int flags)
8842 {
8843 	if (!kvm_x86_ops.get_untagged_addr)
8844 		return addr;
8845 
8846 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8847 					       addr, flags);
8848 }
8849 
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8850 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8851 				       gva_t addr, unsigned int flags)
8852 {
8853 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8854 }
8855 
8856 static const struct x86_emulate_ops emulate_ops = {
8857 	.vm_bugged           = emulator_vm_bugged,
8858 	.read_gpr            = emulator_read_gpr,
8859 	.write_gpr           = emulator_write_gpr,
8860 	.read_std            = emulator_read_std,
8861 	.write_std           = emulator_write_std,
8862 	.fetch               = kvm_fetch_guest_virt,
8863 	.read_emulated       = emulator_read_emulated,
8864 	.write_emulated      = emulator_write_emulated,
8865 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8866 	.invlpg              = emulator_invlpg,
8867 	.pio_in_emulated     = emulator_pio_in_emulated,
8868 	.pio_out_emulated    = emulator_pio_out_emulated,
8869 	.get_segment         = emulator_get_segment,
8870 	.set_segment         = emulator_set_segment,
8871 	.get_cached_segment_base = emulator_get_cached_segment_base,
8872 	.get_gdt             = emulator_get_gdt,
8873 	.get_idt	     = emulator_get_idt,
8874 	.set_gdt             = emulator_set_gdt,
8875 	.set_idt	     = emulator_set_idt,
8876 	.get_cr              = emulator_get_cr,
8877 	.set_cr              = emulator_set_cr,
8878 	.cpl                 = emulator_get_cpl,
8879 	.get_dr              = emulator_get_dr,
8880 	.set_dr              = emulator_set_dr,
8881 	.set_msr_with_filter = emulator_set_msr_with_filter,
8882 	.get_msr_with_filter = emulator_get_msr_with_filter,
8883 	.get_msr             = emulator_get_msr,
8884 	.check_rdpmc_early   = emulator_check_rdpmc_early,
8885 	.read_pmc            = emulator_read_pmc,
8886 	.halt                = emulator_halt,
8887 	.wbinvd              = emulator_wbinvd,
8888 	.fix_hypercall       = emulator_fix_hypercall,
8889 	.intercept           = emulator_intercept,
8890 	.get_cpuid           = emulator_get_cpuid,
8891 	.guest_has_movbe     = emulator_guest_has_movbe,
8892 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8893 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8894 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8895 	.set_nmi_mask        = emulator_set_nmi_mask,
8896 	.is_smm              = emulator_is_smm,
8897 	.leave_smm           = emulator_leave_smm,
8898 	.triple_fault        = emulator_triple_fault,
8899 	.get_xcr             = emulator_get_xcr,
8900 	.set_xcr             = emulator_set_xcr,
8901 	.get_untagged_addr   = emulator_get_untagged_addr,
8902 	.is_canonical_addr   = emulator_is_canonical_addr,
8903 };
8904 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8905 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8906 {
8907 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8908 	/*
8909 	 * an sti; sti; sequence only disable interrupts for the first
8910 	 * instruction. So, if the last instruction, be it emulated or
8911 	 * not, left the system with the INT_STI flag enabled, it
8912 	 * means that the last instruction is an sti. We should not
8913 	 * leave the flag on in this case. The same goes for mov ss
8914 	 */
8915 	if (int_shadow & mask)
8916 		mask = 0;
8917 	if (unlikely(int_shadow || mask)) {
8918 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8919 		if (!mask)
8920 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8921 	}
8922 }
8923 
inject_emulated_exception(struct kvm_vcpu * vcpu)8924 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8925 {
8926 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8927 
8928 	if (ctxt->exception.vector == PF_VECTOR)
8929 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8930 	else if (ctxt->exception.error_code_valid)
8931 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8932 				      ctxt->exception.error_code);
8933 	else
8934 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8935 }
8936 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8937 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8938 {
8939 	struct x86_emulate_ctxt *ctxt;
8940 
8941 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8942 	if (!ctxt) {
8943 		pr_err("failed to allocate vcpu's emulator\n");
8944 		return NULL;
8945 	}
8946 
8947 	ctxt->vcpu = vcpu;
8948 	ctxt->ops = &emulate_ops;
8949 	vcpu->arch.emulate_ctxt = ctxt;
8950 
8951 	return ctxt;
8952 }
8953 
init_emulate_ctxt(struct kvm_vcpu * vcpu)8954 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8955 {
8956 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8957 	int cs_db, cs_l;
8958 
8959 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8960 
8961 	ctxt->gpa_available = false;
8962 	ctxt->eflags = kvm_get_rflags(vcpu);
8963 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8964 
8965 	ctxt->eip = kvm_rip_read(vcpu);
8966 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8967 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8968 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8969 		     cs_db				? X86EMUL_MODE_PROT32 :
8970 							  X86EMUL_MODE_PROT16;
8971 	ctxt->interruptibility = 0;
8972 	ctxt->have_exception = false;
8973 	ctxt->exception.vector = -1;
8974 	ctxt->perm_ok = false;
8975 
8976 	init_decode_cache(ctxt);
8977 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8978 }
8979 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8980 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8981 {
8982 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8983 	int ret;
8984 
8985 	init_emulate_ctxt(vcpu);
8986 
8987 	ctxt->op_bytes = 2;
8988 	ctxt->ad_bytes = 2;
8989 	ctxt->_eip = ctxt->eip + inc_eip;
8990 	ret = emulate_int_real(ctxt, irq);
8991 
8992 	if (ret != X86EMUL_CONTINUE) {
8993 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8994 	} else {
8995 		ctxt->eip = ctxt->_eip;
8996 		kvm_rip_write(vcpu, ctxt->eip);
8997 		kvm_set_rflags(vcpu, ctxt->eflags);
8998 	}
8999 }
9000 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
9001 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)9002 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9003 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
9004 {
9005 	struct kvm_run *run = vcpu->run;
9006 	u64 info[5];
9007 	u8 info_start;
9008 
9009 	/*
9010 	 * Zero the whole array used to retrieve the exit info, as casting to
9011 	 * u32 for select entries will leave some chunks uninitialized.
9012 	 */
9013 	memset(&info, 0, sizeof(info));
9014 
9015 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
9016 				    (u32 *)&info[3], (u32 *)&info[4]);
9017 
9018 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9019 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
9020 
9021 	/*
9022 	 * There's currently space for 13 entries, but 5 are used for the exit
9023 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
9024 	 * when expanding kvm_run.emulation_failure in the future.
9025 	 */
9026 	if (WARN_ON_ONCE(ndata > 4))
9027 		ndata = 4;
9028 
9029 	/* Always include the flags as a 'data' entry. */
9030 	info_start = 1;
9031 	run->emulation_failure.flags = 0;
9032 
9033 	if (insn_size) {
9034 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
9035 			      sizeof(run->emulation_failure.insn_bytes) != 16));
9036 		info_start += 2;
9037 		run->emulation_failure.flags |=
9038 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
9039 		run->emulation_failure.insn_size = insn_size;
9040 		memset(run->emulation_failure.insn_bytes, 0x90,
9041 		       sizeof(run->emulation_failure.insn_bytes));
9042 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
9043 	}
9044 
9045 	memcpy(&run->internal.data[info_start], info, sizeof(info));
9046 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
9047 	       ndata * sizeof(data[0]));
9048 
9049 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
9050 }
9051 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)9052 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
9053 {
9054 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9055 
9056 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
9057 				       ctxt->fetch.end - ctxt->fetch.data);
9058 }
9059 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)9060 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9061 					  u8 ndata)
9062 {
9063 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
9064 }
9065 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
9066 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)9067 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
9068 {
9069 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
9070 }
9071 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
9072 
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)9073 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
9074 {
9075 	u32 reason, intr_info, error_code;
9076 	struct kvm_run *run = vcpu->run;
9077 	u64 info1, info2;
9078 	int ndata = 0;
9079 
9080 	kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
9081 				    &intr_info, &error_code);
9082 
9083 	run->internal.data[ndata++] = info2;
9084 	run->internal.data[ndata++] = reason;
9085 	run->internal.data[ndata++] = info1;
9086 	run->internal.data[ndata++] = gpa;
9087 	run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
9088 
9089 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9090 	run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9091 	run->internal.ndata = ndata;
9092 }
9093 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
9094 
kvm_prepare_unexpected_reason_exit(struct kvm_vcpu * vcpu,u64 exit_reason)9095 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason)
9096 {
9097 	vcpu_unimpl(vcpu, "unexpected exit reason 0x%llx\n", exit_reason);
9098 
9099 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9100 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
9101 	vcpu->run->internal.ndata = 2;
9102 	vcpu->run->internal.data[0] = exit_reason;
9103 	vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
9104 }
9105 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_unexpected_reason_exit);
9106 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)9107 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
9108 {
9109 	struct kvm *kvm = vcpu->kvm;
9110 
9111 	++vcpu->stat.insn_emulation_fail;
9112 	trace_kvm_emulate_insn_failed(vcpu);
9113 
9114 	if (emulation_type & EMULTYPE_VMWARE_GP) {
9115 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9116 		return 1;
9117 	}
9118 
9119 	if (kvm->arch.exit_on_emulation_error ||
9120 	    (emulation_type & EMULTYPE_SKIP)) {
9121 		prepare_emulation_ctxt_failure_exit(vcpu);
9122 		return 0;
9123 	}
9124 
9125 	kvm_queue_exception(vcpu, UD_VECTOR);
9126 
9127 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
9128 		prepare_emulation_ctxt_failure_exit(vcpu);
9129 		return 0;
9130 	}
9131 
9132 	return 1;
9133 }
9134 
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)9135 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
9136 					       gpa_t cr2_or_gpa,
9137 					       int emulation_type)
9138 {
9139 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
9140 		return false;
9141 
9142 	/*
9143 	 * If the failed instruction faulted on an access to page tables that
9144 	 * are used to translate any part of the instruction, KVM can't resolve
9145 	 * the issue by unprotecting the gfn, as zapping the shadow page will
9146 	 * result in the instruction taking a !PRESENT page fault and thus put
9147 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
9148 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
9149 	 * then zap the SPTE to unprotect the gfn, and then do it all over
9150 	 * again.  Report the error to userspace.
9151 	 */
9152 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
9153 		return false;
9154 
9155 	/*
9156 	 * If emulation may have been triggered by a write to a shadowed page
9157 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
9158 	 * guest to let the CPU re-execute the instruction in the hope that the
9159 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
9160 	 */
9161 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
9162 
9163 	/*
9164 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
9165 	 * all SPTEs were already zapped by a different task.  The alternative
9166 	 * is to report the error to userspace and likely terminate the guest,
9167 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
9168 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
9169 	 */
9170 	return true;
9171 }
9172 
9173 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
9174 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
9175 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)9176 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
9177 				unsigned long *db)
9178 {
9179 	u32 dr6 = 0;
9180 	int i;
9181 	u32 enable, rwlen;
9182 
9183 	enable = dr7;
9184 	rwlen = dr7 >> 16;
9185 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
9186 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
9187 			dr6 |= (1 << i);
9188 	return dr6;
9189 }
9190 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)9191 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
9192 {
9193 	struct kvm_run *kvm_run = vcpu->run;
9194 
9195 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9196 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
9197 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
9198 		kvm_run->debug.arch.exception = DB_VECTOR;
9199 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
9200 		return 0;
9201 	}
9202 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
9203 	return 1;
9204 }
9205 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)9206 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
9207 {
9208 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9209 	int r;
9210 
9211 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9212 	if (unlikely(!r))
9213 		return 0;
9214 
9215 	kvm_pmu_instruction_retired(vcpu);
9216 
9217 	/*
9218 	 * rflags is the old, "raw" value of the flags.  The new value has
9219 	 * not been saved yet.
9220 	 *
9221 	 * This is correct even for TF set by the guest, because "the
9222 	 * processor will not generate this exception after the instruction
9223 	 * that sets the TF flag".
9224 	 */
9225 	if (unlikely(rflags & X86_EFLAGS_TF))
9226 		r = kvm_vcpu_do_singlestep(vcpu);
9227 	return r;
9228 }
9229 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
9230 
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9231 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9232 {
9233 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9234 		return true;
9235 
9236 	/*
9237 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9238 	 * active, but AMD compatible CPUs do not.
9239 	 */
9240 	if (!guest_cpuid_is_intel_compatible(vcpu))
9241 		return false;
9242 
9243 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9244 }
9245 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9246 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9247 					   int emulation_type, int *r)
9248 {
9249 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9250 
9251 	/*
9252 	 * Do not check for code breakpoints if hardware has already done the
9253 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
9254 	 * the instruction has passed all exception checks, and all intercepted
9255 	 * exceptions that trigger emulation have lower priority than code
9256 	 * breakpoints, i.e. the fact that the intercepted exception occurred
9257 	 * means any code breakpoints have already been serviced.
9258 	 *
9259 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9260 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
9261 	 * the instruction being emulated.  The intent of forced emulation is
9262 	 * to behave as if KVM intercepted the instruction without an exception
9263 	 * and without a prefix.
9264 	 */
9265 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9266 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9267 		return false;
9268 
9269 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9270 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9271 		struct kvm_run *kvm_run = vcpu->run;
9272 		unsigned long eip = kvm_get_linear_rip(vcpu);
9273 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9274 					   vcpu->arch.guest_debug_dr7,
9275 					   vcpu->arch.eff_db);
9276 
9277 		if (dr6 != 0) {
9278 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9279 			kvm_run->debug.arch.pc = eip;
9280 			kvm_run->debug.arch.exception = DB_VECTOR;
9281 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
9282 			*r = 0;
9283 			return true;
9284 		}
9285 	}
9286 
9287 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9288 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
9289 		unsigned long eip = kvm_get_linear_rip(vcpu);
9290 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9291 					   vcpu->arch.dr7,
9292 					   vcpu->arch.db);
9293 
9294 		if (dr6 != 0) {
9295 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9296 			*r = 1;
9297 			return true;
9298 		}
9299 	}
9300 
9301 	return false;
9302 }
9303 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9304 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9305 {
9306 	switch (ctxt->opcode_len) {
9307 	case 1:
9308 		switch (ctxt->b) {
9309 		case 0xe4:	/* IN */
9310 		case 0xe5:
9311 		case 0xec:
9312 		case 0xed:
9313 		case 0xe6:	/* OUT */
9314 		case 0xe7:
9315 		case 0xee:
9316 		case 0xef:
9317 		case 0x6c:	/* INS */
9318 		case 0x6d:
9319 		case 0x6e:	/* OUTS */
9320 		case 0x6f:
9321 			return true;
9322 		}
9323 		break;
9324 	case 2:
9325 		switch (ctxt->b) {
9326 		case 0x33:	/* RDPMC */
9327 			return true;
9328 		}
9329 		break;
9330 	}
9331 
9332 	return false;
9333 }
9334 
is_soft_int_instruction(struct x86_emulate_ctxt * ctxt,int emulation_type)9335 static bool is_soft_int_instruction(struct x86_emulate_ctxt *ctxt,
9336 				    int emulation_type)
9337 {
9338 	u8 vector = EMULTYPE_GET_SOFT_INT_VECTOR(emulation_type);
9339 
9340 	switch (ctxt->b) {
9341 	case 0xcc:
9342 		return vector == BP_VECTOR;
9343 	case 0xcd:
9344 		return vector == ctxt->src.val;
9345 	case 0xce:
9346 		return vector == OF_VECTOR;
9347 	default:
9348 		return false;
9349 	}
9350 }
9351 
9352 /*
9353  * Decode an instruction for emulation.  The caller is responsible for handling
9354  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
9355  * (and wrong) when emulating on an intercepted fault-like exception[*], as
9356  * code breakpoints have higher priority and thus have already been done by
9357  * hardware.
9358  *
9359  * [*] Except #MC, which is higher priority, but KVM should never emulate in
9360  *     response to a machine check.
9361  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9362 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9363 				    void *insn, int insn_len)
9364 {
9365 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9366 	int r;
9367 
9368 	init_emulate_ctxt(vcpu);
9369 
9370 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9371 
9372 	trace_kvm_emulate_insn_start(vcpu);
9373 	++vcpu->stat.insn_emulation;
9374 
9375 	return r;
9376 }
9377 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
9378 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9379 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9380 			    int emulation_type, void *insn, int insn_len)
9381 {
9382 	int r;
9383 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9384 	bool writeback = true;
9385 
9386 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9387 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9388 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9389 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9390 
9391 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9392 	if (r != X86EMUL_CONTINUE) {
9393 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9394 			return 1;
9395 
9396 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9397 						       emulation_type))
9398 			return 1;
9399 
9400 		if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9401 			kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9402 			return 0;
9403 		}
9404 
9405 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9406 		return handle_emulation_failure(vcpu, emulation_type);
9407 	}
9408 
9409 	kvm_request_l1tf_flush_l1d();
9410 
9411 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9412 		kvm_clear_exception_queue(vcpu);
9413 
9414 		/*
9415 		 * Return immediately if RIP hits a code breakpoint, such #DBs
9416 		 * are fault-like and are higher priority than any faults on
9417 		 * the code fetch itself.
9418 		 */
9419 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9420 			return r;
9421 
9422 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
9423 						    insn, insn_len);
9424 		if (r != EMULATION_OK)  {
9425 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
9426 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9427 				kvm_queue_exception(vcpu, UD_VECTOR);
9428 				return 1;
9429 			}
9430 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9431 							       emulation_type))
9432 				return 1;
9433 
9434 			if (ctxt->have_exception &&
9435 			    !(emulation_type & EMULTYPE_SKIP)) {
9436 				/*
9437 				 * #UD should result in just EMULATION_FAILED, and trap-like
9438 				 * exception should not be encountered during decode.
9439 				 */
9440 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9441 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9442 				inject_emulated_exception(vcpu);
9443 				return 1;
9444 			}
9445 			return handle_emulation_failure(vcpu, emulation_type);
9446 		}
9447 	}
9448 
9449 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9450 	    !is_vmware_backdoor_opcode(ctxt)) {
9451 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9452 		return 1;
9453 	}
9454 
9455 	/*
9456 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9457 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9458 	 * The caller is responsible for updating interruptibility state and
9459 	 * injecting single-step #DBs.
9460 	 */
9461 	if (emulation_type & EMULTYPE_SKIP) {
9462 		if (emulation_type & EMULTYPE_SKIP_SOFT_INT &&
9463 		    !is_soft_int_instruction(ctxt, emulation_type))
9464 			return 0;
9465 
9466 		if (ctxt->mode != X86EMUL_MODE_PROT64)
9467 			ctxt->eip = (u32)ctxt->_eip;
9468 		else
9469 			ctxt->eip = ctxt->_eip;
9470 
9471 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9472 			r = 1;
9473 			goto writeback;
9474 		}
9475 
9476 		kvm_rip_write(vcpu, ctxt->eip);
9477 		if (ctxt->eflags & X86_EFLAGS_RF)
9478 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9479 		return 1;
9480 	}
9481 
9482 	/*
9483 	 * If emulation was caused by a write-protection #PF on a non-page_table
9484 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9485 	 * and retry the instruction, as the vCPU is likely no longer using the
9486 	 * gfn as a page table.
9487 	 */
9488 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9489 	    !x86_page_table_writing_insn(ctxt) &&
9490 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9491 		return 1;
9492 
9493 	/* this is needed for vmware backdoor interface to work since it
9494 	   changes registers values  during IO operation */
9495 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9496 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9497 		emulator_invalidate_register_cache(ctxt);
9498 	}
9499 
9500 restart:
9501 	if (emulation_type & EMULTYPE_PF) {
9502 		/* Save the faulting GPA (cr2) in the address field */
9503 		ctxt->exception.address = cr2_or_gpa;
9504 
9505 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
9506 		if (vcpu->arch.mmu->root_role.direct) {
9507 			ctxt->gpa_available = true;
9508 			ctxt->gpa_val = cr2_or_gpa;
9509 		}
9510 	} else {
9511 		/* Sanitize the address out of an abundance of paranoia. */
9512 		ctxt->exception.address = 0;
9513 	}
9514 
9515 	/*
9516 	 * Check L1's instruction intercepts when emulating instructions for
9517 	 * L2, unless KVM is re-emulating a previously decoded instruction,
9518 	 * e.g. to complete userspace I/O, in which case KVM has already
9519 	 * checked the intercepts.
9520 	 */
9521 	r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9522 				   !(emulation_type & EMULTYPE_NO_DECODE));
9523 
9524 	if (r == EMULATION_INTERCEPTED)
9525 		return 1;
9526 
9527 	if (r == EMULATION_FAILED) {
9528 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9529 						       emulation_type))
9530 			return 1;
9531 
9532 		return handle_emulation_failure(vcpu, emulation_type);
9533 	}
9534 
9535 	if (ctxt->have_exception) {
9536 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9537 		vcpu->mmio_needed = false;
9538 		r = 1;
9539 		inject_emulated_exception(vcpu);
9540 	} else if (vcpu->arch.pio.count) {
9541 		if (!vcpu->arch.pio.in) {
9542 			/* FIXME: return into emulator if single-stepping.  */
9543 			vcpu->arch.pio.count = 0;
9544 		} else {
9545 			writeback = false;
9546 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
9547 		}
9548 		r = 0;
9549 	} else if (vcpu->mmio_needed) {
9550 		++vcpu->stat.mmio_exits;
9551 
9552 		if (!vcpu->mmio_is_write)
9553 			writeback = false;
9554 		r = 0;
9555 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9556 	} else if (vcpu->arch.complete_userspace_io) {
9557 		writeback = false;
9558 		r = 0;
9559 	} else if (r == EMULATION_RESTART)
9560 		goto restart;
9561 	else
9562 		r = 1;
9563 
9564 writeback:
9565 	if (writeback) {
9566 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9567 		toggle_interruptibility(vcpu, ctxt->interruptibility);
9568 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9569 
9570 		/*
9571 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9572 		 * only supports code breakpoints and general detect #DB, both
9573 		 * of which are fault-like.
9574 		 */
9575 		if (!ctxt->have_exception ||
9576 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9577 			kvm_pmu_instruction_retired(vcpu);
9578 			if (ctxt->is_branch)
9579 				kvm_pmu_branch_retired(vcpu);
9580 			kvm_rip_write(vcpu, ctxt->eip);
9581 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9582 				r = kvm_vcpu_do_singlestep(vcpu);
9583 			kvm_x86_call(update_emulated_instruction)(vcpu);
9584 			__kvm_set_rflags(vcpu, ctxt->eflags);
9585 		}
9586 
9587 		/*
9588 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9589 		 * do nothing, and it will be requested again as soon as
9590 		 * the shadow expires.  But we still need to check here,
9591 		 * because POPF has no interrupt shadow.
9592 		 */
9593 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9594 			kvm_make_request(KVM_REQ_EVENT, vcpu);
9595 	} else
9596 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9597 
9598 	return r;
9599 }
9600 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9601 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9602 {
9603 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9604 }
9605 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
9606 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9607 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9608 					void *insn, int insn_len)
9609 {
9610 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9611 }
9612 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
9613 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9614 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9615 {
9616 	vcpu->arch.pio.count = 0;
9617 	return 1;
9618 }
9619 
complete_fast_pio_out(struct kvm_vcpu * vcpu)9620 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9621 {
9622 	vcpu->arch.pio.count = 0;
9623 
9624 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9625 		return 1;
9626 
9627 	return kvm_skip_emulated_instruction(vcpu);
9628 }
9629 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9630 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9631 			    unsigned short port)
9632 {
9633 	unsigned long val = kvm_rax_read(vcpu);
9634 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9635 
9636 	if (ret)
9637 		return ret;
9638 
9639 	/*
9640 	 * Workaround userspace that relies on old KVM behavior of %rip being
9641 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9642 	 */
9643 	if (port == 0x7e &&
9644 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9645 		vcpu->arch.complete_userspace_io =
9646 			complete_fast_pio_out_port_0x7e;
9647 		kvm_skip_emulated_instruction(vcpu);
9648 	} else {
9649 		vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9650 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9651 	}
9652 	return 0;
9653 }
9654 
complete_fast_pio_in(struct kvm_vcpu * vcpu)9655 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9656 {
9657 	unsigned long val;
9658 
9659 	/* We should only ever be called with arch.pio.count equal to 1 */
9660 	BUG_ON(vcpu->arch.pio.count != 1);
9661 
9662 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9663 		vcpu->arch.pio.count = 0;
9664 		return 1;
9665 	}
9666 
9667 	/* For size less than 4 we merge, else we zero extend */
9668 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9669 
9670 	complete_emulator_pio_in(vcpu, &val);
9671 	kvm_rax_write(vcpu, val);
9672 
9673 	return kvm_skip_emulated_instruction(vcpu);
9674 }
9675 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9676 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9677 			   unsigned short port)
9678 {
9679 	unsigned long val;
9680 	int ret;
9681 
9682 	/* For size less than 4 we merge, else we zero extend */
9683 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9684 
9685 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
9686 	if (ret) {
9687 		kvm_rax_write(vcpu, val);
9688 		return ret;
9689 	}
9690 
9691 	vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9692 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9693 
9694 	return 0;
9695 }
9696 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9697 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9698 {
9699 	int ret;
9700 
9701 	if (in)
9702 		ret = kvm_fast_pio_in(vcpu, size, port);
9703 	else
9704 		ret = kvm_fast_pio_out(vcpu, size, port);
9705 	return ret && kvm_skip_emulated_instruction(vcpu);
9706 }
9707 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
9708 
kvmclock_cpu_down_prep(unsigned int cpu)9709 static int kvmclock_cpu_down_prep(unsigned int cpu)
9710 {
9711 	__this_cpu_write(cpu_tsc_khz, 0);
9712 	return 0;
9713 }
9714 
tsc_khz_changed(void * data)9715 static void tsc_khz_changed(void *data)
9716 {
9717 	struct cpufreq_freqs *freq = data;
9718 	unsigned long khz;
9719 
9720 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9721 
9722 	if (data)
9723 		khz = freq->new;
9724 	else
9725 		khz = cpufreq_quick_get(raw_smp_processor_id());
9726 	if (!khz)
9727 		khz = tsc_khz;
9728 	__this_cpu_write(cpu_tsc_khz, khz);
9729 }
9730 
9731 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9732 static void kvm_hyperv_tsc_notifier(void)
9733 {
9734 	struct kvm *kvm;
9735 	int cpu;
9736 
9737 	mutex_lock(&kvm_lock);
9738 	list_for_each_entry(kvm, &vm_list, vm_list)
9739 		kvm_make_mclock_inprogress_request(kvm);
9740 
9741 	/* no guest entries from this point */
9742 	hyperv_stop_tsc_emulation();
9743 
9744 	/* TSC frequency always matches when on Hyper-V */
9745 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9746 		for_each_present_cpu(cpu)
9747 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9748 	}
9749 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9750 
9751 	list_for_each_entry(kvm, &vm_list, vm_list) {
9752 		__kvm_start_pvclock_update(kvm);
9753 		pvclock_update_vm_gtod_copy(kvm);
9754 		kvm_end_pvclock_update(kvm);
9755 	}
9756 
9757 	mutex_unlock(&kvm_lock);
9758 }
9759 #endif
9760 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9761 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9762 {
9763 	struct kvm *kvm;
9764 	struct kvm_vcpu *vcpu;
9765 	int send_ipi = 0;
9766 	unsigned long i;
9767 
9768 	/*
9769 	 * We allow guests to temporarily run on slowing clocks,
9770 	 * provided we notify them after, or to run on accelerating
9771 	 * clocks, provided we notify them before.  Thus time never
9772 	 * goes backwards.
9773 	 *
9774 	 * However, we have a problem.  We can't atomically update
9775 	 * the frequency of a given CPU from this function; it is
9776 	 * merely a notifier, which can be called from any CPU.
9777 	 * Changing the TSC frequency at arbitrary points in time
9778 	 * requires a recomputation of local variables related to
9779 	 * the TSC for each VCPU.  We must flag these local variables
9780 	 * to be updated and be sure the update takes place with the
9781 	 * new frequency before any guests proceed.
9782 	 *
9783 	 * Unfortunately, the combination of hotplug CPU and frequency
9784 	 * change creates an intractable locking scenario; the order
9785 	 * of when these callouts happen is undefined with respect to
9786 	 * CPU hotplug, and they can race with each other.  As such,
9787 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9788 	 * undefined; you can actually have a CPU frequency change take
9789 	 * place in between the computation of X and the setting of the
9790 	 * variable.  To protect against this problem, all updates of
9791 	 * the per_cpu tsc_khz variable are done in an interrupt
9792 	 * protected IPI, and all callers wishing to update the value
9793 	 * must wait for a synchronous IPI to complete (which is trivial
9794 	 * if the caller is on the CPU already).  This establishes the
9795 	 * necessary total order on variable updates.
9796 	 *
9797 	 * Note that because a guest time update may take place
9798 	 * anytime after the setting of the VCPU's request bit, the
9799 	 * correct TSC value must be set before the request.  However,
9800 	 * to ensure the update actually makes it to any guest which
9801 	 * starts running in hardware virtualization between the set
9802 	 * and the acquisition of the spinlock, we must also ping the
9803 	 * CPU after setting the request bit.
9804 	 *
9805 	 */
9806 
9807 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9808 
9809 	mutex_lock(&kvm_lock);
9810 	list_for_each_entry(kvm, &vm_list, vm_list) {
9811 		kvm_for_each_vcpu(i, vcpu, kvm) {
9812 			if (vcpu->cpu != cpu)
9813 				continue;
9814 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9815 			if (vcpu->cpu != raw_smp_processor_id())
9816 				send_ipi = 1;
9817 		}
9818 	}
9819 	mutex_unlock(&kvm_lock);
9820 
9821 	if (freq->old < freq->new && send_ipi) {
9822 		/*
9823 		 * We upscale the frequency.  Must make the guest
9824 		 * doesn't see old kvmclock values while running with
9825 		 * the new frequency, otherwise we risk the guest sees
9826 		 * time go backwards.
9827 		 *
9828 		 * In case we update the frequency for another cpu
9829 		 * (which might be in guest context) send an interrupt
9830 		 * to kick the cpu out of guest context.  Next time
9831 		 * guest context is entered kvmclock will be updated,
9832 		 * so the guest will not see stale values.
9833 		 */
9834 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9835 	}
9836 }
9837 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9838 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9839 				     void *data)
9840 {
9841 	struct cpufreq_freqs *freq = data;
9842 	int cpu;
9843 
9844 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9845 		return 0;
9846 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9847 		return 0;
9848 
9849 	for_each_cpu(cpu, freq->policy->cpus)
9850 		__kvmclock_cpufreq_notifier(freq, cpu);
9851 
9852 	return 0;
9853 }
9854 
9855 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9856 	.notifier_call  = kvmclock_cpufreq_notifier
9857 };
9858 
kvmclock_cpu_online(unsigned int cpu)9859 static int kvmclock_cpu_online(unsigned int cpu)
9860 {
9861 	tsc_khz_changed(NULL);
9862 	return 0;
9863 }
9864 
kvm_timer_init(void)9865 static void kvm_timer_init(void)
9866 {
9867 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9868 		max_tsc_khz = tsc_khz;
9869 
9870 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9871 			struct cpufreq_policy *policy;
9872 			int cpu;
9873 
9874 			cpu = get_cpu();
9875 			policy = cpufreq_cpu_get(cpu);
9876 			if (policy) {
9877 				if (policy->cpuinfo.max_freq)
9878 					max_tsc_khz = policy->cpuinfo.max_freq;
9879 				cpufreq_cpu_put(policy);
9880 			}
9881 			put_cpu();
9882 		}
9883 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9884 					  CPUFREQ_TRANSITION_NOTIFIER);
9885 
9886 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9887 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9888 	}
9889 }
9890 
9891 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9892 static void pvclock_gtod_update_fn(struct work_struct *work)
9893 {
9894 	struct kvm *kvm;
9895 	struct kvm_vcpu *vcpu;
9896 	unsigned long i;
9897 
9898 	mutex_lock(&kvm_lock);
9899 	list_for_each_entry(kvm, &vm_list, vm_list)
9900 		kvm_for_each_vcpu(i, vcpu, kvm)
9901 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9902 	atomic_set(&kvm_guest_has_master_clock, 0);
9903 	mutex_unlock(&kvm_lock);
9904 }
9905 
9906 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9907 
9908 /*
9909  * Indirection to move queue_work() out of the tk_core.seq write held
9910  * region to prevent possible deadlocks against time accessors which
9911  * are invoked with work related locks held.
9912  */
pvclock_irq_work_fn(struct irq_work * w)9913 static void pvclock_irq_work_fn(struct irq_work *w)
9914 {
9915 	queue_work(system_long_wq, &pvclock_gtod_work);
9916 }
9917 
9918 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9919 
9920 /*
9921  * Notification about pvclock gtod data update.
9922  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9923 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9924 			       void *priv)
9925 {
9926 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9927 	struct timekeeper *tk = priv;
9928 
9929 	update_pvclock_gtod(tk);
9930 
9931 	/*
9932 	 * Disable master clock if host does not trust, or does not use,
9933 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9934 	 * this is invoked with tk_core.seq write held.
9935 	 */
9936 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9937 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9938 		irq_work_queue(&pvclock_irq_work);
9939 	return 0;
9940 }
9941 
9942 static struct notifier_block pvclock_gtod_notifier = {
9943 	.notifier_call = pvclock_gtod_notify,
9944 };
9945 #endif
9946 
kvm_ops_update(struct kvm_x86_init_ops * ops)9947 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9948 {
9949 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9950 
9951 #define __KVM_X86_OP(func) \
9952 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9953 #define KVM_X86_OP(func) \
9954 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9955 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9956 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9957 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9958 					   (void *)__static_call_return0);
9959 #include <asm/kvm-x86-ops.h>
9960 #undef __KVM_X86_OP
9961 
9962 	kvm_pmu_ops_update(ops->pmu_ops);
9963 }
9964 
kvm_x86_check_processor_compatibility(void)9965 static int kvm_x86_check_processor_compatibility(void)
9966 {
9967 	int cpu = smp_processor_id();
9968 	struct cpuinfo_x86 *c = &cpu_data(cpu);
9969 
9970 	/*
9971 	 * Compatibility checks are done when loading KVM and when enabling
9972 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9973 	 * compatible, i.e. KVM should never perform a compatibility check on
9974 	 * an offline CPU.
9975 	 */
9976 	WARN_ON(!cpu_online(cpu));
9977 
9978 	if (__cr4_reserved_bits(cpu_has, c) !=
9979 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9980 		return -EIO;
9981 
9982 	return kvm_x86_call(check_processor_compatibility)();
9983 }
9984 
kvm_x86_check_cpu_compat(void * ret)9985 static void kvm_x86_check_cpu_compat(void *ret)
9986 {
9987 	*(int *)ret = kvm_x86_check_processor_compatibility();
9988 }
9989 
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9990 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9991 {
9992 	u64 host_pat;
9993 	int r, cpu;
9994 
9995 	guard(mutex)(&vendor_module_lock);
9996 
9997 	if (kvm_x86_ops.enable_virtualization_cpu) {
9998 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9999 		return -EEXIST;
10000 	}
10001 
10002 	/*
10003 	 * KVM explicitly assumes that the guest has an FPU and
10004 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
10005 	 * vCPU's FPU state as a fxregs_state struct.
10006 	 */
10007 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
10008 		pr_err("inadequate fpu\n");
10009 		return -EOPNOTSUPP;
10010 	}
10011 
10012 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10013 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
10014 		return -EOPNOTSUPP;
10015 	}
10016 
10017 	/*
10018 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
10019 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
10020 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
10021 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
10022 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
10023 	 */
10024 	if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
10025 	    (host_pat & GENMASK(2, 0)) != 6) {
10026 		pr_err("host PAT[0] is not WB\n");
10027 		return -EIO;
10028 	}
10029 
10030 	if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
10031 		rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
10032 		/*
10033 		 * Linux doesn't yet support supervisor shadow stacks (SSS), so
10034 		 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
10035 		 * clobber the host values.  Yell and refuse to load if SSS is
10036 		 * unexpectedly enabled, e.g. to avoid crashing the host.
10037 		 */
10038 		if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
10039 			return -EIO;
10040 	}
10041 
10042 	memset(&kvm_caps, 0, sizeof(kvm_caps));
10043 
10044 	x86_emulator_cache = kvm_alloc_emulator_cache();
10045 	if (!x86_emulator_cache) {
10046 		pr_err("failed to allocate cache for x86 emulator\n");
10047 		return -ENOMEM;
10048 	}
10049 
10050 	r = kvm_mmu_vendor_module_init();
10051 	if (r)
10052 		goto out_free_x86_emulator_cache;
10053 
10054 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
10055 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
10056 
10057 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
10058 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
10059 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
10060 	}
10061 
10062 	if (boot_cpu_has(X86_FEATURE_XSAVES)) {
10063 		rdmsrq(MSR_IA32_XSS, kvm_host.xss);
10064 		kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
10065 	}
10066 
10067 	kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
10068 	kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
10069 
10070 	rdmsrq_safe(MSR_EFER, &kvm_host.efer);
10071 
10072 	kvm_init_pmu_capability(ops->pmu_ops);
10073 
10074 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
10075 		rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
10076 
10077 	WARN_ON_ONCE(kvm_nr_uret_msrs);
10078 
10079 	r = ops->hardware_setup();
10080 	if (r != 0)
10081 		goto out_mmu_exit;
10082 
10083 	enable_device_posted_irqs &= enable_apicv &&
10084 				     irq_remapping_cap(IRQ_POSTING_CAP);
10085 
10086 	kvm_ops_update(ops);
10087 
10088 	for_each_online_cpu(cpu) {
10089 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
10090 		if (r < 0)
10091 			goto out_unwind_ops;
10092 	}
10093 
10094 	/*
10095 	 * Point of no return!  DO NOT add error paths below this point unless
10096 	 * absolutely necessary, as most operations from this point forward
10097 	 * require unwinding.
10098 	 */
10099 	kvm_timer_init();
10100 
10101 	if (pi_inject_timer == -1)
10102 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
10103 #ifdef CONFIG_X86_64
10104 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
10105 
10106 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10107 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
10108 #endif
10109 
10110 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
10111 
10112 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
10113 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
10114 
10115 	/* KVM always ignores guest PAT for shadow paging.  */
10116 	if (!tdp_enabled)
10117 		kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
10118 
10119 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10120 		kvm_caps.supported_xss = 0;
10121 
10122 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
10123 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
10124 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10125 
10126 	if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
10127 		kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
10128 		kvm_cpu_cap_clear(X86_FEATURE_IBT);
10129 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10130 	}
10131 
10132 	if (kvm_caps.has_tsc_control) {
10133 		/*
10134 		 * Make sure the user can only configure tsc_khz values that
10135 		 * fit into a signed integer.
10136 		 * A min value is not calculated because it will always
10137 		 * be 1 on all machines.
10138 		 */
10139 		u64 max = min(0x7fffffffULL,
10140 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
10141 		kvm_caps.max_guest_tsc_khz = max;
10142 	}
10143 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
10144 	kvm_init_msr_lists();
10145 	return 0;
10146 
10147 out_unwind_ops:
10148 	kvm_x86_ops.enable_virtualization_cpu = NULL;
10149 	kvm_x86_call(hardware_unsetup)();
10150 out_mmu_exit:
10151 	kvm_destroy_user_return_msrs();
10152 	kvm_mmu_vendor_module_exit();
10153 out_free_x86_emulator_cache:
10154 	kmem_cache_destroy(x86_emulator_cache);
10155 	return r;
10156 }
10157 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
10158 
kvm_x86_vendor_exit(void)10159 void kvm_x86_vendor_exit(void)
10160 {
10161 	kvm_unregister_perf_callbacks();
10162 
10163 #ifdef CONFIG_X86_64
10164 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10165 		clear_hv_tscchange_cb();
10166 #endif
10167 	kvm_lapic_exit();
10168 
10169 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10170 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
10171 					    CPUFREQ_TRANSITION_NOTIFIER);
10172 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
10173 	}
10174 #ifdef CONFIG_X86_64
10175 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
10176 	irq_work_sync(&pvclock_irq_work);
10177 	cancel_work_sync(&pvclock_gtod_work);
10178 #endif
10179 	kvm_x86_call(hardware_unsetup)();
10180 	kvm_destroy_user_return_msrs();
10181 	kvm_mmu_vendor_module_exit();
10182 	kmem_cache_destroy(x86_emulator_cache);
10183 #ifdef CONFIG_KVM_XEN
10184 	static_key_deferred_flush(&kvm_xen_enabled);
10185 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
10186 #endif
10187 	mutex_lock(&vendor_module_lock);
10188 	kvm_x86_ops.enable_virtualization_cpu = NULL;
10189 	mutex_unlock(&vendor_module_lock);
10190 }
10191 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
10192 
10193 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)10194 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
10195 			        unsigned long clock_type)
10196 {
10197 	struct kvm_clock_pairing clock_pairing;
10198 	struct timespec64 ts;
10199 	u64 cycle;
10200 	int ret;
10201 
10202 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
10203 		return -KVM_EOPNOTSUPP;
10204 
10205 	/*
10206 	 * When tsc is in permanent catchup mode guests won't be able to use
10207 	 * pvclock_read_retry loop to get consistent view of pvclock
10208 	 */
10209 	if (vcpu->arch.tsc_always_catchup)
10210 		return -KVM_EOPNOTSUPP;
10211 
10212 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
10213 		return -KVM_EOPNOTSUPP;
10214 
10215 	clock_pairing.sec = ts.tv_sec;
10216 	clock_pairing.nsec = ts.tv_nsec;
10217 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
10218 	clock_pairing.flags = 0;
10219 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
10220 
10221 	ret = 0;
10222 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
10223 			    sizeof(struct kvm_clock_pairing)))
10224 		ret = -KVM_EFAULT;
10225 
10226 	return ret;
10227 }
10228 #endif
10229 
10230 /*
10231  * kvm_pv_kick_cpu_op:  Kick a vcpu.
10232  *
10233  * @apicid - apicid of vcpu to be kicked.
10234  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)10235 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
10236 {
10237 	/*
10238 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
10239 	 * common code, e.g. for tracing. Defer initialization to the compiler.
10240 	 */
10241 	struct kvm_lapic_irq lapic_irq = {
10242 		.delivery_mode = APIC_DM_REMRD,
10243 		.dest_mode = APIC_DEST_PHYSICAL,
10244 		.shorthand = APIC_DEST_NOSHORT,
10245 		.dest_id = apicid,
10246 	};
10247 
10248 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
10249 }
10250 
kvm_apicv_activated(struct kvm * kvm)10251 bool kvm_apicv_activated(struct kvm *kvm)
10252 {
10253 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10254 }
10255 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
10256 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10257 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10258 {
10259 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10260 	ulong vcpu_reasons =
10261 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10262 
10263 	return (vm_reasons | vcpu_reasons) == 0;
10264 }
10265 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
10266 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10267 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10268 				       enum kvm_apicv_inhibit reason, bool set)
10269 {
10270 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10271 
10272 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10273 
10274 	if (set)
10275 		__set_bit(reason, inhibits);
10276 	else
10277 		__clear_bit(reason, inhibits);
10278 
10279 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10280 }
10281 
kvm_apicv_init(struct kvm * kvm)10282 static void kvm_apicv_init(struct kvm *kvm)
10283 {
10284 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10285 						       APICV_INHIBIT_REASON_DISABLED;
10286 
10287 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10288 
10289 	init_rwsem(&kvm->arch.apicv_update_lock);
10290 }
10291 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10292 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10293 {
10294 	struct kvm_vcpu *target = NULL;
10295 	struct kvm_apic_map *map;
10296 
10297 	vcpu->stat.directed_yield_attempted++;
10298 
10299 	if (single_task_running())
10300 		goto no_yield;
10301 
10302 	rcu_read_lock();
10303 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
10304 
10305 	if (likely(map) && dest_id <= map->max_apic_id) {
10306 		dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
10307 		if (map->phys_map[dest_id])
10308 			target = map->phys_map[dest_id]->vcpu;
10309 	}
10310 
10311 	rcu_read_unlock();
10312 
10313 	if (!target || !READ_ONCE(target->ready))
10314 		goto no_yield;
10315 
10316 	/* Ignore requests to yield to self */
10317 	if (vcpu == target)
10318 		goto no_yield;
10319 
10320 	if (kvm_vcpu_yield_to(target) <= 0)
10321 		goto no_yield;
10322 
10323 	vcpu->stat.directed_yield_successful++;
10324 
10325 no_yield:
10326 	return;
10327 }
10328 
complete_hypercall_exit(struct kvm_vcpu * vcpu)10329 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10330 {
10331 	u64 ret = vcpu->run->hypercall.ret;
10332 
10333 	if (!is_64_bit_hypercall(vcpu))
10334 		ret = (u32)ret;
10335 	kvm_rax_write(vcpu, ret);
10336 	return kvm_skip_emulated_instruction(vcpu);
10337 }
10338 
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10339 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10340 			      int (*complete_hypercall)(struct kvm_vcpu *))
10341 {
10342 	unsigned long ret;
10343 	unsigned long nr = kvm_rax_read(vcpu);
10344 	unsigned long a0 = kvm_rbx_read(vcpu);
10345 	unsigned long a1 = kvm_rcx_read(vcpu);
10346 	unsigned long a2 = kvm_rdx_read(vcpu);
10347 	unsigned long a3 = kvm_rsi_read(vcpu);
10348 	int op_64_bit = is_64_bit_hypercall(vcpu);
10349 
10350 	++vcpu->stat.hypercalls;
10351 
10352 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
10353 
10354 	if (!op_64_bit) {
10355 		nr &= 0xFFFFFFFF;
10356 		a0 &= 0xFFFFFFFF;
10357 		a1 &= 0xFFFFFFFF;
10358 		a2 &= 0xFFFFFFFF;
10359 		a3 &= 0xFFFFFFFF;
10360 	}
10361 
10362 	if (cpl) {
10363 		ret = -KVM_EPERM;
10364 		goto out;
10365 	}
10366 
10367 	ret = -KVM_ENOSYS;
10368 
10369 	switch (nr) {
10370 	case KVM_HC_VAPIC_POLL_IRQ:
10371 		ret = 0;
10372 		break;
10373 	case KVM_HC_KICK_CPU:
10374 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10375 			break;
10376 
10377 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10378 		kvm_sched_yield(vcpu, a1);
10379 		ret = 0;
10380 		break;
10381 #ifdef CONFIG_X86_64
10382 	case KVM_HC_CLOCK_PAIRING:
10383 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10384 		break;
10385 #endif
10386 	case KVM_HC_SEND_IPI:
10387 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10388 			break;
10389 
10390 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10391 		break;
10392 	case KVM_HC_SCHED_YIELD:
10393 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10394 			break;
10395 
10396 		kvm_sched_yield(vcpu, a0);
10397 		ret = 0;
10398 		break;
10399 	case KVM_HC_MAP_GPA_RANGE: {
10400 		u64 gpa = a0, npages = a1, attrs = a2;
10401 
10402 		ret = -KVM_ENOSYS;
10403 		if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10404 			break;
10405 
10406 		if (!PAGE_ALIGNED(gpa) || !npages ||
10407 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10408 			ret = -KVM_EINVAL;
10409 			break;
10410 		}
10411 
10412 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
10413 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
10414 		/*
10415 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10416 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10417 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
10418 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10419 		 */
10420 		vcpu->run->hypercall.ret = 0;
10421 		vcpu->run->hypercall.args[0]  = gpa;
10422 		vcpu->run->hypercall.args[1]  = npages;
10423 		vcpu->run->hypercall.args[2]  = attrs;
10424 		vcpu->run->hypercall.flags    = 0;
10425 		if (op_64_bit)
10426 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10427 
10428 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10429 		vcpu->arch.complete_userspace_io = complete_hypercall;
10430 		return 0;
10431 	}
10432 	default:
10433 		ret = -KVM_ENOSYS;
10434 		break;
10435 	}
10436 
10437 out:
10438 	vcpu->run->hypercall.ret = ret;
10439 	return 1;
10440 }
10441 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
10442 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10443 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10444 {
10445 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
10446 		return kvm_xen_hypercall(vcpu);
10447 
10448 	if (kvm_hv_hypercall_enabled(vcpu))
10449 		return kvm_hv_hypercall(vcpu);
10450 
10451 	return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10452 				       complete_hypercall_exit);
10453 }
10454 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
10455 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10456 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10457 {
10458 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10459 	char instruction[3];
10460 	unsigned long rip = kvm_rip_read(vcpu);
10461 
10462 	/*
10463 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10464 	 * the pieces.
10465 	 */
10466 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10467 		ctxt->exception.error_code_valid = false;
10468 		ctxt->exception.vector = UD_VECTOR;
10469 		ctxt->have_exception = true;
10470 		return X86EMUL_PROPAGATE_FAULT;
10471 	}
10472 
10473 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
10474 
10475 	return emulator_write_emulated(ctxt, rip, instruction, 3,
10476 		&ctxt->exception);
10477 }
10478 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10479 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10480 {
10481 	return vcpu->run->request_interrupt_window &&
10482 		likely(!pic_in_kernel(vcpu->kvm));
10483 }
10484 
10485 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)10486 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10487 {
10488 	struct kvm_run *kvm_run = vcpu->run;
10489 
10490 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10491 	kvm_run->cr8 = kvm_get_cr8(vcpu);
10492 	kvm_run->apic_base = vcpu->arch.apic_base;
10493 
10494 	kvm_run->ready_for_interrupt_injection =
10495 		pic_in_kernel(vcpu->kvm) ||
10496 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
10497 
10498 	if (is_smm(vcpu))
10499 		kvm_run->flags |= KVM_RUN_X86_SMM;
10500 	if (is_guest_mode(vcpu))
10501 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10502 }
10503 
update_cr8_intercept(struct kvm_vcpu * vcpu)10504 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10505 {
10506 	int max_irr, tpr;
10507 
10508 	if (!kvm_x86_ops.update_cr8_intercept)
10509 		return;
10510 
10511 	if (!lapic_in_kernel(vcpu))
10512 		return;
10513 
10514 	if (vcpu->arch.apic->apicv_active)
10515 		return;
10516 
10517 	if (!vcpu->arch.apic->vapic_addr)
10518 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10519 	else
10520 		max_irr = -1;
10521 
10522 	if (max_irr != -1)
10523 		max_irr >>= 4;
10524 
10525 	tpr = kvm_lapic_get_cr8(vcpu);
10526 
10527 	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10528 }
10529 
10530 
kvm_check_nested_events(struct kvm_vcpu * vcpu)10531 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10532 {
10533 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10534 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
10535 		return 1;
10536 	}
10537 
10538 	return kvm_x86_ops.nested_ops->check_events(vcpu);
10539 }
10540 
kvm_inject_exception(struct kvm_vcpu * vcpu)10541 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10542 {
10543 	/*
10544 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10545 	 * exceptions don't report error codes.  The presence of an error code
10546 	 * is carried with the exception and only stripped when the exception
10547 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10548 	 * report an error code despite the CPU being in Real Mode.
10549 	 */
10550 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10551 
10552 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
10553 				vcpu->arch.exception.has_error_code,
10554 				vcpu->arch.exception.error_code,
10555 				vcpu->arch.exception.injected);
10556 
10557 	kvm_x86_call(inject_exception)(vcpu);
10558 }
10559 
10560 /*
10561  * Check for any event (interrupt or exception) that is ready to be injected,
10562  * and if there is at least one event, inject the event with the highest
10563  * priority.  This handles both "pending" events, i.e. events that have never
10564  * been injected into the guest, and "injected" events, i.e. events that were
10565  * injected as part of a previous VM-Enter, but weren't successfully delivered
10566  * and need to be re-injected.
10567  *
10568  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10569  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
10570  * be able to inject exceptions in the "middle" of an instruction, and so must
10571  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10572  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10573  * boundaries is necessary and correct.
10574  *
10575  * For simplicity, KVM uses a single path to inject all events (except events
10576  * that are injected directly from L1 to L2) and doesn't explicitly track
10577  * instruction boundaries for asynchronous events.  However, because VM-Exits
10578  * that can occur during instruction execution typically result in KVM skipping
10579  * the instruction or injecting an exception, e.g. instruction and exception
10580  * intercepts, and because pending exceptions have higher priority than pending
10581  * interrupts, KVM still honors instruction boundaries in most scenarios.
10582  *
10583  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10584  * the instruction or inject an exception, then KVM can incorrecty inject a new
10585  * asynchronous event if the event became pending after the CPU fetched the
10586  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
10587  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10588  * injected on the restarted instruction instead of being deferred until the
10589  * instruction completes.
10590  *
10591  * In practice, this virtualization hole is unlikely to be observed by the
10592  * guest, and even less likely to cause functional problems.  To detect the
10593  * hole, the guest would have to trigger an event on a side effect of an early
10594  * phase of instruction execution, e.g. on the instruction fetch from memory.
10595  * And for it to be a functional problem, the guest would need to depend on the
10596  * ordering between that side effect, the instruction completing, _and_ the
10597  * delivery of the asynchronous event.
10598  */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10599 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10600 				       bool *req_immediate_exit)
10601 {
10602 	bool can_inject;
10603 	int r;
10604 
10605 	/*
10606 	 * Process nested events first, as nested VM-Exit supersedes event
10607 	 * re-injection.  If there's an event queued for re-injection, it will
10608 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10609 	 */
10610 	if (is_guest_mode(vcpu))
10611 		r = kvm_check_nested_events(vcpu);
10612 	else
10613 		r = 0;
10614 
10615 	/*
10616 	 * Re-inject exceptions and events *especially* if immediate entry+exit
10617 	 * to/from L2 is needed, as any event that has already been injected
10618 	 * into L2 needs to complete its lifecycle before injecting a new event.
10619 	 *
10620 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
10621 	 * This collision arises if an exception occurred while vectoring the
10622 	 * injected event, KVM intercepted said exception, and KVM ultimately
10623 	 * determined the fault belongs to the guest and queues the exception
10624 	 * for injection back into the guest.
10625 	 *
10626 	 * "Injected" interrupts can also collide with pending exceptions if
10627 	 * userspace ignores the "ready for injection" flag and blindly queues
10628 	 * an interrupt.  In that case, prioritizing the exception is correct,
10629 	 * as the exception "occurred" before the exit to userspace.  Trap-like
10630 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10631 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10632 	 * priority, they're only generated (pended) during instruction
10633 	 * execution, and interrupts are recognized at instruction boundaries.
10634 	 * Thus a pending fault-like exception means the fault occurred on the
10635 	 * *previous* instruction and must be serviced prior to recognizing any
10636 	 * new events in order to fully complete the previous instruction.
10637 	 */
10638 	if (vcpu->arch.exception.injected)
10639 		kvm_inject_exception(vcpu);
10640 	else if (kvm_is_exception_pending(vcpu))
10641 		; /* see above */
10642 	else if (vcpu->arch.nmi_injected)
10643 		kvm_x86_call(inject_nmi)(vcpu);
10644 	else if (vcpu->arch.interrupt.injected)
10645 		kvm_x86_call(inject_irq)(vcpu, true);
10646 
10647 	/*
10648 	 * Exceptions that morph to VM-Exits are handled above, and pending
10649 	 * exceptions on top of injected exceptions that do not VM-Exit should
10650 	 * either morph to #DF or, sadly, override the injected exception.
10651 	 */
10652 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
10653 		     vcpu->arch.exception.pending);
10654 
10655 	/*
10656 	 * Bail if immediate entry+exit to/from the guest is needed to complete
10657 	 * nested VM-Enter or event re-injection so that a different pending
10658 	 * event can be serviced (or if KVM needs to exit to userspace).
10659 	 *
10660 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
10661 	 * VM-Exit will have cleared exceptions that were meant for L2, but
10662 	 * there may now be events that can be injected into L1.
10663 	 */
10664 	if (r < 0)
10665 		goto out;
10666 
10667 	/*
10668 	 * A pending exception VM-Exit should either result in nested VM-Exit
10669 	 * or force an immediate re-entry and exit to/from L2, and exception
10670 	 * VM-Exits cannot be injected (flag should _never_ be set).
10671 	 */
10672 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10673 		     vcpu->arch.exception_vmexit.pending);
10674 
10675 	/*
10676 	 * New events, other than exceptions, cannot be injected if KVM needs
10677 	 * to re-inject a previous event.  See above comments on re-injecting
10678 	 * for why pending exceptions get priority.
10679 	 */
10680 	can_inject = !kvm_event_needs_reinjection(vcpu);
10681 
10682 	if (vcpu->arch.exception.pending) {
10683 		/*
10684 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10685 		 * value pushed on the stack.  Trap-like exception and all #DBs
10686 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
10687 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10688 		 *
10689 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10690 		 * describe the behavior of General Detect #DBs, which are
10691 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
10692 		 */
10693 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10694 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10695 					     X86_EFLAGS_RF);
10696 
10697 		if (vcpu->arch.exception.vector == DB_VECTOR) {
10698 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10699 			if (vcpu->arch.dr7 & DR7_GD) {
10700 				vcpu->arch.dr7 &= ~DR7_GD;
10701 				kvm_update_dr7(vcpu);
10702 			}
10703 		}
10704 
10705 		kvm_inject_exception(vcpu);
10706 
10707 		vcpu->arch.exception.pending = false;
10708 		vcpu->arch.exception.injected = true;
10709 
10710 		can_inject = false;
10711 	}
10712 
10713 	/* Don't inject interrupts if the user asked to avoid doing so */
10714 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10715 		return 0;
10716 
10717 	/*
10718 	 * Finally, inject interrupt events.  If an event cannot be injected
10719 	 * due to architectural conditions (e.g. IF=0) a window-open exit
10720 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
10721 	 * and can architecturally be injected, but we cannot do it right now:
10722 	 * an interrupt could have arrived just now and we have to inject it
10723 	 * as a vmexit, or there could already an event in the queue, which is
10724 	 * indicated by can_inject.  In that case we request an immediate exit
10725 	 * in order to make progress and get back here for another iteration.
10726 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10727 	 */
10728 #ifdef CONFIG_KVM_SMM
10729 	if (vcpu->arch.smi_pending) {
10730 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10731 				 -EBUSY;
10732 		if (r < 0)
10733 			goto out;
10734 		if (r) {
10735 			vcpu->arch.smi_pending = false;
10736 			++vcpu->arch.smi_count;
10737 			enter_smm(vcpu);
10738 			can_inject = false;
10739 		} else
10740 			kvm_x86_call(enable_smi_window)(vcpu);
10741 	}
10742 #endif
10743 
10744 	if (vcpu->arch.nmi_pending) {
10745 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10746 				 -EBUSY;
10747 		if (r < 0)
10748 			goto out;
10749 		if (r) {
10750 			--vcpu->arch.nmi_pending;
10751 			vcpu->arch.nmi_injected = true;
10752 			kvm_x86_call(inject_nmi)(vcpu);
10753 			can_inject = false;
10754 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10755 		}
10756 		if (vcpu->arch.nmi_pending)
10757 			kvm_x86_call(enable_nmi_window)(vcpu);
10758 	}
10759 
10760 	if (kvm_cpu_has_injectable_intr(vcpu)) {
10761 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10762 				 -EBUSY;
10763 		if (r < 0)
10764 			goto out;
10765 		if (r) {
10766 			int irq = kvm_cpu_get_interrupt(vcpu);
10767 
10768 			if (!WARN_ON_ONCE(irq == -1)) {
10769 				kvm_queue_interrupt(vcpu, irq, false);
10770 				kvm_x86_call(inject_irq)(vcpu, false);
10771 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10772 			}
10773 		}
10774 		if (kvm_cpu_has_injectable_intr(vcpu))
10775 			kvm_x86_call(enable_irq_window)(vcpu);
10776 	}
10777 
10778 	if (is_guest_mode(vcpu) &&
10779 	    kvm_x86_ops.nested_ops->has_events &&
10780 	    kvm_x86_ops.nested_ops->has_events(vcpu, true))
10781 		*req_immediate_exit = true;
10782 
10783 	/*
10784 	 * KVM must never queue a new exception while injecting an event; KVM
10785 	 * is done emulating and should only propagate the to-be-injected event
10786 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
10787 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
10788 	 * exception and start the cycle all over.
10789 	 *
10790 	 * Exempt triple faults as they have special handling and won't put the
10791 	 * vCPU into an infinite loop.  Triple fault can be queued when running
10792 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
10793 	 * Mode events (see kvm_inject_realmode_interrupt()).
10794 	 */
10795 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
10796 		     vcpu->arch.exception_vmexit.pending);
10797 	return 0;
10798 
10799 out:
10800 	if (r == -EBUSY) {
10801 		*req_immediate_exit = true;
10802 		r = 0;
10803 	}
10804 	return r;
10805 }
10806 
process_nmi(struct kvm_vcpu * vcpu)10807 static void process_nmi(struct kvm_vcpu *vcpu)
10808 {
10809 	unsigned int limit;
10810 
10811 	/*
10812 	 * x86 is limited to one NMI pending, but because KVM can't react to
10813 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10814 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
10815 	 * up at the same time.  To handle this scenario, allow two NMIs to be
10816 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10817 	 * waiting for a previous NMI injection to complete (which effectively
10818 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
10819 	 * will request an NMI window to handle the second NMI.
10820 	 */
10821 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10822 		limit = 1;
10823 	else
10824 		limit = 2;
10825 
10826 	/*
10827 	 * Adjust the limit to account for pending virtual NMIs, which aren't
10828 	 * tracked in vcpu->arch.nmi_pending.
10829 	 */
10830 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
10831 		limit--;
10832 
10833 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10834 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10835 
10836 	if (vcpu->arch.nmi_pending &&
10837 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
10838 		vcpu->arch.nmi_pending--;
10839 
10840 	if (vcpu->arch.nmi_pending)
10841 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10842 }
10843 
10844 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10845 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10846 {
10847 	return vcpu->arch.nmi_pending +
10848 	       kvm_x86_call(is_vnmi_pending)(vcpu);
10849 }
10850 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10851 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10852 				       unsigned long *vcpu_bitmap)
10853 {
10854 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10855 }
10856 
kvm_make_scan_ioapic_request(struct kvm * kvm)10857 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10858 {
10859 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10860 }
10861 
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10862 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10863 {
10864 	struct kvm_lapic *apic = vcpu->arch.apic;
10865 	bool activate;
10866 
10867 	if (!lapic_in_kernel(vcpu))
10868 		return;
10869 
10870 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10871 	preempt_disable();
10872 
10873 	/* Do not activate APICV when APIC is disabled */
10874 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10875 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10876 
10877 	if (apic->apicv_active == activate)
10878 		goto out;
10879 
10880 	apic->apicv_active = activate;
10881 	kvm_apic_update_apicv(vcpu);
10882 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10883 
10884 	/*
10885 	 * When APICv gets disabled, we may still have injected interrupts
10886 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10887 	 * still active when the interrupt got accepted. Make sure
10888 	 * kvm_check_and_inject_events() is called to check for that.
10889 	 */
10890 	if (!apic->apicv_active)
10891 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10892 
10893 out:
10894 	preempt_enable();
10895 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10896 }
10897 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
10898 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10899 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10900 {
10901 	if (!lapic_in_kernel(vcpu))
10902 		return;
10903 
10904 	/*
10905 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10906 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10907 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
10908 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
10909 	 * this case so that KVM can use the AVIC doorbell to inject interrupts
10910 	 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10911 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10912 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
10913 	 * access page is sticky.
10914 	 */
10915 	if (apic_x2apic_mode(vcpu->arch.apic) &&
10916 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10917 		kvm_inhibit_apic_access_page(vcpu);
10918 
10919 	__kvm_vcpu_update_apicv(vcpu);
10920 }
10921 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10922 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10923 				      enum kvm_apicv_inhibit reason, bool set)
10924 {
10925 	unsigned long old, new;
10926 
10927 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10928 
10929 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10930 		return;
10931 
10932 	old = new = kvm->arch.apicv_inhibit_reasons;
10933 
10934 	set_or_clear_apicv_inhibit(&new, reason, set);
10935 
10936 	if (!!old != !!new) {
10937 		/*
10938 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10939 		 * false positives in the sanity check WARN in vcpu_enter_guest().
10940 		 * This task will wait for all vCPUs to ack the kick IRQ before
10941 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10942 		 * block on acquiring apicv_update_lock so that vCPUs can't
10943 		 * redo vcpu_enter_guest() without seeing the new inhibit state.
10944 		 *
10945 		 * Note, holding apicv_update_lock and taking it in the read
10946 		 * side (handling the request) also prevents other vCPUs from
10947 		 * servicing the request with a stale apicv_inhibit_reasons.
10948 		 */
10949 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10950 		kvm->arch.apicv_inhibit_reasons = new;
10951 		if (new) {
10952 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10953 			int idx = srcu_read_lock(&kvm->srcu);
10954 
10955 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10956 			srcu_read_unlock(&kvm->srcu, idx);
10957 		}
10958 	} else {
10959 		kvm->arch.apicv_inhibit_reasons = new;
10960 	}
10961 }
10962 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10963 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10964 				    enum kvm_apicv_inhibit reason, bool set)
10965 {
10966 	if (!enable_apicv)
10967 		return;
10968 
10969 	down_write(&kvm->arch.apicv_update_lock);
10970 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10971 	up_write(&kvm->arch.apicv_update_lock);
10972 }
10973 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
10974 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10975 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10976 {
10977 	if (!kvm_apic_present(vcpu))
10978 		return;
10979 
10980 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10981 	vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
10982 
10983 	kvm_x86_call(sync_pir_to_irr)(vcpu);
10984 
10985 	if (irqchip_split(vcpu->kvm))
10986 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10987 #ifdef CONFIG_KVM_IOAPIC
10988 	else if (ioapic_in_kernel(vcpu->kvm))
10989 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10990 #endif
10991 
10992 	if (is_guest_mode(vcpu))
10993 		vcpu->arch.load_eoi_exitmap_pending = true;
10994 	else
10995 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10996 }
10997 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10998 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10999 {
11000 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
11001 		return;
11002 
11003 #ifdef CONFIG_KVM_HYPERV
11004 	if (to_hv_vcpu(vcpu)) {
11005 		u64 eoi_exit_bitmap[4];
11006 
11007 		bitmap_or((ulong *)eoi_exit_bitmap,
11008 			  vcpu->arch.ioapic_handled_vectors,
11009 			  to_hv_synic(vcpu)->vec_bitmap, 256);
11010 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
11011 		return;
11012 	}
11013 #endif
11014 	kvm_x86_call(load_eoi_exitmap)(
11015 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
11016 }
11017 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)11018 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
11019 {
11020 	kvm_x86_call(guest_memory_reclaimed)(kvm);
11021 }
11022 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)11023 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
11024 {
11025 	if (!lapic_in_kernel(vcpu))
11026 		return;
11027 
11028 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
11029 }
11030 
11031 /*
11032  * Called within kvm->srcu read side.
11033  * Returns 1 to let vcpu_run() continue the guest execution loop without
11034  * exiting to the userspace.  Otherwise, the value will be returned to the
11035  * userspace.
11036  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)11037 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
11038 {
11039 	int r;
11040 	bool req_int_win =
11041 		dm_request_for_irq_injection(vcpu) &&
11042 		kvm_cpu_accept_dm_intr(vcpu);
11043 	fastpath_t exit_fastpath;
11044 	u64 run_flags, debug_ctl;
11045 
11046 	bool req_immediate_exit = false;
11047 
11048 	if (kvm_request_pending(vcpu)) {
11049 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
11050 			r = -EIO;
11051 			goto out;
11052 		}
11053 
11054 		if (kvm_dirty_ring_check_request(vcpu)) {
11055 			r = 0;
11056 			goto out;
11057 		}
11058 
11059 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
11060 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
11061 				r = 0;
11062 				goto out;
11063 			}
11064 		}
11065 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
11066 			kvm_mmu_free_obsolete_roots(vcpu);
11067 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
11068 			__kvm_migrate_timers(vcpu);
11069 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
11070 			kvm_update_masterclock(vcpu->kvm);
11071 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
11072 			kvm_gen_kvmclock_update(vcpu);
11073 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
11074 			r = kvm_guest_time_update(vcpu);
11075 			if (unlikely(r))
11076 				goto out;
11077 		}
11078 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
11079 			kvm_mmu_sync_roots(vcpu);
11080 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
11081 			kvm_mmu_load_pgd(vcpu);
11082 
11083 		/*
11084 		 * Note, the order matters here, as flushing "all" TLB entries
11085 		 * also flushes the "current" TLB entries, i.e. servicing the
11086 		 * flush "all" will clear any request to flush "current".
11087 		 */
11088 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
11089 			kvm_vcpu_flush_tlb_all(vcpu);
11090 
11091 		kvm_service_local_tlb_flush_requests(vcpu);
11092 
11093 		/*
11094 		 * Fall back to a "full" guest flush if Hyper-V's precise
11095 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
11096 		 * the flushes are considered "remote" and not "local" because
11097 		 * the requests can be initiated from other vCPUs.
11098 		 */
11099 #ifdef CONFIG_KVM_HYPERV
11100 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
11101 		    kvm_hv_vcpu_flush_tlb(vcpu))
11102 			kvm_vcpu_flush_tlb_guest(vcpu);
11103 #endif
11104 
11105 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
11106 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
11107 			r = 0;
11108 			goto out;
11109 		}
11110 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11111 			if (is_guest_mode(vcpu))
11112 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
11113 
11114 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11115 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
11116 				vcpu->mmio_needed = 0;
11117 				r = 0;
11118 				goto out;
11119 			}
11120 		}
11121 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
11122 			/* Page is swapped out. Do synthetic halt */
11123 			vcpu->arch.apf.halted = true;
11124 			r = 1;
11125 			goto out;
11126 		}
11127 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
11128 			record_steal_time(vcpu);
11129 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
11130 			kvm_pmu_handle_event(vcpu);
11131 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
11132 			kvm_pmu_deliver_pmi(vcpu);
11133 #ifdef CONFIG_KVM_SMM
11134 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
11135 			process_smi(vcpu);
11136 #endif
11137 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
11138 			process_nmi(vcpu);
11139 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
11140 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
11141 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
11142 				     vcpu->arch.ioapic_handled_vectors)) {
11143 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
11144 				vcpu->run->eoi.vector =
11145 						vcpu->arch.pending_ioapic_eoi;
11146 				r = 0;
11147 				goto out;
11148 			}
11149 		}
11150 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
11151 			vcpu_scan_ioapic(vcpu);
11152 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
11153 			vcpu_load_eoi_exitmap(vcpu);
11154 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
11155 			kvm_vcpu_reload_apic_access_page(vcpu);
11156 #ifdef CONFIG_KVM_HYPERV
11157 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
11158 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11159 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
11160 			vcpu->run->system_event.ndata = 0;
11161 			r = 0;
11162 			goto out;
11163 		}
11164 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
11165 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11166 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
11167 			vcpu->run->system_event.ndata = 0;
11168 			r = 0;
11169 			goto out;
11170 		}
11171 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
11172 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
11173 
11174 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
11175 			vcpu->run->hyperv = hv_vcpu->exit;
11176 			r = 0;
11177 			goto out;
11178 		}
11179 
11180 		/*
11181 		 * KVM_REQ_HV_STIMER has to be processed after
11182 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
11183 		 * depend on the guest clock being up-to-date
11184 		 */
11185 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
11186 			kvm_hv_process_stimers(vcpu);
11187 #endif
11188 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
11189 			kvm_vcpu_update_apicv(vcpu);
11190 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
11191 			kvm_check_async_pf_completion(vcpu);
11192 
11193 		if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
11194 			kvm_x86_call(recalc_intercepts)(vcpu);
11195 
11196 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
11197 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
11198 
11199 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
11200 			kvm_vcpu_reset(vcpu, true);
11201 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
11202 				r = 1;
11203 				goto out;
11204 			}
11205 		}
11206 	}
11207 
11208 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
11209 	    kvm_xen_has_interrupt(vcpu)) {
11210 		++vcpu->stat.req_event;
11211 		r = kvm_apic_accept_events(vcpu);
11212 		if (r < 0) {
11213 			r = 0;
11214 			goto out;
11215 		}
11216 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
11217 			r = 1;
11218 			goto out;
11219 		}
11220 
11221 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
11222 		if (r < 0) {
11223 			r = 0;
11224 			goto out;
11225 		}
11226 		if (req_int_win)
11227 			kvm_x86_call(enable_irq_window)(vcpu);
11228 
11229 		if (kvm_lapic_enabled(vcpu)) {
11230 			update_cr8_intercept(vcpu);
11231 			kvm_lapic_sync_to_vapic(vcpu);
11232 		}
11233 	}
11234 
11235 	r = kvm_mmu_reload(vcpu);
11236 	if (unlikely(r)) {
11237 		goto cancel_injection;
11238 	}
11239 
11240 	preempt_disable();
11241 
11242 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
11243 
11244 	/*
11245 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
11246 	 * IPI are then delayed after guest entry, which ensures that they
11247 	 * result in virtual interrupt delivery.
11248 	 */
11249 	local_irq_disable();
11250 
11251 	/* Store vcpu->apicv_active before vcpu->mode.  */
11252 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
11253 
11254 	kvm_vcpu_srcu_read_unlock(vcpu);
11255 
11256 	/*
11257 	 * 1) We should set ->mode before checking ->requests.  Please see
11258 	 * the comment in kvm_vcpu_exiting_guest_mode().
11259 	 *
11260 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
11261 	 * pairs with the memory barrier implicit in pi_test_and_set_on
11262 	 * (see vmx_deliver_posted_interrupt).
11263 	 *
11264 	 * 3) This also orders the write to mode from any reads to the page
11265 	 * tables done while the VCPU is running.  Please see the comment
11266 	 * in kvm_flush_remote_tlbs.
11267 	 */
11268 	smp_mb__after_srcu_read_unlock();
11269 
11270 	/*
11271 	 * Process pending posted interrupts to handle the case where the
11272 	 * notification IRQ arrived in the host, or was never sent (because the
11273 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
11274 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
11275 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
11276 	 */
11277 	if (kvm_lapic_enabled(vcpu))
11278 		kvm_x86_call(sync_pir_to_irr)(vcpu);
11279 
11280 	if (kvm_vcpu_exit_request(vcpu)) {
11281 		vcpu->mode = OUTSIDE_GUEST_MODE;
11282 		smp_wmb();
11283 		local_irq_enable();
11284 		preempt_enable();
11285 		kvm_vcpu_srcu_read_lock(vcpu);
11286 		r = 1;
11287 		goto cancel_injection;
11288 	}
11289 
11290 	run_flags = 0;
11291 	if (req_immediate_exit) {
11292 		run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
11293 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11294 	}
11295 
11296 	fpregs_assert_state_consistent();
11297 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
11298 		switch_fpu_return();
11299 
11300 	if (vcpu->arch.guest_fpu.xfd_err)
11301 		wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11302 
11303 	kvm_load_xfeatures(vcpu, true);
11304 
11305 	if (unlikely(vcpu->arch.switch_db_regs &&
11306 		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11307 		set_debugreg(DR7_FIXED_1, 7);
11308 		set_debugreg(vcpu->arch.eff_db[0], 0);
11309 		set_debugreg(vcpu->arch.eff_db[1], 1);
11310 		set_debugreg(vcpu->arch.eff_db[2], 2);
11311 		set_debugreg(vcpu->arch.eff_db[3], 3);
11312 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11313 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11314 			run_flags |= KVM_RUN_LOAD_GUEST_DR6;
11315 	} else if (unlikely(hw_breakpoint_active())) {
11316 		set_debugreg(DR7_FIXED_1, 7);
11317 	}
11318 
11319 	/*
11320 	 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
11321 	 * can be modified in IRQ context, e.g. via SMP function calls.  Inform
11322 	 * vendor code if any host-owned bits were changed, e.g. so that the
11323 	 * value loaded into hardware while running the guest can be updated.
11324 	 */
11325 	debug_ctl = get_debugctlmsr();
11326 	if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
11327 	    !vcpu->arch.guest_state_protected)
11328 		run_flags |= KVM_RUN_LOAD_DEBUGCTL;
11329 	vcpu->arch.host_debugctl = debug_ctl;
11330 
11331 	guest_timing_enter_irqoff();
11332 
11333 	/*
11334 	 * Swap PKRU with hardware breakpoints disabled to minimize the number
11335 	 * of flows where non-KVM code can run with guest state loaded.
11336 	 */
11337 	kvm_load_guest_pkru(vcpu);
11338 
11339 	for (;;) {
11340 		/*
11341 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
11342 		 * update must kick and wait for all vCPUs before toggling the
11343 		 * per-VM state, and responding vCPUs must wait for the update
11344 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
11345 		 */
11346 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11347 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11348 
11349 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11350 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11351 			break;
11352 
11353 		if (kvm_lapic_enabled(vcpu))
11354 			kvm_x86_call(sync_pir_to_irr)(vcpu);
11355 
11356 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11357 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11358 			break;
11359 		}
11360 
11361 		run_flags = 0;
11362 
11363 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
11364 		++vcpu->stat.exits;
11365 	}
11366 
11367 	kvm_load_host_pkru(vcpu);
11368 
11369 	/*
11370 	 * Do this here before restoring debug registers on the host.  And
11371 	 * since we do this before handling the vmexit, a DR access vmexit
11372 	 * can (a) read the correct value of the debug registers, (b) set
11373 	 * KVM_DEBUGREG_WONT_EXIT again.
11374 	 */
11375 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11376 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11377 		WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11378 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11379 		kvm_update_dr0123(vcpu);
11380 		kvm_update_dr7(vcpu);
11381 	}
11382 
11383 	/*
11384 	 * If the guest has used debug registers, at least dr7
11385 	 * will be disabled while returning to the host.
11386 	 * If we don't have active breakpoints in the host, we don't
11387 	 * care about the messed up debug address registers. But if
11388 	 * we have some of them active, restore the old state.
11389 	 */
11390 	if (hw_breakpoint_active())
11391 		hw_breakpoint_restore();
11392 
11393 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11394 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11395 
11396 	vcpu->mode = OUTSIDE_GUEST_MODE;
11397 	smp_wmb();
11398 
11399 	kvm_load_xfeatures(vcpu, false);
11400 
11401 	/*
11402 	 * Sync xfd before calling handle_exit_irqoff() which may
11403 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11404 	 * in #NM irqoff handler).
11405 	 */
11406 	if (vcpu->arch.xfd_no_write_intercept)
11407 		fpu_sync_guest_vmexit_xfd_state();
11408 
11409 	kvm_x86_call(handle_exit_irqoff)(vcpu);
11410 
11411 	if (vcpu->arch.guest_fpu.xfd_err)
11412 		wrmsrq(MSR_IA32_XFD_ERR, 0);
11413 
11414 	/*
11415 	 * Mark this CPU as needing a branch predictor flush before running
11416 	 * userspace. Must be done before enabling preemption to ensure it gets
11417 	 * set for the CPU that actually ran the guest, and not the CPU that it
11418 	 * may migrate to.
11419 	 */
11420 	if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11421 		this_cpu_write(x86_ibpb_exit_to_user, true);
11422 
11423 	/*
11424 	 * Consume any pending interrupts, including the possible source of
11425 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11426 	 * An instruction is required after local_irq_enable() to fully unblock
11427 	 * interrupts on processors that implement an interrupt shadow, the
11428 	 * stat.exits increment will do nicely.
11429 	 */
11430 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11431 	local_irq_enable();
11432 	++vcpu->stat.exits;
11433 	local_irq_disable();
11434 	kvm_after_interrupt(vcpu);
11435 
11436 	/*
11437 	 * Wait until after servicing IRQs to account guest time so that any
11438 	 * ticks that occurred while running the guest are properly accounted
11439 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
11440 	 * of accounting via context tracking, but the loss of accuracy is
11441 	 * acceptable for all known use cases.
11442 	 */
11443 	guest_timing_exit_irqoff();
11444 
11445 	local_irq_enable();
11446 	preempt_enable();
11447 
11448 	kvm_vcpu_srcu_read_lock(vcpu);
11449 
11450 	/*
11451 	 * Call this to ensure WC buffers in guest are evicted after each VM
11452 	 * Exit, so that the evicted WC writes can be snooped across all cpus
11453 	 */
11454 	smp_mb__after_srcu_read_lock();
11455 
11456 	/*
11457 	 * Profile KVM exit RIPs:
11458 	 */
11459 	if (unlikely(prof_on == KVM_PROFILING &&
11460 		     !vcpu->arch.guest_state_protected)) {
11461 		unsigned long rip = kvm_rip_read(vcpu);
11462 		profile_hit(KVM_PROFILING, (void *)rip);
11463 	}
11464 
11465 	if (unlikely(vcpu->arch.tsc_always_catchup))
11466 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11467 
11468 	if (vcpu->arch.apic_attention)
11469 		kvm_lapic_sync_from_vapic(vcpu);
11470 
11471 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11472 		return 0;
11473 
11474 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11475 	return r;
11476 
11477 cancel_injection:
11478 	if (req_immediate_exit)
11479 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11480 	kvm_x86_call(cancel_injection)(vcpu);
11481 	if (unlikely(vcpu->arch.apic_attention))
11482 		kvm_lapic_sync_from_vapic(vcpu);
11483 out:
11484 	return r;
11485 }
11486 
kvm_vcpu_running(struct kvm_vcpu * vcpu)11487 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11488 {
11489 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11490 		!vcpu->arch.apf.halted);
11491 }
11492 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11493 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11494 {
11495 	if (!list_empty_careful(&vcpu->async_pf.done))
11496 		return true;
11497 
11498 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11499 	    kvm_apic_init_sipi_allowed(vcpu))
11500 		return true;
11501 
11502 	if (kvm_is_exception_pending(vcpu))
11503 		return true;
11504 
11505 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11506 	    (vcpu->arch.nmi_pending &&
11507 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
11508 		return true;
11509 
11510 #ifdef CONFIG_KVM_SMM
11511 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11512 	    (vcpu->arch.smi_pending &&
11513 	     kvm_x86_call(smi_allowed)(vcpu, false)))
11514 		return true;
11515 #endif
11516 
11517 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
11518 		return true;
11519 
11520 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11521 		return true;
11522 
11523 	if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11524 		return true;
11525 
11526 	if (kvm_hv_has_stimer_pending(vcpu))
11527 		return true;
11528 
11529 	if (is_guest_mode(vcpu) &&
11530 	    kvm_x86_ops.nested_ops->has_events &&
11531 	    kvm_x86_ops.nested_ops->has_events(vcpu, false))
11532 		return true;
11533 
11534 	if (kvm_xen_has_pending_events(vcpu))
11535 		return true;
11536 
11537 	return false;
11538 }
11539 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
11540 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11541 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11542 {
11543 	return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11544 	       kvm_vcpu_has_events(vcpu);
11545 }
11546 
11547 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)11548 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11549 {
11550 	bool hv_timer;
11551 
11552 	if (!kvm_arch_vcpu_runnable(vcpu)) {
11553 		/*
11554 		 * Switch to the software timer before halt-polling/blocking as
11555 		 * the guest's timer may be a break event for the vCPU, and the
11556 		 * hypervisor timer runs only when the CPU is in guest mode.
11557 		 * Switch before halt-polling so that KVM recognizes an expired
11558 		 * timer before blocking.
11559 		 */
11560 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11561 		if (hv_timer)
11562 			kvm_lapic_switch_to_sw_timer(vcpu);
11563 
11564 		kvm_vcpu_srcu_read_unlock(vcpu);
11565 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11566 			kvm_vcpu_halt(vcpu);
11567 		else
11568 			kvm_vcpu_block(vcpu);
11569 		kvm_vcpu_srcu_read_lock(vcpu);
11570 
11571 		if (hv_timer)
11572 			kvm_lapic_switch_to_hv_timer(vcpu);
11573 
11574 		/*
11575 		 * If the vCPU is not runnable, a signal or another host event
11576 		 * of some kind is pending; service it without changing the
11577 		 * vCPU's activity state.
11578 		 */
11579 		if (!kvm_arch_vcpu_runnable(vcpu))
11580 			return 1;
11581 	}
11582 
11583 	/*
11584 	 * Evaluate nested events before exiting the halted state.  This allows
11585 	 * the halt state to be recorded properly in the VMCS12's activity
11586 	 * state field (AMD does not have a similar field and a VM-Exit always
11587 	 * causes a spurious wakeup from HLT).
11588 	 */
11589 	if (is_guest_mode(vcpu)) {
11590 		int r = kvm_check_nested_events(vcpu);
11591 
11592 		WARN_ON_ONCE(r == -EBUSY);
11593 		if (r < 0)
11594 			return 0;
11595 	}
11596 
11597 	if (kvm_apic_accept_events(vcpu) < 0)
11598 		return 0;
11599 	switch(vcpu->arch.mp_state) {
11600 	case KVM_MP_STATE_HALTED:
11601 	case KVM_MP_STATE_AP_RESET_HOLD:
11602 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11603 		fallthrough;
11604 	case KVM_MP_STATE_RUNNABLE:
11605 		vcpu->arch.apf.halted = false;
11606 		break;
11607 	case KVM_MP_STATE_INIT_RECEIVED:
11608 		break;
11609 	default:
11610 		WARN_ON_ONCE(1);
11611 		break;
11612 	}
11613 	return 1;
11614 }
11615 
11616 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)11617 static int vcpu_run(struct kvm_vcpu *vcpu)
11618 {
11619 	int r;
11620 
11621 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11622 
11623 	for (;;) {
11624 		/*
11625 		 * If another guest vCPU requests a PV TLB flush in the middle
11626 		 * of instruction emulation, the rest of the emulation could
11627 		 * use a stale page translation. Assume that any code after
11628 		 * this point can start executing an instruction.
11629 		 */
11630 		vcpu->arch.at_instruction_boundary = false;
11631 		if (kvm_vcpu_running(vcpu)) {
11632 			r = vcpu_enter_guest(vcpu);
11633 		} else {
11634 			r = vcpu_block(vcpu);
11635 		}
11636 
11637 		if (r <= 0)
11638 			break;
11639 
11640 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11641 		if (kvm_xen_has_pending_events(vcpu))
11642 			kvm_xen_inject_pending_events(vcpu);
11643 
11644 		if (kvm_cpu_has_pending_timer(vcpu))
11645 			kvm_inject_pending_timer_irqs(vcpu);
11646 
11647 		if (dm_request_for_irq_injection(vcpu) &&
11648 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11649 			r = 0;
11650 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11651 			++vcpu->stat.request_irq_exits;
11652 			break;
11653 		}
11654 
11655 		if (__xfer_to_guest_mode_work_pending()) {
11656 			kvm_vcpu_srcu_read_unlock(vcpu);
11657 			r = kvm_xfer_to_guest_mode_handle_work(vcpu);
11658 			kvm_vcpu_srcu_read_lock(vcpu);
11659 			if (r)
11660 				return r;
11661 		}
11662 	}
11663 
11664 	return r;
11665 }
11666 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11667 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11668 {
11669 	/*
11670 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
11671 	 * local APIC is in-kernel, the run loop will detect the non-runnable
11672 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
11673 	 * managed by userspace, in which case userspace is responsible for
11674 	 * handling wake events.
11675 	 */
11676 	++vcpu->stat.halt_exits;
11677 	if (lapic_in_kernel(vcpu)) {
11678 		if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11679 			state = KVM_MP_STATE_RUNNABLE;
11680 		kvm_set_mp_state(vcpu, state);
11681 		return 1;
11682 	} else {
11683 		vcpu->run->exit_reason = reason;
11684 		return 0;
11685 	}
11686 }
11687 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11688 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11689 {
11690 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11691 }
11692 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
11693 
kvm_emulate_halt(struct kvm_vcpu * vcpu)11694 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11695 {
11696 	int ret = kvm_skip_emulated_instruction(vcpu);
11697 	/*
11698 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11699 	 * KVM_EXIT_DEBUG here.
11700 	 */
11701 	return kvm_emulate_halt_noskip(vcpu) && ret;
11702 }
11703 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
11704 
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11705 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11706 {
11707 	if (!kvm_emulate_halt(vcpu))
11708 		return EXIT_FASTPATH_EXIT_USERSPACE;
11709 
11710 	if (kvm_vcpu_running(vcpu))
11711 		return EXIT_FASTPATH_REENTER_GUEST;
11712 
11713 	return EXIT_FASTPATH_EXIT_HANDLED;
11714 }
11715 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
11716 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11717 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11718 {
11719 	int ret = kvm_skip_emulated_instruction(vcpu);
11720 
11721 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11722 					KVM_EXIT_AP_RESET_HOLD) && ret;
11723 }
11724 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
11725 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11726 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11727 {
11728 	return kvm_vcpu_apicv_active(vcpu) &&
11729 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11730 }
11731 
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11732 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11733 {
11734 	return vcpu->arch.preempted_in_kernel;
11735 }
11736 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11737 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11738 {
11739 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11740 		return true;
11741 
11742 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11743 #ifdef CONFIG_KVM_SMM
11744 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
11745 #endif
11746 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
11747 		return true;
11748 
11749 	return kvm_arch_dy_has_pending_interrupt(vcpu);
11750 }
11751 
complete_emulated_io(struct kvm_vcpu * vcpu)11752 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11753 {
11754 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11755 }
11756 
complete_emulated_pio(struct kvm_vcpu * vcpu)11757 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11758 {
11759 	BUG_ON(!vcpu->arch.pio.count);
11760 
11761 	return complete_emulated_io(vcpu);
11762 }
11763 
11764 /*
11765  * Implements the following, as a state machine:
11766  *
11767  * read:
11768  *   for each fragment
11769  *     for each mmio piece in the fragment
11770  *       write gpa, len
11771  *       exit
11772  *       copy data
11773  *   execute insn
11774  *
11775  * write:
11776  *   for each fragment
11777  *     for each mmio piece in the fragment
11778  *       write gpa, len
11779  *       copy data
11780  *       exit
11781  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11782 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11783 {
11784 	struct kvm_run *run = vcpu->run;
11785 	struct kvm_mmio_fragment *frag;
11786 	unsigned len;
11787 
11788 	BUG_ON(!vcpu->mmio_needed);
11789 
11790 	/* Complete previous fragment */
11791 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11792 	len = min(8u, frag->len);
11793 	if (!vcpu->mmio_is_write)
11794 		memcpy(frag->data, run->mmio.data, len);
11795 
11796 	if (frag->len <= 8) {
11797 		/* Switch to the next fragment. */
11798 		frag++;
11799 		vcpu->mmio_cur_fragment++;
11800 	} else {
11801 		/* Go forward to the next mmio piece. */
11802 		frag->data += len;
11803 		frag->gpa += len;
11804 		frag->len -= len;
11805 	}
11806 
11807 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11808 		vcpu->mmio_needed = 0;
11809 
11810 		/* FIXME: return into emulator if single-stepping.  */
11811 		if (vcpu->mmio_is_write)
11812 			return 1;
11813 		vcpu->mmio_read_completed = 1;
11814 		return complete_emulated_io(vcpu);
11815 	}
11816 
11817 	run->exit_reason = KVM_EXIT_MMIO;
11818 	run->mmio.phys_addr = frag->gpa;
11819 	if (vcpu->mmio_is_write)
11820 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11821 	run->mmio.len = min(8u, frag->len);
11822 	run->mmio.is_write = vcpu->mmio_is_write;
11823 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11824 	return 0;
11825 }
11826 
11827 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11828 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11829 {
11830 	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11831 		return;
11832 
11833 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11834 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11835 	trace_kvm_fpu(1);
11836 }
11837 
11838 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11839 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11840 {
11841 	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11842 		return;
11843 
11844 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11845 	++vcpu->stat.fpu_reload;
11846 	trace_kvm_fpu(0);
11847 }
11848 
kvm_x86_vcpu_pre_run(struct kvm_vcpu * vcpu)11849 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
11850 {
11851 	/*
11852 	 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
11853 	 * tracks the pending SIPI separately.  SIPI_RECEIVED is still accepted
11854 	 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
11855 	 * converted to INIT_RECEIVED.
11856 	 */
11857 	if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
11858 		return -EINVAL;
11859 
11860 	/*
11861 	 * Disallow running the vCPU if userspace forced it into an impossible
11862 	 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
11863 	 */
11864 	if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
11865 	    !kvm_apic_init_sipi_allowed(vcpu))
11866 		return -EINVAL;
11867 
11868 	return kvm_x86_call(vcpu_pre_run)(vcpu);
11869 }
11870 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11871 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11872 {
11873 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
11874 	struct kvm_run *kvm_run = vcpu->run;
11875 	u64 sync_valid_fields;
11876 	int r;
11877 
11878 	r = kvm_mmu_post_init_vm(vcpu->kvm);
11879 	if (r)
11880 		return r;
11881 
11882 	vcpu_load(vcpu);
11883 	kvm_sigset_activate(vcpu);
11884 	kvm_run->flags = 0;
11885 	kvm_load_guest_fpu(vcpu);
11886 
11887 	kvm_vcpu_srcu_read_lock(vcpu);
11888 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11889 		if (!vcpu->wants_to_run) {
11890 			r = -EINTR;
11891 			goto out;
11892 		}
11893 
11894 		/*
11895 		 * Don't bother switching APIC timer emulation from the
11896 		 * hypervisor timer to the software timer, the only way for the
11897 		 * APIC timer to be active is if userspace stuffed vCPU state,
11898 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
11899 		 * will transition the vCPU out of UNINITIALIZED (without more
11900 		 * state stuffing from userspace), which will reset the local
11901 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
11902 		 * already expired).
11903 		 */
11904 		kvm_vcpu_srcu_read_unlock(vcpu);
11905 		kvm_vcpu_block(vcpu);
11906 		kvm_vcpu_srcu_read_lock(vcpu);
11907 
11908 		if (kvm_apic_accept_events(vcpu) < 0) {
11909 			r = 0;
11910 			goto out;
11911 		}
11912 		r = -EAGAIN;
11913 		if (signal_pending(current)) {
11914 			r = -EINTR;
11915 			kvm_run->exit_reason = KVM_EXIT_INTR;
11916 			++vcpu->stat.signal_exits;
11917 		}
11918 		goto out;
11919 	}
11920 
11921 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11922 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11923 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11924 		r = -EINVAL;
11925 		goto out;
11926 	}
11927 
11928 	if (kvm_run->kvm_dirty_regs) {
11929 		r = sync_regs(vcpu);
11930 		if (r != 0)
11931 			goto out;
11932 	}
11933 
11934 	/* re-sync apic's tpr */
11935 	if (!lapic_in_kernel(vcpu)) {
11936 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11937 			r = -EINVAL;
11938 			goto out;
11939 		}
11940 	}
11941 
11942 	/*
11943 	 * If userspace set a pending exception and L2 is active, convert it to
11944 	 * a pending VM-Exit if L1 wants to intercept the exception.
11945 	 */
11946 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11947 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11948 							ex->error_code)) {
11949 		kvm_queue_exception_vmexit(vcpu, ex->vector,
11950 					   ex->has_error_code, ex->error_code,
11951 					   ex->has_payload, ex->payload);
11952 		ex->injected = false;
11953 		ex->pending = false;
11954 	}
11955 	vcpu->arch.exception_from_userspace = false;
11956 
11957 	if (unlikely(vcpu->arch.complete_userspace_io)) {
11958 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11959 		vcpu->arch.complete_userspace_io = NULL;
11960 		r = cui(vcpu);
11961 		if (r <= 0)
11962 			goto out;
11963 	} else {
11964 		WARN_ON_ONCE(vcpu->arch.pio.count);
11965 		WARN_ON_ONCE(vcpu->mmio_needed);
11966 	}
11967 
11968 	if (!vcpu->wants_to_run) {
11969 		r = -EINTR;
11970 		goto out;
11971 	}
11972 
11973 	r = kvm_x86_vcpu_pre_run(vcpu);
11974 	if (r <= 0)
11975 		goto out;
11976 
11977 	r = vcpu_run(vcpu);
11978 
11979 out:
11980 	kvm_put_guest_fpu(vcpu);
11981 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11982 		store_regs(vcpu);
11983 	post_kvm_run_save(vcpu);
11984 	kvm_vcpu_srcu_read_unlock(vcpu);
11985 
11986 	kvm_sigset_deactivate(vcpu);
11987 	vcpu_put(vcpu);
11988 	return r;
11989 }
11990 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11991 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11992 {
11993 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11994 		/*
11995 		 * We are here if userspace calls get_regs() in the middle of
11996 		 * instruction emulation. Registers state needs to be copied
11997 		 * back from emulation context to vcpu. Userspace shouldn't do
11998 		 * that usually, but some bad designed PV devices (vmware
11999 		 * backdoor interface) need this to work
12000 		 */
12001 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
12002 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12003 	}
12004 	regs->rax = kvm_rax_read(vcpu);
12005 	regs->rbx = kvm_rbx_read(vcpu);
12006 	regs->rcx = kvm_rcx_read(vcpu);
12007 	regs->rdx = kvm_rdx_read(vcpu);
12008 	regs->rsi = kvm_rsi_read(vcpu);
12009 	regs->rdi = kvm_rdi_read(vcpu);
12010 	regs->rsp = kvm_rsp_read(vcpu);
12011 	regs->rbp = kvm_rbp_read(vcpu);
12012 #ifdef CONFIG_X86_64
12013 	regs->r8 = kvm_r8_read(vcpu);
12014 	regs->r9 = kvm_r9_read(vcpu);
12015 	regs->r10 = kvm_r10_read(vcpu);
12016 	regs->r11 = kvm_r11_read(vcpu);
12017 	regs->r12 = kvm_r12_read(vcpu);
12018 	regs->r13 = kvm_r13_read(vcpu);
12019 	regs->r14 = kvm_r14_read(vcpu);
12020 	regs->r15 = kvm_r15_read(vcpu);
12021 #endif
12022 
12023 	regs->rip = kvm_rip_read(vcpu);
12024 	regs->rflags = kvm_get_rflags(vcpu);
12025 }
12026 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12027 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12028 {
12029 	if (vcpu->kvm->arch.has_protected_state &&
12030 	    vcpu->arch.guest_state_protected)
12031 		return -EINVAL;
12032 
12033 	vcpu_load(vcpu);
12034 	__get_regs(vcpu, regs);
12035 	vcpu_put(vcpu);
12036 	return 0;
12037 }
12038 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12039 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12040 {
12041 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
12042 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12043 
12044 	kvm_rax_write(vcpu, regs->rax);
12045 	kvm_rbx_write(vcpu, regs->rbx);
12046 	kvm_rcx_write(vcpu, regs->rcx);
12047 	kvm_rdx_write(vcpu, regs->rdx);
12048 	kvm_rsi_write(vcpu, regs->rsi);
12049 	kvm_rdi_write(vcpu, regs->rdi);
12050 	kvm_rsp_write(vcpu, regs->rsp);
12051 	kvm_rbp_write(vcpu, regs->rbp);
12052 #ifdef CONFIG_X86_64
12053 	kvm_r8_write(vcpu, regs->r8);
12054 	kvm_r9_write(vcpu, regs->r9);
12055 	kvm_r10_write(vcpu, regs->r10);
12056 	kvm_r11_write(vcpu, regs->r11);
12057 	kvm_r12_write(vcpu, regs->r12);
12058 	kvm_r13_write(vcpu, regs->r13);
12059 	kvm_r14_write(vcpu, regs->r14);
12060 	kvm_r15_write(vcpu, regs->r15);
12061 #endif
12062 
12063 	kvm_rip_write(vcpu, regs->rip);
12064 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
12065 
12066 	vcpu->arch.exception.pending = false;
12067 	vcpu->arch.exception_vmexit.pending = false;
12068 
12069 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12070 }
12071 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12072 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12073 {
12074 	if (vcpu->kvm->arch.has_protected_state &&
12075 	    vcpu->arch.guest_state_protected)
12076 		return -EINVAL;
12077 
12078 	vcpu_load(vcpu);
12079 	__set_regs(vcpu, regs);
12080 	vcpu_put(vcpu);
12081 	return 0;
12082 }
12083 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12084 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12085 {
12086 	struct desc_ptr dt;
12087 
12088 	if (vcpu->arch.guest_state_protected)
12089 		goto skip_protected_regs;
12090 
12091 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12092 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12093 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12094 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12095 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12096 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12097 
12098 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12099 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12100 
12101 	kvm_x86_call(get_idt)(vcpu, &dt);
12102 	sregs->idt.limit = dt.size;
12103 	sregs->idt.base = dt.address;
12104 	kvm_x86_call(get_gdt)(vcpu, &dt);
12105 	sregs->gdt.limit = dt.size;
12106 	sregs->gdt.base = dt.address;
12107 
12108 	sregs->cr2 = vcpu->arch.cr2;
12109 	sregs->cr3 = kvm_read_cr3(vcpu);
12110 
12111 skip_protected_regs:
12112 	sregs->cr0 = kvm_read_cr0(vcpu);
12113 	sregs->cr4 = kvm_read_cr4(vcpu);
12114 	sregs->cr8 = kvm_get_cr8(vcpu);
12115 	sregs->efer = vcpu->arch.efer;
12116 	sregs->apic_base = vcpu->arch.apic_base;
12117 }
12118 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12119 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12120 {
12121 	__get_sregs_common(vcpu, sregs);
12122 
12123 	if (vcpu->arch.guest_state_protected)
12124 		return;
12125 
12126 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
12127 		set_bit(vcpu->arch.interrupt.nr,
12128 			(unsigned long *)sregs->interrupt_bitmap);
12129 }
12130 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12131 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12132 {
12133 	int i;
12134 
12135 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
12136 
12137 	if (vcpu->arch.guest_state_protected)
12138 		return;
12139 
12140 	if (is_pae_paging(vcpu)) {
12141 		for (i = 0 ; i < 4 ; i++)
12142 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
12143 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
12144 	}
12145 }
12146 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12147 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
12148 				  struct kvm_sregs *sregs)
12149 {
12150 	if (vcpu->kvm->arch.has_protected_state &&
12151 	    vcpu->arch.guest_state_protected)
12152 		return -EINVAL;
12153 
12154 	vcpu_load(vcpu);
12155 	__get_sregs(vcpu, sregs);
12156 	vcpu_put(vcpu);
12157 	return 0;
12158 }
12159 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12160 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
12161 				    struct kvm_mp_state *mp_state)
12162 {
12163 	int r;
12164 
12165 	vcpu_load(vcpu);
12166 	kvm_vcpu_srcu_read_lock(vcpu);
12167 
12168 	r = kvm_apic_accept_events(vcpu);
12169 	if (r < 0)
12170 		goto out;
12171 	r = 0;
12172 
12173 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
12174 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
12175 	    vcpu->arch.pv.pv_unhalted)
12176 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
12177 	else
12178 		mp_state->mp_state = vcpu->arch.mp_state;
12179 
12180 out:
12181 	kvm_vcpu_srcu_read_unlock(vcpu);
12182 	vcpu_put(vcpu);
12183 	return r;
12184 }
12185 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12186 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
12187 				    struct kvm_mp_state *mp_state)
12188 {
12189 	int ret = -EINVAL;
12190 
12191 	vcpu_load(vcpu);
12192 
12193 	switch (mp_state->mp_state) {
12194 	case KVM_MP_STATE_UNINITIALIZED:
12195 	case KVM_MP_STATE_HALTED:
12196 	case KVM_MP_STATE_AP_RESET_HOLD:
12197 	case KVM_MP_STATE_INIT_RECEIVED:
12198 	case KVM_MP_STATE_SIPI_RECEIVED:
12199 		if (!lapic_in_kernel(vcpu))
12200 			goto out;
12201 		break;
12202 
12203 	case KVM_MP_STATE_RUNNABLE:
12204 		break;
12205 
12206 	default:
12207 		goto out;
12208 	}
12209 
12210 	/*
12211 	 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
12212 	 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
12213 	 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
12214 	 */
12215 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
12216 		mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
12217 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
12218 	}
12219 
12220 	kvm_set_mp_state(vcpu, mp_state->mp_state);
12221 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12222 
12223 	ret = 0;
12224 out:
12225 	vcpu_put(vcpu);
12226 	return ret;
12227 }
12228 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)12229 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
12230 		    int reason, bool has_error_code, u32 error_code)
12231 {
12232 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
12233 	int ret;
12234 
12235 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
12236 		u64 u_cet, s_cet;
12237 
12238 		/*
12239 		 * Check both User and Supervisor on task switches as inter-
12240 		 * privilege level task switches are impacted by CET at both
12241 		 * the current privilege level and the new privilege level, and
12242 		 * that information is not known at this time.  The expectation
12243 		 * is that the guest won't require emulation of task switches
12244 		 * while using IBT or Shadow Stacks.
12245 		 */
12246 		if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
12247 		    __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
12248 			goto unhandled_task_switch;
12249 
12250 		if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
12251 			goto unhandled_task_switch;
12252 	}
12253 
12254 	init_emulate_ctxt(vcpu);
12255 
12256 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
12257 				   has_error_code, error_code);
12258 
12259 	/*
12260 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
12261 	 * MMIO during a task switch (or any other complex operation).
12262 	 */
12263 	if (ret || vcpu->mmio_needed)
12264 		goto unhandled_task_switch;
12265 
12266 	kvm_rip_write(vcpu, ctxt->eip);
12267 	kvm_set_rflags(vcpu, ctxt->eflags);
12268 	return 1;
12269 
12270 unhandled_task_switch:
12271 	vcpu->mmio_needed = false;
12272 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
12273 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
12274 	vcpu->run->internal.ndata = 0;
12275 	return 0;
12276 }
12277 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
12278 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12279 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12280 {
12281 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
12282 		/*
12283 		 * When EFER.LME and CR0.PG are set, the processor is in
12284 		 * 64-bit mode (though maybe in a 32-bit code segment).
12285 		 * CR4.PAE and EFER.LMA must be set.
12286 		 */
12287 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
12288 			return false;
12289 		if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
12290 			return false;
12291 	} else {
12292 		/*
12293 		 * Not in 64-bit mode: EFER.LMA is clear and the code
12294 		 * segment cannot be 64-bit.
12295 		 */
12296 		if (sregs->efer & EFER_LMA || sregs->cs.l)
12297 			return false;
12298 	}
12299 
12300 	return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
12301 	       kvm_is_valid_cr0(vcpu, sregs->cr0);
12302 }
12303 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)12304 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
12305 		int *mmu_reset_needed, bool update_pdptrs)
12306 {
12307 	int idx;
12308 	struct desc_ptr dt;
12309 
12310 	if (!kvm_is_valid_sregs(vcpu, sregs))
12311 		return -EINVAL;
12312 
12313 	if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
12314 		return -EINVAL;
12315 
12316 	if (vcpu->arch.guest_state_protected)
12317 		return 0;
12318 
12319 	dt.size = sregs->idt.limit;
12320 	dt.address = sregs->idt.base;
12321 	kvm_x86_call(set_idt)(vcpu, &dt);
12322 	dt.size = sregs->gdt.limit;
12323 	dt.address = sregs->gdt.base;
12324 	kvm_x86_call(set_gdt)(vcpu, &dt);
12325 
12326 	vcpu->arch.cr2 = sregs->cr2;
12327 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
12328 	vcpu->arch.cr3 = sregs->cr3;
12329 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12330 	kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12331 
12332 	kvm_set_cr8(vcpu, sregs->cr8);
12333 
12334 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12335 	kvm_x86_call(set_efer)(vcpu, sregs->efer);
12336 
12337 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12338 	kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12339 
12340 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12341 	kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12342 
12343 	if (update_pdptrs) {
12344 		idx = srcu_read_lock(&vcpu->kvm->srcu);
12345 		if (is_pae_paging(vcpu)) {
12346 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12347 			*mmu_reset_needed = 1;
12348 		}
12349 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
12350 	}
12351 
12352 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12353 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12354 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12355 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12356 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12357 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12358 
12359 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12360 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12361 
12362 	update_cr8_intercept(vcpu);
12363 
12364 	/* Older userspace won't unhalt the vcpu on reset. */
12365 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12366 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12367 	    !is_protmode(vcpu))
12368 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12369 
12370 	return 0;
12371 }
12372 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12373 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12374 {
12375 	int pending_vec, max_bits;
12376 	int mmu_reset_needed = 0;
12377 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12378 
12379 	if (ret)
12380 		return ret;
12381 
12382 	if (mmu_reset_needed) {
12383 		kvm_mmu_reset_context(vcpu);
12384 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12385 	}
12386 
12387 	max_bits = KVM_NR_INTERRUPTS;
12388 	pending_vec = find_first_bit(
12389 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
12390 
12391 	if (pending_vec < max_bits) {
12392 		kvm_queue_interrupt(vcpu, pending_vec, false);
12393 		pr_debug("Set back pending irq %d\n", pending_vec);
12394 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12395 	}
12396 	return 0;
12397 }
12398 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12399 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12400 {
12401 	int mmu_reset_needed = 0;
12402 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12403 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12404 		!(sregs2->efer & EFER_LMA);
12405 	int i, ret;
12406 
12407 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12408 		return -EINVAL;
12409 
12410 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12411 		return -EINVAL;
12412 
12413 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12414 				 &mmu_reset_needed, !valid_pdptrs);
12415 	if (ret)
12416 		return ret;
12417 
12418 	if (valid_pdptrs) {
12419 		for (i = 0; i < 4 ; i++)
12420 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12421 
12422 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12423 		mmu_reset_needed = 1;
12424 		vcpu->arch.pdptrs_from_userspace = true;
12425 	}
12426 	if (mmu_reset_needed) {
12427 		kvm_mmu_reset_context(vcpu);
12428 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12429 	}
12430 	return 0;
12431 }
12432 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12433 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12434 				  struct kvm_sregs *sregs)
12435 {
12436 	int ret;
12437 
12438 	if (vcpu->kvm->arch.has_protected_state &&
12439 	    vcpu->arch.guest_state_protected)
12440 		return -EINVAL;
12441 
12442 	vcpu_load(vcpu);
12443 	ret = __set_sregs(vcpu, sregs);
12444 	vcpu_put(vcpu);
12445 	return ret;
12446 }
12447 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12448 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12449 {
12450 	bool set = false;
12451 	struct kvm_vcpu *vcpu;
12452 	unsigned long i;
12453 
12454 	if (!enable_apicv)
12455 		return;
12456 
12457 	down_write(&kvm->arch.apicv_update_lock);
12458 
12459 	kvm_for_each_vcpu(i, vcpu, kvm) {
12460 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12461 			set = true;
12462 			break;
12463 		}
12464 	}
12465 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12466 	up_write(&kvm->arch.apicv_update_lock);
12467 }
12468 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12469 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12470 					struct kvm_guest_debug *dbg)
12471 {
12472 	unsigned long rflags;
12473 	int i, r;
12474 
12475 	if (vcpu->arch.guest_state_protected)
12476 		return -EINVAL;
12477 
12478 	vcpu_load(vcpu);
12479 
12480 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12481 		r = -EBUSY;
12482 		if (kvm_is_exception_pending(vcpu))
12483 			goto out;
12484 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12485 			kvm_queue_exception(vcpu, DB_VECTOR);
12486 		else
12487 			kvm_queue_exception(vcpu, BP_VECTOR);
12488 	}
12489 
12490 	/*
12491 	 * Read rflags as long as potentially injected trace flags are still
12492 	 * filtered out.
12493 	 */
12494 	rflags = kvm_get_rflags(vcpu);
12495 
12496 	vcpu->guest_debug = dbg->control;
12497 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12498 		vcpu->guest_debug = 0;
12499 
12500 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12501 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
12502 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12503 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12504 	} else {
12505 		for (i = 0; i < KVM_NR_DB_REGS; i++)
12506 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12507 	}
12508 	kvm_update_dr7(vcpu);
12509 
12510 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12511 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12512 
12513 	/*
12514 	 * Trigger an rflags update that will inject or remove the trace
12515 	 * flags.
12516 	 */
12517 	kvm_set_rflags(vcpu, rflags);
12518 
12519 	kvm_x86_call(update_exception_bitmap)(vcpu);
12520 
12521 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12522 
12523 	r = 0;
12524 
12525 out:
12526 	vcpu_put(vcpu);
12527 	return r;
12528 }
12529 
12530 /*
12531  * Translate a guest virtual address to a guest physical address.
12532  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12533 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12534 				    struct kvm_translation *tr)
12535 {
12536 	unsigned long vaddr = tr->linear_address;
12537 	gpa_t gpa;
12538 	int idx;
12539 
12540 	vcpu_load(vcpu);
12541 
12542 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12543 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12544 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12545 	tr->physical_address = gpa;
12546 	tr->valid = gpa != INVALID_GPA;
12547 	tr->writeable = 1;
12548 	tr->usermode = 0;
12549 
12550 	vcpu_put(vcpu);
12551 	return 0;
12552 }
12553 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12554 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12555 {
12556 	struct fxregs_state *fxsave;
12557 
12558 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12559 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12560 
12561 	vcpu_load(vcpu);
12562 
12563 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12564 	memcpy(fpu->fpr, fxsave->st_space, 128);
12565 	fpu->fcw = fxsave->cwd;
12566 	fpu->fsw = fxsave->swd;
12567 	fpu->ftwx = fxsave->twd;
12568 	fpu->last_opcode = fxsave->fop;
12569 	fpu->last_ip = fxsave->rip;
12570 	fpu->last_dp = fxsave->rdp;
12571 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12572 
12573 	vcpu_put(vcpu);
12574 	return 0;
12575 }
12576 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12577 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12578 {
12579 	struct fxregs_state *fxsave;
12580 
12581 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12582 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12583 
12584 	vcpu_load(vcpu);
12585 
12586 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12587 
12588 	memcpy(fxsave->st_space, fpu->fpr, 128);
12589 	fxsave->cwd = fpu->fcw;
12590 	fxsave->swd = fpu->fsw;
12591 	fxsave->twd = fpu->ftwx;
12592 	fxsave->fop = fpu->last_opcode;
12593 	fxsave->rip = fpu->last_ip;
12594 	fxsave->rdp = fpu->last_dp;
12595 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12596 
12597 	vcpu_put(vcpu);
12598 	return 0;
12599 }
12600 
store_regs(struct kvm_vcpu * vcpu)12601 static void store_regs(struct kvm_vcpu *vcpu)
12602 {
12603 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12604 
12605 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12606 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
12607 
12608 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12609 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12610 
12611 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12612 		kvm_vcpu_ioctl_x86_get_vcpu_events(
12613 				vcpu, &vcpu->run->s.regs.events);
12614 }
12615 
sync_regs(struct kvm_vcpu * vcpu)12616 static int sync_regs(struct kvm_vcpu *vcpu)
12617 {
12618 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12619 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
12620 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12621 	}
12622 
12623 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12624 		struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12625 
12626 		if (__set_sregs(vcpu, &sregs))
12627 			return -EINVAL;
12628 
12629 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12630 	}
12631 
12632 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12633 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12634 
12635 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12636 			return -EINVAL;
12637 
12638 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12639 	}
12640 
12641 	return 0;
12642 }
12643 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12644 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12645 {
12646 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12647 		pr_warn_once("SMP vm created on host with unstable TSC; "
12648 			     "guest TSC will not be reliable\n");
12649 
12650 	if (!kvm->arch.max_vcpu_ids)
12651 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12652 
12653 	if (id >= kvm->arch.max_vcpu_ids)
12654 		return -EINVAL;
12655 
12656 	return kvm_x86_call(vcpu_precreate)(kvm);
12657 }
12658 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12659 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12660 {
12661 	struct page *page;
12662 	int r;
12663 
12664 	vcpu->arch.last_vmentry_cpu = -1;
12665 	vcpu->arch.regs_avail = ~0;
12666 	vcpu->arch.regs_dirty = ~0;
12667 
12668 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12669 
12670 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12671 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12672 	else
12673 		kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12674 
12675 	r = kvm_mmu_create(vcpu);
12676 	if (r < 0)
12677 		return r;
12678 
12679 	r = kvm_create_lapic(vcpu);
12680 	if (r < 0)
12681 		goto fail_mmu_destroy;
12682 
12683 	r = -ENOMEM;
12684 
12685 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12686 	if (!page)
12687 		goto fail_free_lapic;
12688 	vcpu->arch.pio_data = page_address(page);
12689 
12690 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12691 				       GFP_KERNEL_ACCOUNT);
12692 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12693 					    GFP_KERNEL_ACCOUNT);
12694 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12695 		goto fail_free_mce_banks;
12696 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12697 
12698 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12699 				GFP_KERNEL_ACCOUNT))
12700 		goto fail_free_mce_banks;
12701 
12702 	if (!alloc_emulate_ctxt(vcpu))
12703 		goto free_wbinvd_dirty_mask;
12704 
12705 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12706 		pr_err("failed to allocate vcpu's fpu\n");
12707 		goto free_emulate_ctxt;
12708 	}
12709 
12710 	kvm_async_pf_hash_reset(vcpu);
12711 
12712 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12713 		vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12714 		vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12715 		vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12716 	}
12717 	kvm_pmu_init(vcpu);
12718 
12719 	vcpu->arch.pending_external_vector = -1;
12720 	vcpu->arch.preempted_in_kernel = false;
12721 
12722 #if IS_ENABLED(CONFIG_HYPERV)
12723 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
12724 #endif
12725 
12726 	r = kvm_x86_call(vcpu_create)(vcpu);
12727 	if (r)
12728 		goto free_guest_fpu;
12729 
12730 	kvm_xen_init_vcpu(vcpu);
12731 	vcpu_load(vcpu);
12732 	kvm_vcpu_after_set_cpuid(vcpu);
12733 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12734 	kvm_vcpu_reset(vcpu, false);
12735 	kvm_init_mmu(vcpu);
12736 	vcpu_put(vcpu);
12737 	return 0;
12738 
12739 free_guest_fpu:
12740 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12741 free_emulate_ctxt:
12742 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12743 free_wbinvd_dirty_mask:
12744 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12745 fail_free_mce_banks:
12746 	kfree(vcpu->arch.mce_banks);
12747 	kfree(vcpu->arch.mci_ctl2_banks);
12748 	free_page((unsigned long)vcpu->arch.pio_data);
12749 fail_free_lapic:
12750 	kvm_free_lapic(vcpu);
12751 fail_mmu_destroy:
12752 	kvm_mmu_destroy(vcpu);
12753 	return r;
12754 }
12755 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12756 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12757 {
12758 	if (mutex_lock_killable(&vcpu->mutex))
12759 		return;
12760 	vcpu_load(vcpu);
12761 	kvm_synchronize_tsc(vcpu, NULL);
12762 	vcpu_put(vcpu);
12763 
12764 	/* poll control enabled by default */
12765 	vcpu->arch.msr_kvm_poll_control = 1;
12766 
12767 	mutex_unlock(&vcpu->mutex);
12768 }
12769 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12770 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12771 {
12772 	int idx, cpu;
12773 
12774 	kvm_clear_async_pf_completion_queue(vcpu);
12775 	kvm_mmu_unload(vcpu);
12776 
12777 	kvmclock_reset(vcpu);
12778 
12779 	for_each_possible_cpu(cpu)
12780 		cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12781 
12782 	kvm_x86_call(vcpu_free)(vcpu);
12783 
12784 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12785 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12786 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12787 
12788 	kvm_xen_destroy_vcpu(vcpu);
12789 	kvm_hv_vcpu_uninit(vcpu);
12790 	kvm_pmu_destroy(vcpu);
12791 	kfree(vcpu->arch.mce_banks);
12792 	kfree(vcpu->arch.mci_ctl2_banks);
12793 	kvm_free_lapic(vcpu);
12794 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12795 	kvm_mmu_destroy(vcpu);
12796 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12797 	free_page((unsigned long)vcpu->arch.pio_data);
12798 	kvfree(vcpu->arch.cpuid_entries);
12799 }
12800 
kvm_xstate_reset(struct kvm_vcpu * vcpu,bool init_event)12801 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
12802 {
12803 	struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12804 	u64 xfeatures_mask;
12805 	bool fpu_in_use;
12806 	int i;
12807 
12808 	/*
12809 	 * Guest FPU state is zero allocated and so doesn't need to be manually
12810 	 * cleared on RESET, i.e. during vCPU creation.
12811 	 */
12812 	if (!init_event || !fpstate)
12813 		return;
12814 
12815 	/*
12816 	 * On INIT, only select XSTATE components are zeroed, most components
12817 	 * are unchanged.  Currently, the only components that are zeroed and
12818 	 * supported by KVM are MPX and CET related.
12819 	 */
12820 	xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
12821 			 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
12822 			  XFEATURE_MASK_CET_ALL);
12823 	if (!xfeatures_mask)
12824 		return;
12825 
12826 	BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
12827 
12828 	/*
12829 	 * Unload guest FPU state (if necessary) before zeroing XSTATE fields
12830 	 * as the kernel can only modify the state when its resident in memory,
12831 	 * i.e. when it's not loaded into hardware.
12832 	 *
12833 	 * WARN if the vCPU's desire to run, i.e. whether or not its in KVM_RUN,
12834 	 * doesn't match the loaded/in-use state of the FPU, as KVM_RUN is the
12835 	 * only path that can trigger INIT emulation _and_ loads FPU state, and
12836 	 * KVM_RUN should _always_ load FPU state.
12837 	 */
12838 	WARN_ON_ONCE(vcpu->wants_to_run != fpstate->in_use);
12839 	fpu_in_use = fpstate->in_use;
12840 	if (fpu_in_use)
12841 		kvm_put_guest_fpu(vcpu);
12842 	for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
12843 		fpstate_clear_xstate_component(fpstate, i);
12844 	if (fpu_in_use)
12845 		kvm_load_guest_fpu(vcpu);
12846 }
12847 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12848 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12849 {
12850 	struct kvm_cpuid_entry2 *cpuid_0x1;
12851 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
12852 	unsigned long new_cr0;
12853 
12854 	/*
12855 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12856 	 * to handle side effects.  RESET emulation hits those flows and relies
12857 	 * on emulated/virtualized registers, including those that are loaded
12858 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
12859 	 * to detect improper or missing initialization.
12860 	 */
12861 	WARN_ON_ONCE(!init_event &&
12862 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12863 
12864 	/*
12865 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12866 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
12867 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12868 	 * bits), i.e. virtualization is disabled.
12869 	 */
12870 	if (is_guest_mode(vcpu))
12871 		kvm_leave_nested(vcpu);
12872 
12873 	kvm_lapic_reset(vcpu, init_event);
12874 
12875 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12876 	vcpu->arch.hflags = 0;
12877 
12878 	vcpu->arch.smi_pending = 0;
12879 	vcpu->arch.smi_count = 0;
12880 	atomic_set(&vcpu->arch.nmi_queued, 0);
12881 	vcpu->arch.nmi_pending = 0;
12882 	vcpu->arch.nmi_injected = false;
12883 	kvm_clear_interrupt_queue(vcpu);
12884 	kvm_clear_exception_queue(vcpu);
12885 
12886 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12887 	kvm_update_dr0123(vcpu);
12888 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12889 	vcpu->arch.dr7 = DR7_FIXED_1;
12890 	kvm_update_dr7(vcpu);
12891 
12892 	vcpu->arch.cr2 = 0;
12893 
12894 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12895 	vcpu->arch.apf.msr_en_val = 0;
12896 	vcpu->arch.apf.msr_int_val = 0;
12897 	vcpu->arch.st.msr_val = 0;
12898 
12899 	kvmclock_reset(vcpu);
12900 
12901 	kvm_clear_async_pf_completion_queue(vcpu);
12902 	kvm_async_pf_hash_reset(vcpu);
12903 	vcpu->arch.apf.halted = false;
12904 
12905 	kvm_xstate_reset(vcpu, init_event);
12906 
12907 	if (!init_event) {
12908 		vcpu->arch.smbase = 0x30000;
12909 
12910 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12911 
12912 		vcpu->arch.msr_misc_features_enables = 0;
12913 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12914 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12915 
12916 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12917 		kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
12918 	}
12919 
12920 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12921 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12922 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12923 
12924 	/*
12925 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12926 	 * if no CPUID match is found.  Note, it's impossible to get a match at
12927 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12928 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12929 	 * on RESET.  But, go through the motions in case that's ever remedied.
12930 	 */
12931 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12932 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12933 
12934 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
12935 
12936 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12937 	kvm_rip_write(vcpu, 0xfff0);
12938 
12939 	vcpu->arch.cr3 = 0;
12940 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12941 
12942 	/*
12943 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
12944 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12945 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
12946 	 */
12947 	new_cr0 = X86_CR0_ET;
12948 	if (init_event)
12949 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12950 	else
12951 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12952 
12953 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
12954 	kvm_x86_call(set_cr4)(vcpu, 0);
12955 	kvm_x86_call(set_efer)(vcpu, 0);
12956 	kvm_x86_call(update_exception_bitmap)(vcpu);
12957 
12958 	/*
12959 	 * On the standard CR0/CR4/EFER modification paths, there are several
12960 	 * complex conditions determining whether the MMU has to be reset and/or
12961 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
12962 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12963 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12964 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
12965 	 */
12966 	if (old_cr0 & X86_CR0_PG) {
12967 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12968 		kvm_mmu_reset_context(vcpu);
12969 	}
12970 
12971 	/*
12972 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
12973 	 * APM states the TLBs are untouched by INIT, but it also states that
12974 	 * the TLBs are flushed on "External initialization of the processor."
12975 	 * Flush the guest TLB regardless of vendor, there is no meaningful
12976 	 * benefit in relying on the guest to flush the TLB immediately after
12977 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
12978 	 * performance perspective.
12979 	 */
12980 	if (init_event)
12981 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12982 }
12983 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
12984 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12985 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12986 {
12987 	struct kvm_segment cs;
12988 
12989 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12990 	cs.selector = vector << 8;
12991 	cs.base = vector << 12;
12992 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12993 	kvm_rip_write(vcpu, 0);
12994 }
12995 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
12996 
kvm_arch_enable_virtualization(void)12997 void kvm_arch_enable_virtualization(void)
12998 {
12999 	cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13000 }
13001 
kvm_arch_disable_virtualization(void)13002 void kvm_arch_disable_virtualization(void)
13003 {
13004 	cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13005 }
13006 
kvm_arch_enable_virtualization_cpu(void)13007 int kvm_arch_enable_virtualization_cpu(void)
13008 {
13009 	struct kvm *kvm;
13010 	struct kvm_vcpu *vcpu;
13011 	unsigned long i;
13012 	int ret;
13013 	u64 local_tsc;
13014 	u64 max_tsc = 0;
13015 	bool stable, backwards_tsc = false;
13016 
13017 	kvm_user_return_msr_cpu_online();
13018 
13019 	ret = kvm_x86_check_processor_compatibility();
13020 	if (ret)
13021 		return ret;
13022 
13023 	ret = kvm_x86_call(enable_virtualization_cpu)();
13024 	if (ret != 0)
13025 		return ret;
13026 
13027 	local_tsc = rdtsc();
13028 	stable = !kvm_check_tsc_unstable();
13029 	list_for_each_entry(kvm, &vm_list, vm_list) {
13030 		kvm_for_each_vcpu(i, vcpu, kvm) {
13031 			if (!stable && vcpu->cpu == smp_processor_id())
13032 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
13033 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
13034 				backwards_tsc = true;
13035 				if (vcpu->arch.last_host_tsc > max_tsc)
13036 					max_tsc = vcpu->arch.last_host_tsc;
13037 			}
13038 		}
13039 	}
13040 
13041 	/*
13042 	 * Sometimes, even reliable TSCs go backwards.  This happens on
13043 	 * platforms that reset TSC during suspend or hibernate actions, but
13044 	 * maintain synchronization.  We must compensate.  Fortunately, we can
13045 	 * detect that condition here, which happens early in CPU bringup,
13046 	 * before any KVM threads can be running.  Unfortunately, we can't
13047 	 * bring the TSCs fully up to date with real time, as we aren't yet far
13048 	 * enough into CPU bringup that we know how much real time has actually
13049 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
13050 	 * variables that haven't been updated yet.
13051 	 *
13052 	 * So we simply find the maximum observed TSC above, then record the
13053 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
13054 	 * the adjustment will be applied.  Note that we accumulate
13055 	 * adjustments, in case multiple suspend cycles happen before some VCPU
13056 	 * gets a chance to run again.  In the event that no KVM threads get a
13057 	 * chance to run, we will miss the entire elapsed period, as we'll have
13058 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
13059 	 * loose cycle time.  This isn't too big a deal, since the loss will be
13060 	 * uniform across all VCPUs (not to mention the scenario is extremely
13061 	 * unlikely). It is possible that a second hibernate recovery happens
13062 	 * much faster than a first, causing the observed TSC here to be
13063 	 * smaller; this would require additional padding adjustment, which is
13064 	 * why we set last_host_tsc to the local tsc observed here.
13065 	 *
13066 	 * N.B. - this code below runs only on platforms with reliable TSC,
13067 	 * as that is the only way backwards_tsc is set above.  Also note
13068 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
13069 	 * have the same delta_cyc adjustment applied if backwards_tsc
13070 	 * is detected.  Note further, this adjustment is only done once,
13071 	 * as we reset last_host_tsc on all VCPUs to stop this from being
13072 	 * called multiple times (one for each physical CPU bringup).
13073 	 *
13074 	 * Platforms with unreliable TSCs don't have to deal with this, they
13075 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
13076 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
13077 	 * guarantee that they stay in perfect synchronization.
13078 	 */
13079 	if (backwards_tsc) {
13080 		u64 delta_cyc = max_tsc - local_tsc;
13081 		list_for_each_entry(kvm, &vm_list, vm_list) {
13082 			kvm->arch.backwards_tsc_observed = true;
13083 			kvm_for_each_vcpu(i, vcpu, kvm) {
13084 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
13085 				vcpu->arch.last_host_tsc = local_tsc;
13086 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
13087 			}
13088 
13089 			/*
13090 			 * We have to disable TSC offset matching.. if you were
13091 			 * booting a VM while issuing an S4 host suspend....
13092 			 * you may have some problem.  Solving this issue is
13093 			 * left as an exercise to the reader.
13094 			 */
13095 			kvm->arch.last_tsc_nsec = 0;
13096 			kvm->arch.last_tsc_write = 0;
13097 		}
13098 
13099 	}
13100 	return 0;
13101 }
13102 
kvm_arch_disable_virtualization_cpu(void)13103 void kvm_arch_disable_virtualization_cpu(void)
13104 {
13105 	kvm_x86_call(disable_virtualization_cpu)();
13106 
13107 	/*
13108 	 * Leave the user-return notifiers as-is when disabling virtualization
13109 	 * for reboot, i.e. when disabling via IPI function call, and instead
13110 	 * pin kvm.ko (if it's a module) to defend against use-after-free (in
13111 	 * the *very* unlikely scenario module unload is racing with reboot).
13112 	 * On a forced reboot, tasks aren't frozen before shutdown, and so KVM
13113 	 * could be actively modifying user-return MSR state when the IPI to
13114 	 * disable virtualization arrives.  Handle the extreme edge case here
13115 	 * instead of trying to account for it in the normal flows.
13116 	 */
13117 	if (in_task() || WARN_ON_ONCE(!kvm_rebooting))
13118 		drop_user_return_notifiers();
13119 	else
13120 		__module_get(THIS_MODULE);
13121 }
13122 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)13123 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
13124 {
13125 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
13126 }
13127 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
13128 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)13129 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
13130 {
13131 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
13132 }
13133 
kvm_arch_free_vm(struct kvm * kvm)13134 void kvm_arch_free_vm(struct kvm *kvm)
13135 {
13136 #if IS_ENABLED(CONFIG_HYPERV)
13137 	kfree(kvm->arch.hv_pa_pg);
13138 #endif
13139 	__kvm_arch_free_vm(kvm);
13140 }
13141 
13142 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)13143 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
13144 {
13145 	int ret;
13146 	unsigned long flags;
13147 
13148 	if (!kvm_is_vm_type_supported(type))
13149 		return -EINVAL;
13150 
13151 	kvm->arch.vm_type = type;
13152 	kvm->arch.has_private_mem =
13153 		(type == KVM_X86_SW_PROTECTED_VM);
13154 	/* Decided by the vendor code for other VM types.  */
13155 	kvm->arch.pre_fault_allowed =
13156 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
13157 	kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
13158 
13159 	ret = kvm_page_track_init(kvm);
13160 	if (ret)
13161 		goto out;
13162 
13163 	ret = kvm_mmu_init_vm(kvm);
13164 	if (ret)
13165 		goto out_cleanup_page_track;
13166 
13167 	ret = kvm_x86_call(vm_init)(kvm);
13168 	if (ret)
13169 		goto out_uninit_mmu;
13170 
13171 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
13172 
13173 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
13174 	mutex_init(&kvm->arch.apic_map_lock);
13175 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
13176 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
13177 
13178 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
13179 	pvclock_update_vm_gtod_copy(kvm);
13180 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
13181 
13182 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
13183 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
13184 	kvm->arch.guest_can_read_msr_platform_info = true;
13185 	kvm->arch.enable_pmu = enable_pmu;
13186 
13187 #if IS_ENABLED(CONFIG_HYPERV)
13188 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
13189 	kvm->arch.hv_root_tdp = INVALID_PAGE;
13190 #endif
13191 
13192 	kvm_apicv_init(kvm);
13193 	kvm_hv_init_vm(kvm);
13194 	kvm_xen_init_vm(kvm);
13195 
13196 	if (ignore_msrs && !report_ignored_msrs) {
13197 		pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
13198 			     "a supported configuration.  Lying to the guest about the existence of MSRs\n"
13199 			     "may cause the guest operating system to hang or produce errors.  If a guest\n"
13200 			     "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
13201 	}
13202 
13203 	once_init(&kvm->arch.nx_once);
13204 	return 0;
13205 
13206 out_uninit_mmu:
13207 	kvm_mmu_uninit_vm(kvm);
13208 out_cleanup_page_track:
13209 	kvm_page_track_cleanup(kvm);
13210 out:
13211 	return ret;
13212 }
13213 
13214 /**
13215  * __x86_set_memory_region: Setup KVM internal memory slot
13216  *
13217  * @kvm: the kvm pointer to the VM.
13218  * @id: the slot ID to setup.
13219  * @gpa: the GPA to install the slot (unused when @size == 0).
13220  * @size: the size of the slot. Set to zero to uninstall a slot.
13221  *
13222  * This function helps to setup a KVM internal memory slot.  Specify
13223  * @size > 0 to install a new slot, while @size == 0 to uninstall a
13224  * slot.  The return code can be one of the following:
13225  *
13226  *   HVA:           on success (uninstall will return a bogus HVA)
13227  *   -errno:        on error
13228  *
13229  * The caller should always use IS_ERR() to check the return value
13230  * before use.  Note, the KVM internal memory slots are guaranteed to
13231  * remain valid and unchanged until the VM is destroyed, i.e., the
13232  * GPA->HVA translation will not change.  However, the HVA is a user
13233  * address, i.e. its accessibility is not guaranteed, and must be
13234  * accessed via __copy_{to,from}_user().
13235  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)13236 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
13237 				      u32 size)
13238 {
13239 	int i, r;
13240 	unsigned long hva, old_npages;
13241 	struct kvm_memslots *slots = kvm_memslots(kvm);
13242 	struct kvm_memory_slot *slot;
13243 
13244 	lockdep_assert_held(&kvm->slots_lock);
13245 
13246 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
13247 		return ERR_PTR_USR(-EINVAL);
13248 
13249 	slot = id_to_memslot(slots, id);
13250 	if (size) {
13251 		if (slot && slot->npages)
13252 			return ERR_PTR_USR(-EEXIST);
13253 
13254 		/*
13255 		 * MAP_SHARED to prevent internal slot pages from being moved
13256 		 * by fork()/COW.
13257 		 */
13258 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
13259 			      MAP_SHARED | MAP_ANONYMOUS, 0);
13260 		if (IS_ERR_VALUE(hva))
13261 			return (void __user *)hva;
13262 	} else {
13263 		if (!slot || !slot->npages)
13264 			return NULL;
13265 
13266 		old_npages = slot->npages;
13267 		hva = slot->userspace_addr;
13268 	}
13269 
13270 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
13271 		struct kvm_userspace_memory_region2 m;
13272 
13273 		m.slot = id | (i << 16);
13274 		m.flags = 0;
13275 		m.guest_phys_addr = gpa;
13276 		m.userspace_addr = hva;
13277 		m.memory_size = size;
13278 		r = kvm_set_internal_memslot(kvm, &m);
13279 		if (r < 0)
13280 			return ERR_PTR_USR(r);
13281 	}
13282 
13283 	if (!size)
13284 		vm_munmap(hva, old_npages * PAGE_SIZE);
13285 
13286 	return (void __user *)hva;
13287 }
13288 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
13289 
kvm_arch_pre_destroy_vm(struct kvm * kvm)13290 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
13291 {
13292 	/*
13293 	 * Stop all background workers and kthreads before destroying vCPUs, as
13294 	 * iterating over vCPUs in a different task while vCPUs are being freed
13295 	 * is unsafe, i.e. will lead to use-after-free.  The PIT also needs to
13296 	 * be stopped before IRQ routing is freed.
13297 	 */
13298 #ifdef CONFIG_KVM_IOAPIC
13299 	kvm_free_pit(kvm);
13300 #endif
13301 
13302 	kvm_mmu_pre_destroy_vm(kvm);
13303 	static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
13304 }
13305 
kvm_arch_destroy_vm(struct kvm * kvm)13306 void kvm_arch_destroy_vm(struct kvm *kvm)
13307 {
13308 	if (current->mm == kvm->mm) {
13309 		/*
13310 		 * Free memory regions allocated on behalf of userspace,
13311 		 * unless the memory map has changed due to process exit
13312 		 * or fd copying.
13313 		 */
13314 		mutex_lock(&kvm->slots_lock);
13315 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
13316 					0, 0);
13317 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
13318 					0, 0);
13319 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
13320 		mutex_unlock(&kvm->slots_lock);
13321 	}
13322 	kvm_destroy_vcpus(kvm);
13323 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
13324 #ifdef CONFIG_KVM_IOAPIC
13325 	kvm_pic_destroy(kvm);
13326 	kvm_ioapic_destroy(kvm);
13327 #endif
13328 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
13329 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13330 	kvm_mmu_uninit_vm(kvm);
13331 	kvm_page_track_cleanup(kvm);
13332 	kvm_xen_destroy_vm(kvm);
13333 	kvm_hv_destroy_vm(kvm);
13334 	kvm_x86_call(vm_destroy)(kvm);
13335 }
13336 
memslot_rmap_free(struct kvm_memory_slot * slot)13337 static void memslot_rmap_free(struct kvm_memory_slot *slot)
13338 {
13339 	int i;
13340 
13341 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13342 		vfree(slot->arch.rmap[i]);
13343 		slot->arch.rmap[i] = NULL;
13344 	}
13345 }
13346 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)13347 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
13348 {
13349 	int i;
13350 
13351 	memslot_rmap_free(slot);
13352 
13353 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13354 		vfree(slot->arch.lpage_info[i - 1]);
13355 		slot->arch.lpage_info[i - 1] = NULL;
13356 	}
13357 
13358 	kvm_page_track_free_memslot(slot);
13359 }
13360 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)13361 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
13362 {
13363 	const int sz = sizeof(*slot->arch.rmap[0]);
13364 	int i;
13365 
13366 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13367 		int level = i + 1;
13368 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13369 
13370 		if (slot->arch.rmap[i])
13371 			continue;
13372 
13373 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13374 		if (!slot->arch.rmap[i]) {
13375 			memslot_rmap_free(slot);
13376 			return -ENOMEM;
13377 		}
13378 	}
13379 
13380 	return 0;
13381 }
13382 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13383 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13384 				      struct kvm_memory_slot *slot)
13385 {
13386 	unsigned long npages = slot->npages;
13387 	int i, r;
13388 
13389 	/*
13390 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
13391 	 * old arrays will be freed by kvm_set_memory_region() if installing
13392 	 * the new memslot is successful.
13393 	 */
13394 	memset(&slot->arch, 0, sizeof(slot->arch));
13395 
13396 	if (kvm_memslots_have_rmaps(kvm)) {
13397 		r = memslot_rmap_alloc(slot, npages);
13398 		if (r)
13399 			return r;
13400 	}
13401 
13402 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13403 		struct kvm_lpage_info *linfo;
13404 		unsigned long ugfn;
13405 		int lpages;
13406 		int level = i + 1;
13407 
13408 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13409 
13410 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13411 		if (!linfo)
13412 			goto out_free;
13413 
13414 		slot->arch.lpage_info[i - 1] = linfo;
13415 
13416 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13417 			linfo[0].disallow_lpage = 1;
13418 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13419 			linfo[lpages - 1].disallow_lpage = 1;
13420 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
13421 		/*
13422 		 * If the gfn and userspace address are not aligned wrt each
13423 		 * other, disable large page support for this slot.
13424 		 */
13425 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13426 			unsigned long j;
13427 
13428 			for (j = 0; j < lpages; ++j)
13429 				linfo[j].disallow_lpage = 1;
13430 		}
13431 	}
13432 
13433 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13434 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13435 #endif
13436 
13437 	if (kvm_page_track_create_memslot(kvm, slot, npages))
13438 		goto out_free;
13439 
13440 	return 0;
13441 
13442 out_free:
13443 	memslot_rmap_free(slot);
13444 
13445 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13446 		vfree(slot->arch.lpage_info[i - 1]);
13447 		slot->arch.lpage_info[i - 1] = NULL;
13448 	}
13449 	return -ENOMEM;
13450 }
13451 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13452 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13453 {
13454 	struct kvm_vcpu *vcpu;
13455 	unsigned long i;
13456 
13457 	/*
13458 	 * memslots->generation has been incremented.
13459 	 * mmio generation may have reached its maximum value.
13460 	 */
13461 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13462 
13463 	/* Force re-initialization of steal_time cache */
13464 	kvm_for_each_vcpu(i, vcpu, kvm)
13465 		kvm_vcpu_kick(vcpu);
13466 }
13467 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13468 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13469 				   const struct kvm_memory_slot *old,
13470 				   struct kvm_memory_slot *new,
13471 				   enum kvm_mr_change change)
13472 {
13473 	/*
13474 	 * KVM doesn't support moving memslots when there are external page
13475 	 * trackers attached to the VM, i.e. if KVMGT is in use.
13476 	 */
13477 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13478 		return -EINVAL;
13479 
13480 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13481 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13482 			return -EINVAL;
13483 
13484 		if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13485 			return -EINVAL;
13486 
13487 		return kvm_alloc_memslot_metadata(kvm, new);
13488 	}
13489 
13490 	if (change == KVM_MR_FLAGS_ONLY)
13491 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
13492 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13493 		return -EIO;
13494 
13495 	return 0;
13496 }
13497 
13498 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13499 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13500 {
13501 	int nr_slots;
13502 
13503 	if (!kvm->arch.cpu_dirty_log_size)
13504 		return;
13505 
13506 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13507 	if ((enable && nr_slots == 1) || !nr_slots)
13508 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13509 }
13510 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13511 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13512 				     struct kvm_memory_slot *old,
13513 				     const struct kvm_memory_slot *new,
13514 				     enum kvm_mr_change change)
13515 {
13516 	u32 old_flags = old ? old->flags : 0;
13517 	u32 new_flags = new ? new->flags : 0;
13518 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13519 
13520 	/*
13521 	 * Update CPU dirty logging if dirty logging is being toggled.  This
13522 	 * applies to all operations.
13523 	 */
13524 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13525 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13526 
13527 	/*
13528 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
13529 	 * made writable) or CREATE/MOVE/DELETE of a slot.
13530 	 *
13531 	 * For a memslot with dirty logging disabled:
13532 	 * CREATE:      No dirty mappings will already exist.
13533 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13534 	 *		kvm_arch_flush_shadow_memslot()
13535 	 *
13536 	 * For a memslot with dirty logging enabled:
13537 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
13538 	 *		and no dirty bits to clear.
13539 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13540 	 *		kvm_arch_flush_shadow_memslot().
13541 	 */
13542 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13543 		return;
13544 
13545 	/*
13546 	 * READONLY and non-flags changes were filtered out above, and the only
13547 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13548 	 * logging isn't being toggled on or off.
13549 	 */
13550 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13551 		return;
13552 
13553 	if (!log_dirty_pages) {
13554 		/*
13555 		 * Recover huge page mappings in the slot now that dirty logging
13556 		 * is disabled, i.e. now that KVM does not have to track guest
13557 		 * writes at 4KiB granularity.
13558 		 *
13559 		 * Dirty logging might be disabled by userspace if an ongoing VM
13560 		 * live migration is cancelled and the VM must continue running
13561 		 * on the source.
13562 		 */
13563 		kvm_mmu_recover_huge_pages(kvm, new);
13564 	} else {
13565 		/*
13566 		 * Initially-all-set does not require write protecting any page,
13567 		 * because they're all assumed to be dirty.
13568 		 */
13569 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13570 			return;
13571 
13572 		if (READ_ONCE(eager_page_split))
13573 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13574 
13575 		if (kvm->arch.cpu_dirty_log_size) {
13576 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13577 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13578 		} else {
13579 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13580 		}
13581 
13582 		/*
13583 		 * Unconditionally flush the TLBs after enabling dirty logging.
13584 		 * A flush is almost always going to be necessary (see below),
13585 		 * and unconditionally flushing allows the helpers to omit
13586 		 * the subtly complex checks when removing write access.
13587 		 *
13588 		 * Do the flush outside of mmu_lock to reduce the amount of
13589 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
13590 		 * safe as KVM only needs to guarantee the slot is fully
13591 		 * write-protected before returning to userspace, i.e. before
13592 		 * userspace can consume the dirty status.
13593 		 *
13594 		 * Flushing outside of mmu_lock requires KVM to be careful when
13595 		 * making decisions based on writable status of an SPTE, e.g. a
13596 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13597 		 *
13598 		 * Specifically, KVM also write-protects guest page tables to
13599 		 * monitor changes when using shadow paging, and must guarantee
13600 		 * no CPUs can write to those page before mmu_lock is dropped.
13601 		 * Because CPUs may have stale TLB entries at this point, a
13602 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13603 		 *
13604 		 * KVM also allows making SPTES writable outside of mmu_lock,
13605 		 * e.g. to allow dirty logging without taking mmu_lock.
13606 		 *
13607 		 * To handle these scenarios, KVM uses a separate software-only
13608 		 * bit (MMU-writable) to track if a SPTE is !writable due to
13609 		 * a guest page table being write-protected (KVM clears the
13610 		 * MMU-writable flag when write-protecting for shadow paging).
13611 		 *
13612 		 * The use of MMU-writable is also the primary motivation for
13613 		 * the unconditional flush.  Because KVM must guarantee that a
13614 		 * CPU doesn't contain stale, writable TLB entries for a
13615 		 * !MMU-writable SPTE, KVM must flush if it encounters any
13616 		 * MMU-writable SPTE regardless of whether the actual hardware
13617 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
13618 		 * to flush, while unconditionally flushing allows the "remove
13619 		 * write access" helpers to ignore MMU-writable entirely.
13620 		 *
13621 		 * See is_writable_pte() for more details (the case involving
13622 		 * access-tracked SPTEs is particularly relevant).
13623 		 */
13624 		kvm_flush_remote_tlbs_memslot(kvm, new);
13625 	}
13626 }
13627 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13628 void kvm_arch_commit_memory_region(struct kvm *kvm,
13629 				struct kvm_memory_slot *old,
13630 				const struct kvm_memory_slot *new,
13631 				enum kvm_mr_change change)
13632 {
13633 	if (change == KVM_MR_DELETE)
13634 		kvm_page_track_delete_slot(kvm, old);
13635 
13636 	if (!kvm->arch.n_requested_mmu_pages &&
13637 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13638 		unsigned long nr_mmu_pages;
13639 
13640 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13641 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13642 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13643 	}
13644 
13645 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
13646 
13647 	/* Free the arrays associated with the old memslot. */
13648 	if (change == KVM_MR_MOVE)
13649 		kvm_arch_free_memslot(kvm, old);
13650 }
13651 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13652 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13653 {
13654 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13655 
13656 	if (vcpu->arch.guest_state_protected)
13657 		return true;
13658 
13659 	return kvm_x86_call(get_cpl)(vcpu) == 0;
13660 }
13661 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13662 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13663 {
13664 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13665 
13666 	if (vcpu->arch.guest_state_protected)
13667 		return 0;
13668 
13669 	return kvm_rip_read(vcpu);
13670 }
13671 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13672 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13673 {
13674 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13675 }
13676 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13677 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13678 {
13679 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
13680 }
13681 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13682 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13683 {
13684 	/* Can't read the RIP when guest state is protected, just return 0 */
13685 	if (vcpu->arch.guest_state_protected)
13686 		return 0;
13687 
13688 	if (is_64_bit_mode(vcpu))
13689 		return kvm_rip_read(vcpu);
13690 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13691 		     kvm_rip_read(vcpu));
13692 }
13693 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_linear_rip);
13694 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13695 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13696 {
13697 	return kvm_get_linear_rip(vcpu) == linear_rip;
13698 }
13699 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_linear_rip);
13700 
kvm_get_rflags(struct kvm_vcpu * vcpu)13701 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13702 {
13703 	unsigned long rflags;
13704 
13705 	rflags = kvm_x86_call(get_rflags)(vcpu);
13706 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13707 		rflags &= ~X86_EFLAGS_TF;
13708 	return rflags;
13709 }
13710 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_rflags);
13711 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13712 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13713 {
13714 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13715 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13716 		rflags |= X86_EFLAGS_TF;
13717 	kvm_x86_call(set_rflags)(vcpu, rflags);
13718 }
13719 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13720 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13721 {
13722 	__kvm_set_rflags(vcpu, rflags);
13723 	kvm_make_request(KVM_REQ_EVENT, vcpu);
13724 }
13725 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_rflags);
13726 
kvm_async_pf_hash_fn(gfn_t gfn)13727 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13728 {
13729 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13730 
13731 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13732 }
13733 
kvm_async_pf_next_probe(u32 key)13734 static inline u32 kvm_async_pf_next_probe(u32 key)
13735 {
13736 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13737 }
13738 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13739 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13740 {
13741 	u32 key = kvm_async_pf_hash_fn(gfn);
13742 
13743 	while (vcpu->arch.apf.gfns[key] != ~0)
13744 		key = kvm_async_pf_next_probe(key);
13745 
13746 	vcpu->arch.apf.gfns[key] = gfn;
13747 }
13748 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13749 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13750 {
13751 	int i;
13752 	u32 key = kvm_async_pf_hash_fn(gfn);
13753 
13754 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
13755 		     (vcpu->arch.apf.gfns[key] != gfn &&
13756 		      vcpu->arch.apf.gfns[key] != ~0); i++)
13757 		key = kvm_async_pf_next_probe(key);
13758 
13759 	return key;
13760 }
13761 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13762 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13763 {
13764 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13765 }
13766 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13767 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13768 {
13769 	u32 i, j, k;
13770 
13771 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13772 
13773 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13774 		return;
13775 
13776 	while (true) {
13777 		vcpu->arch.apf.gfns[i] = ~0;
13778 		do {
13779 			j = kvm_async_pf_next_probe(j);
13780 			if (vcpu->arch.apf.gfns[j] == ~0)
13781 				return;
13782 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13783 			/*
13784 			 * k lies cyclically in ]i,j]
13785 			 * |    i.k.j |
13786 			 * |....j i.k.| or  |.k..j i...|
13787 			 */
13788 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13789 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13790 		i = j;
13791 	}
13792 }
13793 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13794 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13795 {
13796 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13797 
13798 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13799 				      sizeof(reason));
13800 }
13801 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13802 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13803 {
13804 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13805 
13806 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13807 					     &token, offset, sizeof(token));
13808 }
13809 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13810 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13811 {
13812 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13813 	u32 val;
13814 
13815 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13816 					 &val, offset, sizeof(val)))
13817 		return false;
13818 
13819 	return !val;
13820 }
13821 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13822 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13823 {
13824 
13825 	if (!kvm_pv_async_pf_enabled(vcpu))
13826 		return false;
13827 
13828 	if (!vcpu->arch.apf.send_always &&
13829 	    (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13830 		return false;
13831 
13832 	if (is_guest_mode(vcpu)) {
13833 		/*
13834 		 * L1 needs to opt into the special #PF vmexits that are
13835 		 * used to deliver async page faults.
13836 		 */
13837 		return vcpu->arch.apf.delivery_as_pf_vmexit;
13838 	} else {
13839 		/*
13840 		 * Play it safe in case the guest temporarily disables paging.
13841 		 * The real mode IDT in particular is unlikely to have a #PF
13842 		 * exception setup.
13843 		 */
13844 		return is_paging(vcpu);
13845 	}
13846 }
13847 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13848 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13849 {
13850 	if (unlikely(!lapic_in_kernel(vcpu) ||
13851 		     kvm_event_needs_reinjection(vcpu) ||
13852 		     kvm_is_exception_pending(vcpu)))
13853 		return false;
13854 
13855 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13856 		return false;
13857 
13858 	/*
13859 	 * If interrupts are off we cannot even use an artificial
13860 	 * halt state.
13861 	 */
13862 	return kvm_arch_interrupt_allowed(vcpu);
13863 }
13864 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13865 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13866 				     struct kvm_async_pf *work)
13867 {
13868 	struct x86_exception fault;
13869 
13870 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13871 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13872 
13873 	if (kvm_can_deliver_async_pf(vcpu) &&
13874 	    !apf_put_user_notpresent(vcpu)) {
13875 		fault.vector = PF_VECTOR;
13876 		fault.error_code_valid = true;
13877 		fault.error_code = 0;
13878 		fault.nested_page_fault = false;
13879 		fault.address = work->arch.token;
13880 		fault.async_page_fault = true;
13881 		kvm_inject_page_fault(vcpu, &fault);
13882 		return true;
13883 	} else {
13884 		/*
13885 		 * It is not possible to deliver a paravirtualized asynchronous
13886 		 * page fault, but putting the guest in an artificial halt state
13887 		 * can be beneficial nevertheless: if an interrupt arrives, we
13888 		 * can deliver it timely and perhaps the guest will schedule
13889 		 * another process.  When the instruction that triggered a page
13890 		 * fault is retried, hopefully the page will be ready in the host.
13891 		 */
13892 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13893 		return false;
13894 	}
13895 }
13896 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13897 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13898 				 struct kvm_async_pf *work)
13899 {
13900 	struct kvm_lapic_irq irq = {
13901 		.delivery_mode = APIC_DM_FIXED,
13902 		.vector = vcpu->arch.apf.vec
13903 	};
13904 
13905 	if (work->wakeup_all)
13906 		work->arch.token = ~0; /* broadcast wakeup */
13907 	else
13908 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13909 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13910 
13911 	if ((work->wakeup_all || work->notpresent_injected) &&
13912 	    kvm_pv_async_pf_enabled(vcpu) &&
13913 	    !apf_put_user_ready(vcpu, work->arch.token)) {
13914 		WRITE_ONCE(vcpu->arch.apf.pageready_pending, true);
13915 		kvm_apic_set_irq(vcpu, &irq, NULL);
13916 	}
13917 
13918 	vcpu->arch.apf.halted = false;
13919 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13920 }
13921 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13922 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13923 {
13924 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
13925 
13926 	/* Pairs with smp_store_mb() in kvm_set_msr_common(). */
13927 	smp_mb__after_atomic();
13928 
13929 	if (!READ_ONCE(vcpu->arch.apf.pageready_pending))
13930 		kvm_vcpu_kick(vcpu);
13931 }
13932 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13933 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13934 {
13935 	if (!kvm_pv_async_pf_enabled(vcpu))
13936 		return true;
13937 	else
13938 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13939 }
13940 
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13941 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13942 {
13943 	/*
13944 	 * Non-coherent DMA assignment and de-assignment may affect whether or
13945 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13946 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
13947 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
13948 	 * with the correct "ignore guest PAT" setting are created.
13949 	 *
13950 	 * If KVM always honors guest PAT, however, there is nothing to do.
13951 	 */
13952 	if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
13953 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13954 }
13955 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13956 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13957 {
13958 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13959 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13960 }
13961 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13962 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13963 {
13964 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13965 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13966 }
13967 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13968 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13969 {
13970 	return atomic_read(&kvm->arch.noncoherent_dma_count);
13971 }
13972 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
13973 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13974 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13975 {
13976 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13977 }
13978 
13979 #ifdef CONFIG_KVM_GUEST_MEMFD
13980 /*
13981  * KVM doesn't yet support initializing guest_memfd memory as shared for VMs
13982  * with private memory (the private vs. shared tracking needs to be moved into
13983  * guest_memfd).
13984  */
kvm_arch_supports_gmem_init_shared(struct kvm * kvm)13985 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
13986 {
13987 	return !kvm_arch_has_private_mem(kvm);
13988 }
13989 
13990 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13991 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13992 {
13993 	return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13994 }
13995 #endif
13996 
13997 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13998 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13999 {
14000 	kvm_x86_call(gmem_invalidate)(start, end);
14001 }
14002 #endif
14003 #endif
14004 
kvm_spec_ctrl_test_value(u64 value)14005 int kvm_spec_ctrl_test_value(u64 value)
14006 {
14007 	/*
14008 	 * test that setting IA32_SPEC_CTRL to given value
14009 	 * is allowed by the host processor
14010 	 */
14011 
14012 	u64 saved_value;
14013 	unsigned long flags;
14014 	int ret = 0;
14015 
14016 	local_irq_save(flags);
14017 
14018 	if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
14019 		ret = 1;
14020 	else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
14021 		ret = 1;
14022 	else
14023 		wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
14024 
14025 	local_irq_restore(flags);
14026 
14027 	return ret;
14028 }
14029 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spec_ctrl_test_value);
14030 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)14031 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
14032 {
14033 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
14034 	struct x86_exception fault;
14035 	u64 access = error_code &
14036 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
14037 
14038 	if (!(error_code & PFERR_PRESENT_MASK) ||
14039 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
14040 		/*
14041 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
14042 		 * tables probably do not match the TLB.  Just proceed
14043 		 * with the error code that the processor gave.
14044 		 */
14045 		fault.vector = PF_VECTOR;
14046 		fault.error_code_valid = true;
14047 		fault.error_code = error_code;
14048 		fault.nested_page_fault = false;
14049 		fault.address = gva;
14050 		fault.async_page_fault = false;
14051 	}
14052 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
14053 }
14054 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
14055 
14056 /*
14057  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
14058  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
14059  * indicates whether exit to userspace is needed.
14060  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)14061 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
14062 			      struct x86_exception *e)
14063 {
14064 	if (r == X86EMUL_PROPAGATE_FAULT) {
14065 		if (KVM_BUG_ON(!e, vcpu->kvm))
14066 			return -EIO;
14067 
14068 		kvm_inject_emulated_page_fault(vcpu, e);
14069 		return 1;
14070 	}
14071 
14072 	/*
14073 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
14074 	 * while handling a VMX instruction KVM could've handled the request
14075 	 * correctly by exiting to userspace and performing I/O but there
14076 	 * doesn't seem to be a real use-case behind such requests, just return
14077 	 * KVM_EXIT_INTERNAL_ERROR for now.
14078 	 */
14079 	kvm_prepare_emulation_failure_exit(vcpu);
14080 
14081 	return 0;
14082 }
14083 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
14084 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)14085 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
14086 {
14087 	bool pcid_enabled;
14088 	struct x86_exception e;
14089 	struct {
14090 		u64 pcid;
14091 		u64 gla;
14092 	} operand;
14093 	int r;
14094 
14095 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
14096 	if (r != X86EMUL_CONTINUE)
14097 		return kvm_handle_memory_failure(vcpu, r, &e);
14098 
14099 	if (operand.pcid >> 12 != 0) {
14100 		kvm_inject_gp(vcpu, 0);
14101 		return 1;
14102 	}
14103 
14104 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
14105 
14106 	switch (type) {
14107 	case INVPCID_TYPE_INDIV_ADDR:
14108 		/*
14109 		 * LAM doesn't apply to addresses that are inputs to TLB
14110 		 * invalidation.
14111 		 */
14112 		if ((!pcid_enabled && (operand.pcid != 0)) ||
14113 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
14114 			kvm_inject_gp(vcpu, 0);
14115 			return 1;
14116 		}
14117 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
14118 		return kvm_skip_emulated_instruction(vcpu);
14119 
14120 	case INVPCID_TYPE_SINGLE_CTXT:
14121 		if (!pcid_enabled && (operand.pcid != 0)) {
14122 			kvm_inject_gp(vcpu, 0);
14123 			return 1;
14124 		}
14125 
14126 		kvm_invalidate_pcid(vcpu, operand.pcid);
14127 		return kvm_skip_emulated_instruction(vcpu);
14128 
14129 	case INVPCID_TYPE_ALL_NON_GLOBAL:
14130 		/*
14131 		 * Currently, KVM doesn't mark global entries in the shadow
14132 		 * page tables, so a non-global flush just degenerates to a
14133 		 * global flush. If needed, we could optimize this later by
14134 		 * keeping track of global entries in shadow page tables.
14135 		 */
14136 
14137 		fallthrough;
14138 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
14139 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
14140 		return kvm_skip_emulated_instruction(vcpu);
14141 
14142 	default:
14143 		kvm_inject_gp(vcpu, 0);
14144 		return 1;
14145 	}
14146 }
14147 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
14148 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)14149 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
14150 {
14151 	struct kvm_run *run = vcpu->run;
14152 	struct kvm_mmio_fragment *frag;
14153 	unsigned int len;
14154 
14155 	BUG_ON(!vcpu->mmio_needed);
14156 
14157 	/* Complete previous fragment */
14158 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
14159 	len = min(8u, frag->len);
14160 	if (!vcpu->mmio_is_write)
14161 		memcpy(frag->data, run->mmio.data, len);
14162 
14163 	if (frag->len <= 8) {
14164 		/* Switch to the next fragment. */
14165 		frag++;
14166 		vcpu->mmio_cur_fragment++;
14167 	} else {
14168 		/* Go forward to the next mmio piece. */
14169 		frag->data += len;
14170 		frag->gpa += len;
14171 		frag->len -= len;
14172 	}
14173 
14174 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
14175 		vcpu->mmio_needed = 0;
14176 
14177 		// VMG change, at this point, we're always done
14178 		// RIP has already been advanced
14179 		return 1;
14180 	}
14181 
14182 	// More MMIO is needed
14183 	run->mmio.phys_addr = frag->gpa;
14184 	run->mmio.len = min(8u, frag->len);
14185 	run->mmio.is_write = vcpu->mmio_is_write;
14186 	if (run->mmio.is_write)
14187 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
14188 	run->exit_reason = KVM_EXIT_MMIO;
14189 
14190 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14191 
14192 	return 0;
14193 }
14194 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14195 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14196 			  void *data)
14197 {
14198 	int handled;
14199 	struct kvm_mmio_fragment *frag;
14200 
14201 	if (!data)
14202 		return -EINVAL;
14203 
14204 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14205 	if (handled == bytes)
14206 		return 1;
14207 
14208 	bytes -= handled;
14209 	gpa += handled;
14210 	data += handled;
14211 
14212 	/*TODO: Check if need to increment number of frags */
14213 	frag = vcpu->mmio_fragments;
14214 	vcpu->mmio_nr_fragments = 1;
14215 	frag->len = bytes;
14216 	frag->gpa = gpa;
14217 	frag->data = data;
14218 
14219 	vcpu->mmio_needed = 1;
14220 	vcpu->mmio_cur_fragment = 0;
14221 
14222 	vcpu->run->mmio.phys_addr = gpa;
14223 	vcpu->run->mmio.len = min(8u, frag->len);
14224 	vcpu->run->mmio.is_write = 1;
14225 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
14226 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
14227 
14228 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14229 
14230 	return 0;
14231 }
14232 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_write);
14233 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14234 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14235 			 void *data)
14236 {
14237 	int handled;
14238 	struct kvm_mmio_fragment *frag;
14239 
14240 	if (!data)
14241 		return -EINVAL;
14242 
14243 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14244 	if (handled == bytes)
14245 		return 1;
14246 
14247 	bytes -= handled;
14248 	gpa += handled;
14249 	data += handled;
14250 
14251 	/*TODO: Check if need to increment number of frags */
14252 	frag = vcpu->mmio_fragments;
14253 	vcpu->mmio_nr_fragments = 1;
14254 	frag->len = bytes;
14255 	frag->gpa = gpa;
14256 	frag->data = data;
14257 
14258 	vcpu->mmio_needed = 1;
14259 	vcpu->mmio_cur_fragment = 0;
14260 
14261 	vcpu->run->mmio.phys_addr = gpa;
14262 	vcpu->run->mmio.len = min(8u, frag->len);
14263 	vcpu->run->mmio.is_write = 0;
14264 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
14265 
14266 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14267 
14268 	return 0;
14269 }
14270 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_read);
14271 
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)14272 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
14273 {
14274 	vcpu->arch.sev_pio_count -= count;
14275 	vcpu->arch.sev_pio_data += count * size;
14276 }
14277 
14278 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14279 			   unsigned int port);
14280 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)14281 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
14282 {
14283 	int size = vcpu->arch.pio.size;
14284 	int port = vcpu->arch.pio.port;
14285 
14286 	vcpu->arch.pio.count = 0;
14287 	if (vcpu->arch.sev_pio_count)
14288 		return kvm_sev_es_outs(vcpu, size, port);
14289 	return 1;
14290 }
14291 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14292 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14293 			   unsigned int port)
14294 {
14295 	for (;;) {
14296 		unsigned int count =
14297 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14298 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14299 
14300 		/* memcpy done already by emulator_pio_out.  */
14301 		advance_sev_es_emulated_pio(vcpu, count, size);
14302 		if (!ret)
14303 			break;
14304 
14305 		/* Emulation done by the kernel.  */
14306 		if (!vcpu->arch.sev_pio_count)
14307 			return 1;
14308 	}
14309 
14310 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14311 	return 0;
14312 }
14313 
14314 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14315 			  unsigned int port);
14316 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14317 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14318 {
14319 	unsigned count = vcpu->arch.pio.count;
14320 	int size = vcpu->arch.pio.size;
14321 	int port = vcpu->arch.pio.port;
14322 
14323 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14324 	advance_sev_es_emulated_pio(vcpu, count, size);
14325 	if (vcpu->arch.sev_pio_count)
14326 		return kvm_sev_es_ins(vcpu, size, port);
14327 	return 1;
14328 }
14329 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14330 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14331 			  unsigned int port)
14332 {
14333 	for (;;) {
14334 		unsigned int count =
14335 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14336 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14337 			break;
14338 
14339 		/* Emulation done by the kernel.  */
14340 		advance_sev_es_emulated_pio(vcpu, count, size);
14341 		if (!vcpu->arch.sev_pio_count)
14342 			return 1;
14343 	}
14344 
14345 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14346 	return 0;
14347 }
14348 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14349 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14350 			 unsigned int port, void *data,  unsigned int count,
14351 			 int in)
14352 {
14353 	vcpu->arch.sev_pio_data = data;
14354 	vcpu->arch.sev_pio_count = count;
14355 	return in ? kvm_sev_es_ins(vcpu, size, port)
14356 		  : kvm_sev_es_outs(vcpu, size, port);
14357 }
14358 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
14359 
14360 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14361 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14362 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14363 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14364 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14365 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14366 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14367 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14368 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14369 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14370 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14371 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14372 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14373 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14374 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14375 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14376 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14377 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14378 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14379 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14380 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14381 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14382 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14383 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14384 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14385 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14386 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14387 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14388 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14389 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14390 
kvm_x86_init(void)14391 static int __init kvm_x86_init(void)
14392 {
14393 	kvm_init_xstate_sizes();
14394 
14395 	kvm_mmu_x86_module_init();
14396 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14397 	return 0;
14398 }
14399 module_init(kvm_x86_init);
14400 
kvm_x86_exit(void)14401 static void __exit kvm_x86_exit(void)
14402 {
14403 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14404 }
14405 module_exit(kvm_x86_exit);
14406