xref: /linux/arch/x86/kvm/x86.c (revision c924c5e9b8c65b3a479a90e5e37d74cc8cd9fe0a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/kvm_host.h>
21 #include "irq.h"
22 #include "ioapic.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
29 #include "x86.h"
30 #include "cpuid.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33 #include "lapic.h"
34 #include "xen.h"
35 #include "smm.h"
36 
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
40 #include <linux/fs.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/entry-kvm.h>
63 #include <linux/suspend.h>
64 #include <linux/smp.h>
65 
66 #include <trace/events/ipi.h>
67 #include <trace/events/kvm.h>
68 
69 #include <asm/debugreg.h>
70 #include <asm/msr.h>
71 #include <asm/desc.h>
72 #include <asm/mce.h>
73 #include <asm/pkru.h>
74 #include <linux/kernel_stat.h>
75 #include <asm/fpu/api.h>
76 #include <asm/fpu/xcr.h>
77 #include <asm/fpu/xstate.h>
78 #include <asm/pvclock.h>
79 #include <asm/div64.h>
80 #include <asm/irq_remapping.h>
81 #include <asm/mshyperv.h>
82 #include <asm/hypervisor.h>
83 #include <asm/tlbflush.h>
84 #include <asm/intel_pt.h>
85 #include <asm/emulate_prefix.h>
86 #include <asm/sgx.h>
87 #include <clocksource/hyperv_timer.h>
88 
89 #define CREATE_TRACE_POINTS
90 #include "trace.h"
91 
92 #define MAX_IO_MSRS 256
93 #define KVM_MAX_MCE_BANKS 32
94 
95 /*
96  * Note, kvm_caps fields should *never* have default values, all fields must be
97  * recomputed from scratch during vendor module load, e.g. to account for a
98  * vendor module being reloaded with different module parameters.
99  */
100 struct kvm_caps kvm_caps __read_mostly;
101 EXPORT_SYMBOL_GPL(kvm_caps);
102 
103 struct kvm_host_values kvm_host __read_mostly;
104 EXPORT_SYMBOL_GPL(kvm_host);
105 
106 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
107 
108 #define emul_to_vcpu(ctxt) \
109 	((struct kvm_vcpu *)(ctxt)->vcpu)
110 
111 /* EFER defaults:
112  * - enable syscall per default because its emulated by KVM
113  * - enable LME and LMA per default on 64 bit KVM
114  */
115 #ifdef CONFIG_X86_64
116 static
117 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
118 #else
119 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
120 #endif
121 
122 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
123 
124 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
125 
126 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
127                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
128 
129 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
130 static void process_nmi(struct kvm_vcpu *vcpu);
131 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
132 static void store_regs(struct kvm_vcpu *vcpu);
133 static int sync_regs(struct kvm_vcpu *vcpu);
134 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
135 
136 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
137 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
138 
139 static DEFINE_MUTEX(vendor_module_lock);
140 struct kvm_x86_ops kvm_x86_ops __read_mostly;
141 
142 #define KVM_X86_OP(func)					     \
143 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
144 				*(((struct kvm_x86_ops *)0)->func));
145 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
146 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
147 #include <asm/kvm-x86-ops.h>
148 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
149 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
150 
151 static bool __read_mostly ignore_msrs = 0;
152 module_param(ignore_msrs, bool, 0644);
153 
154 bool __read_mostly report_ignored_msrs = true;
155 module_param(report_ignored_msrs, bool, 0644);
156 EXPORT_SYMBOL_GPL(report_ignored_msrs);
157 
158 unsigned int min_timer_period_us = 200;
159 module_param(min_timer_period_us, uint, 0644);
160 
161 static bool __read_mostly kvmclock_periodic_sync = true;
162 module_param(kvmclock_periodic_sync, bool, 0444);
163 
164 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
165 static u32 __read_mostly tsc_tolerance_ppm = 250;
166 module_param(tsc_tolerance_ppm, uint, 0644);
167 
168 static bool __read_mostly vector_hashing = true;
169 module_param(vector_hashing, bool, 0444);
170 
171 bool __read_mostly enable_vmware_backdoor = false;
172 module_param(enable_vmware_backdoor, bool, 0444);
173 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
174 
175 /*
176  * Flags to manipulate forced emulation behavior (any non-zero value will
177  * enable forced emulation).
178  */
179 #define KVM_FEP_CLEAR_RFLAGS_RF	BIT(1)
180 static int __read_mostly force_emulation_prefix;
181 module_param(force_emulation_prefix, int, 0644);
182 
183 int __read_mostly pi_inject_timer = -1;
184 module_param(pi_inject_timer, bint, 0644);
185 
186 /* Enable/disable PMU virtualization */
187 bool __read_mostly enable_pmu = true;
188 EXPORT_SYMBOL_GPL(enable_pmu);
189 module_param(enable_pmu, bool, 0444);
190 
191 bool __read_mostly eager_page_split = true;
192 module_param(eager_page_split, bool, 0644);
193 
194 /* Enable/disable SMT_RSB bug mitigation */
195 static bool __read_mostly mitigate_smt_rsb;
196 module_param(mitigate_smt_rsb, bool, 0444);
197 
198 /*
199  * Restoring the host value for MSRs that are only consumed when running in
200  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
201  * returns to userspace, i.e. the kernel can run with the guest's value.
202  */
203 #define KVM_MAX_NR_USER_RETURN_MSRS 16
204 
205 struct kvm_user_return_msrs {
206 	struct user_return_notifier urn;
207 	bool registered;
208 	struct kvm_user_return_msr_values {
209 		u64 host;
210 		u64 curr;
211 	} values[KVM_MAX_NR_USER_RETURN_MSRS];
212 };
213 
214 u32 __read_mostly kvm_nr_uret_msrs;
215 EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
216 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
217 static struct kvm_user_return_msrs __percpu *user_return_msrs;
218 
219 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
220 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
221 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
222 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
223 
224 bool __read_mostly allow_smaller_maxphyaddr = 0;
225 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
226 
227 bool __read_mostly enable_apicv = true;
228 EXPORT_SYMBOL_GPL(enable_apicv);
229 
230 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
231 	KVM_GENERIC_VM_STATS(),
232 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
233 	STATS_DESC_COUNTER(VM, mmu_pte_write),
234 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
235 	STATS_DESC_COUNTER(VM, mmu_flooded),
236 	STATS_DESC_COUNTER(VM, mmu_recycled),
237 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
238 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
239 	STATS_DESC_ICOUNTER(VM, pages_4k),
240 	STATS_DESC_ICOUNTER(VM, pages_2m),
241 	STATS_DESC_ICOUNTER(VM, pages_1g),
242 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
243 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
244 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
245 };
246 
247 const struct kvm_stats_header kvm_vm_stats_header = {
248 	.name_size = KVM_STATS_NAME_SIZE,
249 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
250 	.id_offset = sizeof(struct kvm_stats_header),
251 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
252 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
253 		       sizeof(kvm_vm_stats_desc),
254 };
255 
256 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
257 	KVM_GENERIC_VCPU_STATS(),
258 	STATS_DESC_COUNTER(VCPU, pf_taken),
259 	STATS_DESC_COUNTER(VCPU, pf_fixed),
260 	STATS_DESC_COUNTER(VCPU, pf_emulate),
261 	STATS_DESC_COUNTER(VCPU, pf_spurious),
262 	STATS_DESC_COUNTER(VCPU, pf_fast),
263 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
264 	STATS_DESC_COUNTER(VCPU, pf_guest),
265 	STATS_DESC_COUNTER(VCPU, tlb_flush),
266 	STATS_DESC_COUNTER(VCPU, invlpg),
267 	STATS_DESC_COUNTER(VCPU, exits),
268 	STATS_DESC_COUNTER(VCPU, io_exits),
269 	STATS_DESC_COUNTER(VCPU, mmio_exits),
270 	STATS_DESC_COUNTER(VCPU, signal_exits),
271 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
272 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
273 	STATS_DESC_COUNTER(VCPU, l1d_flush),
274 	STATS_DESC_COUNTER(VCPU, halt_exits),
275 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
276 	STATS_DESC_COUNTER(VCPU, irq_exits),
277 	STATS_DESC_COUNTER(VCPU, host_state_reload),
278 	STATS_DESC_COUNTER(VCPU, fpu_reload),
279 	STATS_DESC_COUNTER(VCPU, insn_emulation),
280 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
281 	STATS_DESC_COUNTER(VCPU, hypercalls),
282 	STATS_DESC_COUNTER(VCPU, irq_injections),
283 	STATS_DESC_COUNTER(VCPU, nmi_injections),
284 	STATS_DESC_COUNTER(VCPU, req_event),
285 	STATS_DESC_COUNTER(VCPU, nested_run),
286 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
287 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
288 	STATS_DESC_COUNTER(VCPU, preemption_reported),
289 	STATS_DESC_COUNTER(VCPU, preemption_other),
290 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
291 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
292 };
293 
294 const struct kvm_stats_header kvm_vcpu_stats_header = {
295 	.name_size = KVM_STATS_NAME_SIZE,
296 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
297 	.id_offset = sizeof(struct kvm_stats_header),
298 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
299 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
300 		       sizeof(kvm_vcpu_stats_desc),
301 };
302 
303 static struct kmem_cache *x86_emulator_cache;
304 
305 /*
306  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
307  * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
308  * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.  msrs_to_save holds MSRs that
309  * require host support, i.e. should be probed via RDMSR.  emulated_msrs holds
310  * MSRs that KVM emulates without strictly requiring host support.
311  * msr_based_features holds MSRs that enumerate features, i.e. are effectively
312  * CPUID leafs.  Note, msr_based_features isn't mutually exclusive with
313  * msrs_to_save and emulated_msrs.
314  */
315 
316 static const u32 msrs_to_save_base[] = {
317 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
318 	MSR_STAR,
319 #ifdef CONFIG_X86_64
320 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
321 #endif
322 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
323 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
324 	MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
325 	MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
326 	MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
327 	MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
328 	MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
329 	MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
330 	MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
331 	MSR_IA32_UMWAIT_CONTROL,
332 
333 	MSR_IA32_XFD, MSR_IA32_XFD_ERR,
334 };
335 
336 static const u32 msrs_to_save_pmu[] = {
337 	MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
338 	MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
339 	MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
340 	MSR_CORE_PERF_GLOBAL_CTRL,
341 	MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
342 
343 	/* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
344 	MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
345 	MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
346 	MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
347 	MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
348 	MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
349 	MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
350 	MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
351 	MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
352 
353 	MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
354 	MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
355 
356 	/* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
357 	MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
358 	MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
359 	MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
360 	MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
361 
362 	MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
363 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
364 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
365 };
366 
367 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
368 			ARRAY_SIZE(msrs_to_save_pmu)];
369 static unsigned num_msrs_to_save;
370 
371 static const u32 emulated_msrs_all[] = {
372 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
373 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
374 
375 #ifdef CONFIG_KVM_HYPERV
376 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
377 	HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
378 	HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
379 	HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
380 	HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
381 	HV_X64_MSR_RESET,
382 	HV_X64_MSR_VP_INDEX,
383 	HV_X64_MSR_VP_RUNTIME,
384 	HV_X64_MSR_SCONTROL,
385 	HV_X64_MSR_STIMER0_CONFIG,
386 	HV_X64_MSR_VP_ASSIST_PAGE,
387 	HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
388 	HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
389 	HV_X64_MSR_SYNDBG_OPTIONS,
390 	HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
391 	HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
392 	HV_X64_MSR_SYNDBG_PENDING_BUFFER,
393 #endif
394 
395 	MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
396 	MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
397 
398 	MSR_IA32_TSC_ADJUST,
399 	MSR_IA32_TSC_DEADLINE,
400 	MSR_IA32_ARCH_CAPABILITIES,
401 	MSR_IA32_PERF_CAPABILITIES,
402 	MSR_IA32_MISC_ENABLE,
403 	MSR_IA32_MCG_STATUS,
404 	MSR_IA32_MCG_CTL,
405 	MSR_IA32_MCG_EXT_CTL,
406 	MSR_IA32_SMBASE,
407 	MSR_SMI_COUNT,
408 	MSR_PLATFORM_INFO,
409 	MSR_MISC_FEATURES_ENABLES,
410 	MSR_AMD64_VIRT_SPEC_CTRL,
411 	MSR_AMD64_TSC_RATIO,
412 	MSR_IA32_POWER_CTL,
413 	MSR_IA32_UCODE_REV,
414 
415 	/*
416 	 * KVM always supports the "true" VMX control MSRs, even if the host
417 	 * does not.  The VMX MSRs as a whole are considered "emulated" as KVM
418 	 * doesn't strictly require them to exist in the host (ignoring that
419 	 * KVM would refuse to load in the first place if the core set of MSRs
420 	 * aren't supported).
421 	 */
422 	MSR_IA32_VMX_BASIC,
423 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
424 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
425 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
426 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
427 	MSR_IA32_VMX_MISC,
428 	MSR_IA32_VMX_CR0_FIXED0,
429 	MSR_IA32_VMX_CR4_FIXED0,
430 	MSR_IA32_VMX_VMCS_ENUM,
431 	MSR_IA32_VMX_PROCBASED_CTLS2,
432 	MSR_IA32_VMX_EPT_VPID_CAP,
433 	MSR_IA32_VMX_VMFUNC,
434 
435 	MSR_K7_HWCR,
436 	MSR_KVM_POLL_CONTROL,
437 };
438 
439 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
440 static unsigned num_emulated_msrs;
441 
442 /*
443  * List of MSRs that control the existence of MSR-based features, i.e. MSRs
444  * that are effectively CPUID leafs.  VMX MSRs are also included in the set of
445  * feature MSRs, but are handled separately to allow expedited lookups.
446  */
447 static const u32 msr_based_features_all_except_vmx[] = {
448 	MSR_AMD64_DE_CFG,
449 	MSR_IA32_UCODE_REV,
450 	MSR_IA32_ARCH_CAPABILITIES,
451 	MSR_IA32_PERF_CAPABILITIES,
452 	MSR_PLATFORM_INFO,
453 };
454 
455 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
456 			      (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
457 static unsigned int num_msr_based_features;
458 
459 /*
460  * All feature MSRs except uCode revID, which tracks the currently loaded uCode
461  * patch, are immutable once the vCPU model is defined.
462  */
kvm_is_immutable_feature_msr(u32 msr)463 static bool kvm_is_immutable_feature_msr(u32 msr)
464 {
465 	int i;
466 
467 	if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
468 		return true;
469 
470 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
471 		if (msr == msr_based_features_all_except_vmx[i])
472 			return msr != MSR_IA32_UCODE_REV;
473 	}
474 
475 	return false;
476 }
477 
kvm_is_advertised_msr(u32 msr_index)478 static bool kvm_is_advertised_msr(u32 msr_index)
479 {
480 	unsigned int i;
481 
482 	for (i = 0; i < num_msrs_to_save; i++) {
483 		if (msrs_to_save[i] == msr_index)
484 			return true;
485 	}
486 
487 	for (i = 0; i < num_emulated_msrs; i++) {
488 		if (emulated_msrs[i] == msr_index)
489 			return true;
490 	}
491 
492 	return false;
493 }
494 
495 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
496 			    bool host_initiated);
497 
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)498 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
499 					     u64 *data, bool host_initiated,
500 					     enum kvm_msr_access rw,
501 					     msr_access_t msr_access_fn)
502 {
503 	const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
504 	int ret;
505 
506 	BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
507 
508 	/*
509 	 * Zero the data on read failures to avoid leaking stack data to the
510 	 * guest and/or userspace, e.g. if the failure is ignored below.
511 	 */
512 	ret = msr_access_fn(vcpu, msr, data, host_initiated);
513 	if (ret && rw == MSR_TYPE_R)
514 		*data = 0;
515 
516 	if (ret != KVM_MSR_RET_UNSUPPORTED)
517 		return ret;
518 
519 	/*
520 	 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
521 	 * advertises to userspace, even if an MSR isn't fully supported.
522 	 * Simply check that @data is '0', which covers both the write '0' case
523 	 * and all reads (in which case @data is zeroed on failure; see above).
524 	 */
525 	if (host_initiated && !*data && kvm_is_advertised_msr(msr))
526 		return 0;
527 
528 	if (!ignore_msrs) {
529 		kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
530 				      op, msr, *data);
531 		return ret;
532 	}
533 
534 	if (report_ignored_msrs)
535 		kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
536 
537 	return 0;
538 }
539 
kvm_alloc_emulator_cache(void)540 static struct kmem_cache *kvm_alloc_emulator_cache(void)
541 {
542 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
543 	unsigned int size = sizeof(struct x86_emulate_ctxt);
544 
545 	return kmem_cache_create_usercopy("x86_emulator", size,
546 					  __alignof__(struct x86_emulate_ctxt),
547 					  SLAB_ACCOUNT, useroffset,
548 					  size - useroffset, NULL);
549 }
550 
551 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
552 
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)553 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
554 {
555 	int i;
556 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
557 		vcpu->arch.apf.gfns[i] = ~0;
558 }
559 
kvm_on_user_return(struct user_return_notifier * urn)560 static void kvm_on_user_return(struct user_return_notifier *urn)
561 {
562 	unsigned slot;
563 	struct kvm_user_return_msrs *msrs
564 		= container_of(urn, struct kvm_user_return_msrs, urn);
565 	struct kvm_user_return_msr_values *values;
566 	unsigned long flags;
567 
568 	/*
569 	 * Disabling irqs at this point since the following code could be
570 	 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
571 	 */
572 	local_irq_save(flags);
573 	if (msrs->registered) {
574 		msrs->registered = false;
575 		user_return_notifier_unregister(urn);
576 	}
577 	local_irq_restore(flags);
578 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
579 		values = &msrs->values[slot];
580 		if (values->host != values->curr) {
581 			wrmsrl(kvm_uret_msrs_list[slot], values->host);
582 			values->curr = values->host;
583 		}
584 	}
585 }
586 
kvm_probe_user_return_msr(u32 msr)587 static int kvm_probe_user_return_msr(u32 msr)
588 {
589 	u64 val;
590 	int ret;
591 
592 	preempt_disable();
593 	ret = rdmsrl_safe(msr, &val);
594 	if (ret)
595 		goto out;
596 	ret = wrmsrl_safe(msr, val);
597 out:
598 	preempt_enable();
599 	return ret;
600 }
601 
kvm_add_user_return_msr(u32 msr)602 int kvm_add_user_return_msr(u32 msr)
603 {
604 	BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
605 
606 	if (kvm_probe_user_return_msr(msr))
607 		return -1;
608 
609 	kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
610 	return kvm_nr_uret_msrs++;
611 }
612 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
613 
kvm_find_user_return_msr(u32 msr)614 int kvm_find_user_return_msr(u32 msr)
615 {
616 	int i;
617 
618 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
619 		if (kvm_uret_msrs_list[i] == msr)
620 			return i;
621 	}
622 	return -1;
623 }
624 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
625 
kvm_user_return_msr_cpu_online(void)626 static void kvm_user_return_msr_cpu_online(void)
627 {
628 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
629 	u64 value;
630 	int i;
631 
632 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
633 		rdmsrl_safe(kvm_uret_msrs_list[i], &value);
634 		msrs->values[i].host = value;
635 		msrs->values[i].curr = value;
636 	}
637 }
638 
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)639 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
640 {
641 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
642 	int err;
643 
644 	value = (value & mask) | (msrs->values[slot].host & ~mask);
645 	if (value == msrs->values[slot].curr)
646 		return 0;
647 	err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
648 	if (err)
649 		return 1;
650 
651 	msrs->values[slot].curr = value;
652 	if (!msrs->registered) {
653 		msrs->urn.on_user_return = kvm_on_user_return;
654 		user_return_notifier_register(&msrs->urn);
655 		msrs->registered = true;
656 	}
657 	return 0;
658 }
659 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
660 
drop_user_return_notifiers(void)661 static void drop_user_return_notifiers(void)
662 {
663 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
664 
665 	if (msrs->registered)
666 		kvm_on_user_return(&msrs->urn);
667 }
668 
669 /*
670  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
671  *
672  * Hardware virtualization extension instructions may fault if a reboot turns
673  * off virtualization while processes are running.  Usually after catching the
674  * fault we just panic; during reboot instead the instruction is ignored.
675  */
kvm_spurious_fault(void)676 noinstr void kvm_spurious_fault(void)
677 {
678 	/* Fault while not rebooting.  We want the trace. */
679 	BUG_ON(!kvm_rebooting);
680 }
681 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
682 
683 #define EXCPT_BENIGN		0
684 #define EXCPT_CONTRIBUTORY	1
685 #define EXCPT_PF		2
686 
exception_class(int vector)687 static int exception_class(int vector)
688 {
689 	switch (vector) {
690 	case PF_VECTOR:
691 		return EXCPT_PF;
692 	case DE_VECTOR:
693 	case TS_VECTOR:
694 	case NP_VECTOR:
695 	case SS_VECTOR:
696 	case GP_VECTOR:
697 		return EXCPT_CONTRIBUTORY;
698 	default:
699 		break;
700 	}
701 	return EXCPT_BENIGN;
702 }
703 
704 #define EXCPT_FAULT		0
705 #define EXCPT_TRAP		1
706 #define EXCPT_ABORT		2
707 #define EXCPT_INTERRUPT		3
708 #define EXCPT_DB		4
709 
exception_type(int vector)710 static int exception_type(int vector)
711 {
712 	unsigned int mask;
713 
714 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
715 		return EXCPT_INTERRUPT;
716 
717 	mask = 1 << vector;
718 
719 	/*
720 	 * #DBs can be trap-like or fault-like, the caller must check other CPU
721 	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
722 	 */
723 	if (mask & (1 << DB_VECTOR))
724 		return EXCPT_DB;
725 
726 	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
727 		return EXCPT_TRAP;
728 
729 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
730 		return EXCPT_ABORT;
731 
732 	/* Reserved exceptions will result in fault */
733 	return EXCPT_FAULT;
734 }
735 
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)736 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
737 				   struct kvm_queued_exception *ex)
738 {
739 	if (!ex->has_payload)
740 		return;
741 
742 	switch (ex->vector) {
743 	case DB_VECTOR:
744 		/*
745 		 * "Certain debug exceptions may clear bit 0-3.  The
746 		 * remaining contents of the DR6 register are never
747 		 * cleared by the processor".
748 		 */
749 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
750 		/*
751 		 * In order to reflect the #DB exception payload in guest
752 		 * dr6, three components need to be considered: active low
753 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
754 		 * DR6_BS and DR6_BT)
755 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
756 		 * In the target guest dr6:
757 		 * FIXED_1 bits should always be set.
758 		 * Active low bits should be cleared if 1-setting in payload.
759 		 * Active high bits should be set if 1-setting in payload.
760 		 *
761 		 * Note, the payload is compatible with the pending debug
762 		 * exceptions/exit qualification under VMX, that active_low bits
763 		 * are active high in payload.
764 		 * So they need to be flipped for DR6.
765 		 */
766 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
767 		vcpu->arch.dr6 |= ex->payload;
768 		vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
769 
770 		/*
771 		 * The #DB payload is defined as compatible with the 'pending
772 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
773 		 * defined in the 'pending debug exceptions' field (enabled
774 		 * breakpoint), it is reserved and must be zero in DR6.
775 		 */
776 		vcpu->arch.dr6 &= ~BIT(12);
777 		break;
778 	case PF_VECTOR:
779 		vcpu->arch.cr2 = ex->payload;
780 		break;
781 	}
782 
783 	ex->has_payload = false;
784 	ex->payload = 0;
785 }
786 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
787 
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)788 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
789 				       bool has_error_code, u32 error_code,
790 				       bool has_payload, unsigned long payload)
791 {
792 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
793 
794 	ex->vector = vector;
795 	ex->injected = false;
796 	ex->pending = true;
797 	ex->has_error_code = has_error_code;
798 	ex->error_code = error_code;
799 	ex->has_payload = has_payload;
800 	ex->payload = payload;
801 }
802 
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)803 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
804 				   bool has_error, u32 error_code,
805 				   bool has_payload, unsigned long payload)
806 {
807 	u32 prev_nr;
808 	int class1, class2;
809 
810 	kvm_make_request(KVM_REQ_EVENT, vcpu);
811 
812 	/*
813 	 * If the exception is destined for L2, morph it to a VM-Exit if L1
814 	 * wants to intercept the exception.
815 	 */
816 	if (is_guest_mode(vcpu) &&
817 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
818 		kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
819 					   has_payload, payload);
820 		return;
821 	}
822 
823 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
824 	queue:
825 		vcpu->arch.exception.pending = true;
826 		vcpu->arch.exception.injected = false;
827 
828 		vcpu->arch.exception.has_error_code = has_error;
829 		vcpu->arch.exception.vector = nr;
830 		vcpu->arch.exception.error_code = error_code;
831 		vcpu->arch.exception.has_payload = has_payload;
832 		vcpu->arch.exception.payload = payload;
833 		if (!is_guest_mode(vcpu))
834 			kvm_deliver_exception_payload(vcpu,
835 						      &vcpu->arch.exception);
836 		return;
837 	}
838 
839 	/* to check exception */
840 	prev_nr = vcpu->arch.exception.vector;
841 	if (prev_nr == DF_VECTOR) {
842 		/* triple fault -> shutdown */
843 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
844 		return;
845 	}
846 	class1 = exception_class(prev_nr);
847 	class2 = exception_class(nr);
848 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
849 	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
850 		/*
851 		 * Synthesize #DF.  Clear the previously injected or pending
852 		 * exception so as not to incorrectly trigger shutdown.
853 		 */
854 		vcpu->arch.exception.injected = false;
855 		vcpu->arch.exception.pending = false;
856 
857 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
858 	} else {
859 		/* replace previous exception with a new one in a hope
860 		   that instruction re-execution will regenerate lost
861 		   exception */
862 		goto queue;
863 	}
864 }
865 
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)866 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
867 {
868 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
869 }
870 EXPORT_SYMBOL_GPL(kvm_queue_exception);
871 
872 
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)873 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
874 			   unsigned long payload)
875 {
876 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
877 }
878 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
879 
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)880 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
881 				    u32 error_code, unsigned long payload)
882 {
883 	kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
884 }
885 
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)886 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
887 			   bool has_error_code, u32 error_code)
888 {
889 
890 	/*
891 	 * On VM-Entry, an exception can be pending if and only if event
892 	 * injection was blocked by nested_run_pending.  In that case, however,
893 	 * vcpu_enter_guest() requests an immediate exit, and the guest
894 	 * shouldn't proceed far enough to need reinjection.
895 	 */
896 	WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
897 
898 	/*
899 	 * Do not check for interception when injecting an event for L2, as the
900 	 * exception was checked for intercept when it was original queued, and
901 	 * re-checking is incorrect if _L1_ injected the exception, in which
902 	 * case it's exempt from interception.
903 	 */
904 	kvm_make_request(KVM_REQ_EVENT, vcpu);
905 
906 	vcpu->arch.exception.injected = true;
907 	vcpu->arch.exception.has_error_code = has_error_code;
908 	vcpu->arch.exception.vector = nr;
909 	vcpu->arch.exception.error_code = error_code;
910 	vcpu->arch.exception.has_payload = false;
911 	vcpu->arch.exception.payload = 0;
912 }
913 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
914 
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)915 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
916 {
917 	if (err)
918 		kvm_inject_gp(vcpu, 0);
919 	else
920 		return kvm_skip_emulated_instruction(vcpu);
921 
922 	return 1;
923 }
924 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
925 
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)926 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
927 {
928 	if (err) {
929 		kvm_inject_gp(vcpu, 0);
930 		return 1;
931 	}
932 
933 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
934 				       EMULTYPE_COMPLETE_USER_EXIT);
935 }
936 
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)937 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
938 {
939 	++vcpu->stat.pf_guest;
940 
941 	/*
942 	 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
943 	 * whether or not L1 wants to intercept "regular" #PF.
944 	 */
945 	if (is_guest_mode(vcpu) && fault->async_page_fault)
946 		kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
947 					   true, fault->error_code,
948 					   true, fault->address);
949 	else
950 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
951 					fault->address);
952 }
953 
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)954 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
955 				    struct x86_exception *fault)
956 {
957 	struct kvm_mmu *fault_mmu;
958 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
959 
960 	fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
961 					       vcpu->arch.walk_mmu;
962 
963 	/*
964 	 * Invalidate the TLB entry for the faulting address, if it exists,
965 	 * else the access will fault indefinitely (and to emulate hardware).
966 	 */
967 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
968 	    !(fault->error_code & PFERR_RSVD_MASK))
969 		kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
970 					KVM_MMU_ROOT_CURRENT);
971 
972 	fault_mmu->inject_page_fault(vcpu, fault);
973 }
974 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
975 
kvm_inject_nmi(struct kvm_vcpu * vcpu)976 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
977 {
978 	atomic_inc(&vcpu->arch.nmi_queued);
979 	kvm_make_request(KVM_REQ_NMI, vcpu);
980 }
981 
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)982 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
983 {
984 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
985 }
986 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
987 
988 /*
989  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
990  * a #GP and return false.
991  */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)992 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
993 {
994 	if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
995 		return true;
996 	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
997 	return false;
998 }
999 
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1000 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1001 {
1002 	if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1003 		return true;
1004 
1005 	kvm_queue_exception(vcpu, UD_VECTOR);
1006 	return false;
1007 }
1008 EXPORT_SYMBOL_GPL(kvm_require_dr);
1009 
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1010 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1011 {
1012 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1013 }
1014 
1015 /*
1016  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
1017  */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1018 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1019 {
1020 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1021 	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1022 	gpa_t real_gpa;
1023 	int i;
1024 	int ret;
1025 	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1026 
1027 	/*
1028 	 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1029 	 * to an L1 GPA.
1030 	 */
1031 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1032 				     PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1033 	if (real_gpa == INVALID_GPA)
1034 		return 0;
1035 
1036 	/* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1037 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1038 				       cr3 & GENMASK(11, 5), sizeof(pdpte));
1039 	if (ret < 0)
1040 		return 0;
1041 
1042 	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1043 		if ((pdpte[i] & PT_PRESENT_MASK) &&
1044 		    (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1045 			return 0;
1046 		}
1047 	}
1048 
1049 	/*
1050 	 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1051 	 * Shadow page roots need to be reconstructed instead.
1052 	 */
1053 	if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1054 		kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1055 
1056 	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1057 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1058 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1059 	vcpu->arch.pdptrs_from_userspace = false;
1060 
1061 	return 1;
1062 }
1063 EXPORT_SYMBOL_GPL(load_pdptrs);
1064 
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1065 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1066 {
1067 #ifdef CONFIG_X86_64
1068 	if (cr0 & 0xffffffff00000000UL)
1069 		return false;
1070 #endif
1071 
1072 	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1073 		return false;
1074 
1075 	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1076 		return false;
1077 
1078 	return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1079 }
1080 
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1081 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1082 {
1083 	/*
1084 	 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1085 	 * indirect shadow MMUs.  If paging is disabled, no updates are needed
1086 	 * as there are no permission bits to emulate.  If TDP is enabled, the
1087 	 * MMU's metadata needs to be updated, e.g. so that emulating guest
1088 	 * translations does the right thing, but there's no need to unload the
1089 	 * root as CR0.WP doesn't affect SPTEs.
1090 	 */
1091 	if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1092 		if (!(cr0 & X86_CR0_PG))
1093 			return;
1094 
1095 		if (tdp_enabled) {
1096 			kvm_init_mmu(vcpu);
1097 			return;
1098 		}
1099 	}
1100 
1101 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1102 		kvm_clear_async_pf_completion_queue(vcpu);
1103 		kvm_async_pf_hash_reset(vcpu);
1104 
1105 		/*
1106 		 * Clearing CR0.PG is defined to flush the TLB from the guest's
1107 		 * perspective.
1108 		 */
1109 		if (!(cr0 & X86_CR0_PG))
1110 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1111 	}
1112 
1113 	if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1114 		kvm_mmu_reset_context(vcpu);
1115 }
1116 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
1117 
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1118 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1119 {
1120 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
1121 
1122 	if (!kvm_is_valid_cr0(vcpu, cr0))
1123 		return 1;
1124 
1125 	cr0 |= X86_CR0_ET;
1126 
1127 	/* Write to CR0 reserved bits are ignored, even on Intel. */
1128 	cr0 &= ~CR0_RESERVED_BITS;
1129 
1130 #ifdef CONFIG_X86_64
1131 	if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1132 	    (cr0 & X86_CR0_PG)) {
1133 		int cs_db, cs_l;
1134 
1135 		if (!is_pae(vcpu))
1136 			return 1;
1137 		kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1138 		if (cs_l)
1139 			return 1;
1140 	}
1141 #endif
1142 	if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1143 	    is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1144 	    !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1145 		return 1;
1146 
1147 	if (!(cr0 & X86_CR0_PG) &&
1148 	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1149 		return 1;
1150 
1151 	kvm_x86_call(set_cr0)(vcpu, cr0);
1152 
1153 	kvm_post_set_cr0(vcpu, old_cr0, cr0);
1154 
1155 	return 0;
1156 }
1157 EXPORT_SYMBOL_GPL(kvm_set_cr0);
1158 
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1159 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1160 {
1161 	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1162 }
1163 EXPORT_SYMBOL_GPL(kvm_lmsw);
1164 
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)1165 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1166 {
1167 	if (vcpu->arch.guest_state_protected)
1168 		return;
1169 
1170 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1171 
1172 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1173 			xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1174 
1175 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1176 		    vcpu->arch.ia32_xss != kvm_host.xss)
1177 			wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1178 	}
1179 
1180 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1181 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
1182 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1183 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1184 		wrpkru(vcpu->arch.pkru);
1185 }
1186 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
1187 
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1188 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1189 {
1190 	if (vcpu->arch.guest_state_protected)
1191 		return;
1192 
1193 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1194 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1195 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1196 		vcpu->arch.pkru = rdpkru();
1197 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1198 			wrpkru(vcpu->arch.host_pkru);
1199 	}
1200 
1201 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1202 
1203 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1204 			xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1205 
1206 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1207 		    vcpu->arch.ia32_xss != kvm_host.xss)
1208 			wrmsrl(MSR_IA32_XSS, kvm_host.xss);
1209 	}
1210 
1211 }
1212 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1213 
1214 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1215 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1216 {
1217 	return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1218 }
1219 #endif
1220 
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1221 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1222 {
1223 	u64 xcr0 = xcr;
1224 	u64 old_xcr0 = vcpu->arch.xcr0;
1225 	u64 valid_bits;
1226 
1227 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
1228 	if (index != XCR_XFEATURE_ENABLED_MASK)
1229 		return 1;
1230 	if (!(xcr0 & XFEATURE_MASK_FP))
1231 		return 1;
1232 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1233 		return 1;
1234 
1235 	/*
1236 	 * Do not allow the guest to set bits that we do not support
1237 	 * saving.  However, xcr0 bit 0 is always set, even if the
1238 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1239 	 */
1240 	valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1241 	if (xcr0 & ~valid_bits)
1242 		return 1;
1243 
1244 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1245 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1246 		return 1;
1247 
1248 	if (xcr0 & XFEATURE_MASK_AVX512) {
1249 		if (!(xcr0 & XFEATURE_MASK_YMM))
1250 			return 1;
1251 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1252 			return 1;
1253 	}
1254 
1255 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
1256 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1257 		return 1;
1258 
1259 	vcpu->arch.xcr0 = xcr0;
1260 
1261 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1262 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
1263 	return 0;
1264 }
1265 
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1266 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1267 {
1268 	/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1269 	if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1270 	    __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1271 		kvm_inject_gp(vcpu, 0);
1272 		return 1;
1273 	}
1274 
1275 	return kvm_skip_emulated_instruction(vcpu);
1276 }
1277 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1278 
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1279 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1280 {
1281 	return __kvm_is_valid_cr4(vcpu, cr4) &&
1282 	       kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1283 }
1284 
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1285 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1286 {
1287 	if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1288 		kvm_mmu_reset_context(vcpu);
1289 
1290 	/*
1291 	 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1292 	 * according to the SDM; however, stale prev_roots could be reused
1293 	 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1294 	 * free them all.  This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1295 	 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1296 	 * so fall through.
1297 	 */
1298 	if (!tdp_enabled &&
1299 	    (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1300 		kvm_mmu_unload(vcpu);
1301 
1302 	/*
1303 	 * The TLB has to be flushed for all PCIDs if any of the following
1304 	 * (architecturally required) changes happen:
1305 	 * - CR4.PCIDE is changed from 1 to 0
1306 	 * - CR4.PGE is toggled
1307 	 *
1308 	 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1309 	 */
1310 	if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1311 	    (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1312 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1313 
1314 	/*
1315 	 * The TLB has to be flushed for the current PCID if any of the
1316 	 * following (architecturally required) changes happen:
1317 	 * - CR4.SMEP is changed from 0 to 1
1318 	 * - CR4.PAE is toggled
1319 	 */
1320 	else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1321 		 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1322 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1323 
1324 }
1325 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1326 
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1327 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1328 {
1329 	unsigned long old_cr4 = kvm_read_cr4(vcpu);
1330 
1331 	if (!kvm_is_valid_cr4(vcpu, cr4))
1332 		return 1;
1333 
1334 	if (is_long_mode(vcpu)) {
1335 		if (!(cr4 & X86_CR4_PAE))
1336 			return 1;
1337 		if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1338 			return 1;
1339 	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1340 		   && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1341 		   && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1342 		return 1;
1343 
1344 	if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1345 		/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1346 		if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1347 			return 1;
1348 	}
1349 
1350 	kvm_x86_call(set_cr4)(vcpu, cr4);
1351 
1352 	kvm_post_set_cr4(vcpu, old_cr4, cr4);
1353 
1354 	return 0;
1355 }
1356 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1357 
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1358 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1359 {
1360 	struct kvm_mmu *mmu = vcpu->arch.mmu;
1361 	unsigned long roots_to_free = 0;
1362 	int i;
1363 
1364 	/*
1365 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1366 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
1367 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
1368 	 * the invalidation, but the guest's TLB entries need to be flushed as
1369 	 * the CPU may have cached entries in its TLB for the target PCID.
1370 	 */
1371 	if (unlikely(tdp_enabled)) {
1372 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1373 		return;
1374 	}
1375 
1376 	/*
1377 	 * If neither the current CR3 nor any of the prev_roots use the given
1378 	 * PCID, then nothing needs to be done here because a resync will
1379 	 * happen anyway before switching to any other CR3.
1380 	 */
1381 	if (kvm_get_active_pcid(vcpu) == pcid) {
1382 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1383 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1384 	}
1385 
1386 	/*
1387 	 * If PCID is disabled, there is no need to free prev_roots even if the
1388 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1389 	 * with PCIDE=0.
1390 	 */
1391 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1392 		return;
1393 
1394 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1395 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1396 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1397 
1398 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1399 }
1400 
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1401 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1402 {
1403 	bool skip_tlb_flush = false;
1404 	unsigned long pcid = 0;
1405 #ifdef CONFIG_X86_64
1406 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1407 		skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1408 		cr3 &= ~X86_CR3_PCID_NOFLUSH;
1409 		pcid = cr3 & X86_CR3_PCID_MASK;
1410 	}
1411 #endif
1412 
1413 	/* PDPTRs are always reloaded for PAE paging. */
1414 	if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1415 		goto handle_tlb_flush;
1416 
1417 	/*
1418 	 * Do not condition the GPA check on long mode, this helper is used to
1419 	 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1420 	 * the current vCPU mode is accurate.
1421 	 */
1422 	if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1423 		return 1;
1424 
1425 	if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1426 		return 1;
1427 
1428 	if (cr3 != kvm_read_cr3(vcpu))
1429 		kvm_mmu_new_pgd(vcpu, cr3);
1430 
1431 	vcpu->arch.cr3 = cr3;
1432 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1433 	/* Do not call post_set_cr3, we do not get here for confidential guests.  */
1434 
1435 handle_tlb_flush:
1436 	/*
1437 	 * A load of CR3 that flushes the TLB flushes only the current PCID,
1438 	 * even if PCID is disabled, in which case PCID=0 is flushed.  It's a
1439 	 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1440 	 * and it's impossible to use a non-zero PCID when PCID is disabled,
1441 	 * i.e. only PCID=0 can be relevant.
1442 	 */
1443 	if (!skip_tlb_flush)
1444 		kvm_invalidate_pcid(vcpu, pcid);
1445 
1446 	return 0;
1447 }
1448 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1449 
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1450 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1451 {
1452 	if (cr8 & CR8_RESERVED_BITS)
1453 		return 1;
1454 	if (lapic_in_kernel(vcpu))
1455 		kvm_lapic_set_tpr(vcpu, cr8);
1456 	else
1457 		vcpu->arch.cr8 = cr8;
1458 	return 0;
1459 }
1460 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1461 
kvm_get_cr8(struct kvm_vcpu * vcpu)1462 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1463 {
1464 	if (lapic_in_kernel(vcpu))
1465 		return kvm_lapic_get_cr8(vcpu);
1466 	else
1467 		return vcpu->arch.cr8;
1468 }
1469 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1470 
kvm_update_dr0123(struct kvm_vcpu * vcpu)1471 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1472 {
1473 	int i;
1474 
1475 	if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1476 		for (i = 0; i < KVM_NR_DB_REGS; i++)
1477 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1478 	}
1479 }
1480 
kvm_update_dr7(struct kvm_vcpu * vcpu)1481 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1482 {
1483 	unsigned long dr7;
1484 
1485 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1486 		dr7 = vcpu->arch.guest_debug_dr7;
1487 	else
1488 		dr7 = vcpu->arch.dr7;
1489 	kvm_x86_call(set_dr7)(vcpu, dr7);
1490 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1491 	if (dr7 & DR7_BP_EN_MASK)
1492 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1493 }
1494 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1495 
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1496 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1497 {
1498 	u64 fixed = DR6_FIXED_1;
1499 
1500 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1501 		fixed |= DR6_RTM;
1502 
1503 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1504 		fixed |= DR6_BUS_LOCK;
1505 	return fixed;
1506 }
1507 
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1508 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1509 {
1510 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1511 
1512 	switch (dr) {
1513 	case 0 ... 3:
1514 		vcpu->arch.db[array_index_nospec(dr, size)] = val;
1515 		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1516 			vcpu->arch.eff_db[dr] = val;
1517 		break;
1518 	case 4:
1519 	case 6:
1520 		if (!kvm_dr6_valid(val))
1521 			return 1; /* #GP */
1522 		vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1523 		break;
1524 	case 5:
1525 	default: /* 7 */
1526 		if (!kvm_dr7_valid(val))
1527 			return 1; /* #GP */
1528 		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1529 		kvm_update_dr7(vcpu);
1530 		break;
1531 	}
1532 
1533 	return 0;
1534 }
1535 EXPORT_SYMBOL_GPL(kvm_set_dr);
1536 
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1537 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1538 {
1539 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1540 
1541 	switch (dr) {
1542 	case 0 ... 3:
1543 		return vcpu->arch.db[array_index_nospec(dr, size)];
1544 	case 4:
1545 	case 6:
1546 		return vcpu->arch.dr6;
1547 	case 5:
1548 	default: /* 7 */
1549 		return vcpu->arch.dr7;
1550 	}
1551 }
1552 EXPORT_SYMBOL_GPL(kvm_get_dr);
1553 
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1554 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1555 {
1556 	u32 ecx = kvm_rcx_read(vcpu);
1557 	u64 data;
1558 
1559 	if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1560 		kvm_inject_gp(vcpu, 0);
1561 		return 1;
1562 	}
1563 
1564 	kvm_rax_write(vcpu, (u32)data);
1565 	kvm_rdx_write(vcpu, data >> 32);
1566 	return kvm_skip_emulated_instruction(vcpu);
1567 }
1568 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1569 
1570 /*
1571  * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1572  * does not yet virtualize. These include:
1573  *   10 - MISC_PACKAGE_CTRLS
1574  *   11 - ENERGY_FILTERING_CTL
1575  *   12 - DOITM
1576  *   18 - FB_CLEAR_CTRL
1577  *   21 - XAPIC_DISABLE_STATUS
1578  *   23 - OVERCLOCKING_STATUS
1579  */
1580 
1581 #define KVM_SUPPORTED_ARCH_CAP \
1582 	(ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1583 	 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1584 	 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1585 	 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1586 	 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1587 	 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO)
1588 
kvm_get_arch_capabilities(void)1589 static u64 kvm_get_arch_capabilities(void)
1590 {
1591 	u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1592 
1593 	/*
1594 	 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1595 	 * the nested hypervisor runs with NX huge pages.  If it is not,
1596 	 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1597 	 * L1 guests, so it need not worry about its own (L2) guests.
1598 	 */
1599 	data |= ARCH_CAP_PSCHANGE_MC_NO;
1600 
1601 	/*
1602 	 * If we're doing cache flushes (either "always" or "cond")
1603 	 * we will do one whenever the guest does a vmlaunch/vmresume.
1604 	 * If an outer hypervisor is doing the cache flush for us
1605 	 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1606 	 * capability to the guest too, and if EPT is disabled we're not
1607 	 * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1608 	 * require a nested hypervisor to do a flush of its own.
1609 	 */
1610 	if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1611 		data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1612 
1613 	if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1614 		data |= ARCH_CAP_RDCL_NO;
1615 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1616 		data |= ARCH_CAP_SSB_NO;
1617 	if (!boot_cpu_has_bug(X86_BUG_MDS))
1618 		data |= ARCH_CAP_MDS_NO;
1619 	if (!boot_cpu_has_bug(X86_BUG_RFDS))
1620 		data |= ARCH_CAP_RFDS_NO;
1621 
1622 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1623 		/*
1624 		 * If RTM=0 because the kernel has disabled TSX, the host might
1625 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1626 		 * and therefore knows that there cannot be TAA) but keep
1627 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1628 		 * and we want to allow migrating those guests to tsx=off hosts.
1629 		 */
1630 		data &= ~ARCH_CAP_TAA_NO;
1631 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1632 		data |= ARCH_CAP_TAA_NO;
1633 	} else {
1634 		/*
1635 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1636 		 * host so the guest can choose between disabling TSX or
1637 		 * using VERW to clear CPU buffers.
1638 		 */
1639 	}
1640 
1641 	if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1642 		data |= ARCH_CAP_GDS_NO;
1643 
1644 	return data;
1645 }
1646 
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1647 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1648 			       bool host_initiated)
1649 {
1650 	WARN_ON_ONCE(!host_initiated);
1651 
1652 	switch (index) {
1653 	case MSR_IA32_ARCH_CAPABILITIES:
1654 		*data = kvm_get_arch_capabilities();
1655 		break;
1656 	case MSR_IA32_PERF_CAPABILITIES:
1657 		*data = kvm_caps.supported_perf_cap;
1658 		break;
1659 	case MSR_PLATFORM_INFO:
1660 		*data = MSR_PLATFORM_INFO_CPUID_FAULT;
1661 		break;
1662 	case MSR_IA32_UCODE_REV:
1663 		rdmsrl_safe(index, data);
1664 		break;
1665 	default:
1666 		return kvm_x86_call(get_feature_msr)(index, data);
1667 	}
1668 	return 0;
1669 }
1670 
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1671 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1672 {
1673 	return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1674 				 kvm_get_feature_msr);
1675 }
1676 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1677 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1678 {
1679 	if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1680 		return false;
1681 
1682 	if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1683 		return false;
1684 
1685 	if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1686 		return false;
1687 
1688 	if (efer & (EFER_LME | EFER_LMA) &&
1689 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1690 		return false;
1691 
1692 	if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1693 		return false;
1694 
1695 	return true;
1696 
1697 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1698 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1699 {
1700 	if (efer & efer_reserved_bits)
1701 		return false;
1702 
1703 	return __kvm_valid_efer(vcpu, efer);
1704 }
1705 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1706 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1707 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1708 {
1709 	u64 old_efer = vcpu->arch.efer;
1710 	u64 efer = msr_info->data;
1711 	int r;
1712 
1713 	if (efer & efer_reserved_bits)
1714 		return 1;
1715 
1716 	if (!msr_info->host_initiated) {
1717 		if (!__kvm_valid_efer(vcpu, efer))
1718 			return 1;
1719 
1720 		if (is_paging(vcpu) &&
1721 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1722 			return 1;
1723 	}
1724 
1725 	efer &= ~EFER_LMA;
1726 	efer |= vcpu->arch.efer & EFER_LMA;
1727 
1728 	r = kvm_x86_call(set_efer)(vcpu, efer);
1729 	if (r) {
1730 		WARN_ON(r > 0);
1731 		return r;
1732 	}
1733 
1734 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1735 		kvm_mmu_reset_context(vcpu);
1736 
1737 	if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1738 	    (efer & EFER_SVME))
1739 		kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1740 
1741 	return 0;
1742 }
1743 
kvm_enable_efer_bits(u64 mask)1744 void kvm_enable_efer_bits(u64 mask)
1745 {
1746        efer_reserved_bits &= ~mask;
1747 }
1748 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1749 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1750 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1751 {
1752 	struct kvm_x86_msr_filter *msr_filter;
1753 	struct msr_bitmap_range *ranges;
1754 	struct kvm *kvm = vcpu->kvm;
1755 	bool allowed;
1756 	int idx;
1757 	u32 i;
1758 
1759 	/* x2APIC MSRs do not support filtering. */
1760 	if (index >= 0x800 && index <= 0x8ff)
1761 		return true;
1762 
1763 	idx = srcu_read_lock(&kvm->srcu);
1764 
1765 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1766 	if (!msr_filter) {
1767 		allowed = true;
1768 		goto out;
1769 	}
1770 
1771 	allowed = msr_filter->default_allow;
1772 	ranges = msr_filter->ranges;
1773 
1774 	for (i = 0; i < msr_filter->count; i++) {
1775 		u32 start = ranges[i].base;
1776 		u32 end = start + ranges[i].nmsrs;
1777 		u32 flags = ranges[i].flags;
1778 		unsigned long *bitmap = ranges[i].bitmap;
1779 
1780 		if ((index >= start) && (index < end) && (flags & type)) {
1781 			allowed = test_bit(index - start, bitmap);
1782 			break;
1783 		}
1784 	}
1785 
1786 out:
1787 	srcu_read_unlock(&kvm->srcu, idx);
1788 
1789 	return allowed;
1790 }
1791 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1792 
1793 /*
1794  * Write @data into the MSR specified by @index.  Select MSR specific fault
1795  * checks are bypassed if @host_initiated is %true.
1796  * Returns 0 on success, non-0 otherwise.
1797  * Assumes vcpu_load() was already called.
1798  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1799 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1800 			 bool host_initiated)
1801 {
1802 	struct msr_data msr;
1803 
1804 	switch (index) {
1805 	case MSR_FS_BASE:
1806 	case MSR_GS_BASE:
1807 	case MSR_KERNEL_GS_BASE:
1808 	case MSR_CSTAR:
1809 	case MSR_LSTAR:
1810 		if (is_noncanonical_msr_address(data, vcpu))
1811 			return 1;
1812 		break;
1813 	case MSR_IA32_SYSENTER_EIP:
1814 	case MSR_IA32_SYSENTER_ESP:
1815 		/*
1816 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1817 		 * non-canonical address is written on Intel but not on
1818 		 * AMD (which ignores the top 32-bits, because it does
1819 		 * not implement 64-bit SYSENTER).
1820 		 *
1821 		 * 64-bit code should hence be able to write a non-canonical
1822 		 * value on AMD.  Making the address canonical ensures that
1823 		 * vmentry does not fail on Intel after writing a non-canonical
1824 		 * value, and that something deterministic happens if the guest
1825 		 * invokes 64-bit SYSENTER.
1826 		 */
1827 		data = __canonical_address(data, max_host_virt_addr_bits());
1828 		break;
1829 	case MSR_TSC_AUX:
1830 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1831 			return 1;
1832 
1833 		if (!host_initiated &&
1834 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1835 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1836 			return 1;
1837 
1838 		/*
1839 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1840 		 * incomplete and conflicting architectural behavior.  Current
1841 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1842 		 * reserved and always read as zeros.  Enforce Intel's reserved
1843 		 * bits check if the guest CPU is Intel compatible, otherwise
1844 		 * clear the bits.  This ensures cross-vendor migration will
1845 		 * provide consistent behavior for the guest.
1846 		 */
1847 		if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1848 			return 1;
1849 
1850 		data = (u32)data;
1851 		break;
1852 	}
1853 
1854 	msr.data = data;
1855 	msr.index = index;
1856 	msr.host_initiated = host_initiated;
1857 
1858 	return kvm_x86_call(set_msr)(vcpu, &msr);
1859 }
1860 
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1861 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1862 			bool host_initiated)
1863 {
1864 	return __kvm_set_msr(vcpu, index, *data, host_initiated);
1865 }
1866 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1867 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1868 				     u32 index, u64 data, bool host_initiated)
1869 {
1870 	return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1871 				 _kvm_set_msr);
1872 }
1873 
1874 /*
1875  * Read the MSR specified by @index into @data.  Select MSR specific fault
1876  * checks are bypassed if @host_initiated is %true.
1877  * Returns 0 on success, non-0 otherwise.
1878  * Assumes vcpu_load() was already called.
1879  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1880 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1881 		  bool host_initiated)
1882 {
1883 	struct msr_data msr;
1884 	int ret;
1885 
1886 	switch (index) {
1887 	case MSR_TSC_AUX:
1888 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1889 			return 1;
1890 
1891 		if (!host_initiated &&
1892 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1893 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1894 			return 1;
1895 		break;
1896 	}
1897 
1898 	msr.index = index;
1899 	msr.host_initiated = host_initiated;
1900 
1901 	ret = kvm_x86_call(get_msr)(vcpu, &msr);
1902 	if (!ret)
1903 		*data = msr.data;
1904 	return ret;
1905 }
1906 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1907 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1908 				     u32 index, u64 *data, bool host_initiated)
1909 {
1910 	return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
1911 				 __kvm_get_msr);
1912 }
1913 
kvm_get_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 * data)1914 int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1915 {
1916 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1917 		return KVM_MSR_RET_FILTERED;
1918 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1919 }
1920 EXPORT_SYMBOL_GPL(kvm_get_msr_with_filter);
1921 
kvm_set_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 data)1922 int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1923 {
1924 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1925 		return KVM_MSR_RET_FILTERED;
1926 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1927 }
1928 EXPORT_SYMBOL_GPL(kvm_set_msr_with_filter);
1929 
kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data)1930 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1931 {
1932 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1933 }
1934 EXPORT_SYMBOL_GPL(kvm_get_msr);
1935 
kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data)1936 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1937 {
1938 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1939 }
1940 EXPORT_SYMBOL_GPL(kvm_set_msr);
1941 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)1942 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1943 {
1944 	if (!vcpu->run->msr.error) {
1945 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1946 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1947 	}
1948 }
1949 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)1950 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1951 {
1952 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1953 }
1954 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)1955 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1956 {
1957 	complete_userspace_rdmsr(vcpu);
1958 	return complete_emulated_msr_access(vcpu);
1959 }
1960 
complete_fast_msr_access(struct kvm_vcpu * vcpu)1961 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1962 {
1963 	return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1964 }
1965 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)1966 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1967 {
1968 	complete_userspace_rdmsr(vcpu);
1969 	return complete_fast_msr_access(vcpu);
1970 }
1971 
kvm_msr_reason(int r)1972 static u64 kvm_msr_reason(int r)
1973 {
1974 	switch (r) {
1975 	case KVM_MSR_RET_UNSUPPORTED:
1976 		return KVM_MSR_EXIT_REASON_UNKNOWN;
1977 	case KVM_MSR_RET_FILTERED:
1978 		return KVM_MSR_EXIT_REASON_FILTER;
1979 	default:
1980 		return KVM_MSR_EXIT_REASON_INVAL;
1981 	}
1982 }
1983 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)1984 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1985 			      u32 exit_reason, u64 data,
1986 			      int (*completion)(struct kvm_vcpu *vcpu),
1987 			      int r)
1988 {
1989 	u64 msr_reason = kvm_msr_reason(r);
1990 
1991 	/* Check if the user wanted to know about this MSR fault */
1992 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1993 		return 0;
1994 
1995 	vcpu->run->exit_reason = exit_reason;
1996 	vcpu->run->msr.error = 0;
1997 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1998 	vcpu->run->msr.reason = msr_reason;
1999 	vcpu->run->msr.index = index;
2000 	vcpu->run->msr.data = data;
2001 	vcpu->arch.complete_userspace_io = completion;
2002 
2003 	return 1;
2004 }
2005 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2006 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2007 {
2008 	u32 ecx = kvm_rcx_read(vcpu);
2009 	u64 data;
2010 	int r;
2011 
2012 	r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2013 
2014 	if (!r) {
2015 		trace_kvm_msr_read(ecx, data);
2016 
2017 		kvm_rax_write(vcpu, data & -1u);
2018 		kvm_rdx_write(vcpu, (data >> 32) & -1u);
2019 	} else {
2020 		/* MSR read failed? See if we should ask user space */
2021 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2022 				       complete_fast_rdmsr, r))
2023 			return 0;
2024 		trace_kvm_msr_read_ex(ecx);
2025 	}
2026 
2027 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2028 }
2029 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2030 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2031 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2032 {
2033 	u32 ecx = kvm_rcx_read(vcpu);
2034 	u64 data = kvm_read_edx_eax(vcpu);
2035 	int r;
2036 
2037 	r = kvm_set_msr_with_filter(vcpu, ecx, data);
2038 
2039 	if (!r) {
2040 		trace_kvm_msr_write(ecx, data);
2041 	} else {
2042 		/* MSR write failed? See if we should ask user space */
2043 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2044 				       complete_fast_msr_access, r))
2045 			return 0;
2046 		/* Signal all other negative errors to userspace */
2047 		if (r < 0)
2048 			return r;
2049 		trace_kvm_msr_write_ex(ecx, data);
2050 	}
2051 
2052 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2053 }
2054 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2055 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2056 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2057 {
2058 	return kvm_skip_emulated_instruction(vcpu);
2059 }
2060 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2061 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2062 {
2063 	/* Treat an INVD instruction as a NOP and just skip it. */
2064 	return kvm_emulate_as_nop(vcpu);
2065 }
2066 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2067 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2068 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2069 {
2070 	kvm_queue_exception(vcpu, UD_VECTOR);
2071 	return 1;
2072 }
2073 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2074 
2075 
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2076 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2077 {
2078 	bool enabled;
2079 
2080 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2081 		goto emulate_as_nop;
2082 
2083 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2084 		enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2085 	else
2086 		enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2087 
2088 	if (!enabled)
2089 		return kvm_handle_invalid_op(vcpu);
2090 
2091 emulate_as_nop:
2092 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
2093 	return kvm_emulate_as_nop(vcpu);
2094 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2095 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2096 {
2097 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2098 }
2099 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2100 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2101 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2102 {
2103 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2104 }
2105 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2106 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2107 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2108 {
2109 	xfer_to_guest_mode_prepare();
2110 
2111 	return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2112 	       kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2113 }
2114 
2115 /*
2116  * The fast path for frequent and performance sensitive wrmsr emulation,
2117  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2118  * the latency of virtual IPI by avoiding the expensive bits of transitioning
2119  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2120  * other cases which must be called after interrupts are enabled on the host.
2121  */
handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu * vcpu,u64 data)2122 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2123 {
2124 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2125 		return 1;
2126 
2127 	if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2128 	    ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2129 	    ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2130 	    ((u32)(data >> 32) != X2APIC_BROADCAST))
2131 		return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2132 
2133 	return 1;
2134 }
2135 
handle_fastpath_set_tscdeadline(struct kvm_vcpu * vcpu,u64 data)2136 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2137 {
2138 	if (!kvm_can_use_hv_timer(vcpu))
2139 		return 1;
2140 
2141 	kvm_set_lapic_tscdeadline_msr(vcpu, data);
2142 	return 0;
2143 }
2144 
handle_fastpath_set_msr_irqoff(struct kvm_vcpu * vcpu)2145 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2146 {
2147 	u32 msr = kvm_rcx_read(vcpu);
2148 	u64 data;
2149 	fastpath_t ret;
2150 	bool handled;
2151 
2152 	kvm_vcpu_srcu_read_lock(vcpu);
2153 
2154 	switch (msr) {
2155 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2156 		data = kvm_read_edx_eax(vcpu);
2157 		handled = !handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
2158 		break;
2159 	case MSR_IA32_TSC_DEADLINE:
2160 		data = kvm_read_edx_eax(vcpu);
2161 		handled = !handle_fastpath_set_tscdeadline(vcpu, data);
2162 		break;
2163 	default:
2164 		handled = false;
2165 		break;
2166 	}
2167 
2168 	if (handled) {
2169 		if (!kvm_skip_emulated_instruction(vcpu))
2170 			ret = EXIT_FASTPATH_EXIT_USERSPACE;
2171 		else
2172 			ret = EXIT_FASTPATH_REENTER_GUEST;
2173 		trace_kvm_msr_write(msr, data);
2174 	} else {
2175 		ret = EXIT_FASTPATH_NONE;
2176 	}
2177 
2178 	kvm_vcpu_srcu_read_unlock(vcpu);
2179 
2180 	return ret;
2181 }
2182 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2183 
2184 /*
2185  * Adapt set_msr() to msr_io()'s calling convention
2186  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2187 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2188 {
2189 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2190 }
2191 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2192 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2193 {
2194 	u64 val;
2195 
2196 	/*
2197 	 * Disallow writes to immutable feature MSRs after KVM_RUN.  KVM does
2198 	 * not support modifying the guest vCPU model on the fly, e.g. changing
2199 	 * the nVMX capabilities while L2 is running is nonsensical.  Allow
2200 	 * writes of the same value, e.g. to allow userspace to blindly stuff
2201 	 * all MSRs when emulating RESET.
2202 	 */
2203 	if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2204 	    (do_get_msr(vcpu, index, &val) || *data != val))
2205 		return -EINVAL;
2206 
2207 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2208 }
2209 
2210 #ifdef CONFIG_X86_64
2211 struct pvclock_clock {
2212 	int vclock_mode;
2213 	u64 cycle_last;
2214 	u64 mask;
2215 	u32 mult;
2216 	u32 shift;
2217 	u64 base_cycles;
2218 	u64 offset;
2219 };
2220 
2221 struct pvclock_gtod_data {
2222 	seqcount_t	seq;
2223 
2224 	struct pvclock_clock clock; /* extract of a clocksource struct */
2225 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2226 
2227 	ktime_t		offs_boot;
2228 	u64		wall_time_sec;
2229 };
2230 
2231 static struct pvclock_gtod_data pvclock_gtod_data;
2232 
update_pvclock_gtod(struct timekeeper * tk)2233 static void update_pvclock_gtod(struct timekeeper *tk)
2234 {
2235 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2236 
2237 	write_seqcount_begin(&vdata->seq);
2238 
2239 	/* copy pvclock gtod data */
2240 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2241 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2242 	vdata->clock.mask		= tk->tkr_mono.mask;
2243 	vdata->clock.mult		= tk->tkr_mono.mult;
2244 	vdata->clock.shift		= tk->tkr_mono.shift;
2245 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2246 	vdata->clock.offset		= tk->tkr_mono.base;
2247 
2248 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2249 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2250 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2251 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2252 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2253 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2254 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2255 
2256 	vdata->wall_time_sec            = tk->xtime_sec;
2257 
2258 	vdata->offs_boot		= tk->offs_boot;
2259 
2260 	write_seqcount_end(&vdata->seq);
2261 }
2262 
get_kvmclock_base_ns(void)2263 static s64 get_kvmclock_base_ns(void)
2264 {
2265 	/* Count up from boot time, but with the frequency of the raw clock.  */
2266 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2267 }
2268 #else
get_kvmclock_base_ns(void)2269 static s64 get_kvmclock_base_ns(void)
2270 {
2271 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2272 	return ktime_get_boottime_ns();
2273 }
2274 #endif
2275 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2276 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2277 {
2278 	int version;
2279 	int r;
2280 	struct pvclock_wall_clock wc;
2281 	u32 wc_sec_hi;
2282 	u64 wall_nsec;
2283 
2284 	if (!wall_clock)
2285 		return;
2286 
2287 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2288 	if (r)
2289 		return;
2290 
2291 	if (version & 1)
2292 		++version;  /* first time write, random junk */
2293 
2294 	++version;
2295 
2296 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2297 		return;
2298 
2299 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
2300 
2301 	wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2302 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2303 	wc.version = version;
2304 
2305 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2306 
2307 	if (sec_hi_ofs) {
2308 		wc_sec_hi = wall_nsec >> 32;
2309 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2310 				&wc_sec_hi, sizeof(wc_sec_hi));
2311 	}
2312 
2313 	version++;
2314 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2315 }
2316 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2317 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2318 				  bool old_msr, bool host_initiated)
2319 {
2320 	struct kvm_arch *ka = &vcpu->kvm->arch;
2321 
2322 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2323 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2324 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2325 
2326 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2327 	}
2328 
2329 	vcpu->arch.time = system_time;
2330 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2331 
2332 	/* we verify if the enable bit is set... */
2333 	if (system_time & 1)
2334 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2335 				 sizeof(struct pvclock_vcpu_time_info));
2336 	else
2337 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
2338 
2339 	return;
2340 }
2341 
div_frac(uint32_t dividend,uint32_t divisor)2342 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2343 {
2344 	do_shl32_div32(dividend, divisor);
2345 	return dividend;
2346 }
2347 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2348 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2349 			       s8 *pshift, u32 *pmultiplier)
2350 {
2351 	uint64_t scaled64;
2352 	int32_t  shift = 0;
2353 	uint64_t tps64;
2354 	uint32_t tps32;
2355 
2356 	tps64 = base_hz;
2357 	scaled64 = scaled_hz;
2358 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2359 		tps64 >>= 1;
2360 		shift--;
2361 	}
2362 
2363 	tps32 = (uint32_t)tps64;
2364 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2365 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2366 			scaled64 >>= 1;
2367 		else
2368 			tps32 <<= 1;
2369 		shift++;
2370 	}
2371 
2372 	*pshift = shift;
2373 	*pmultiplier = div_frac(scaled64, tps32);
2374 }
2375 
2376 #ifdef CONFIG_X86_64
2377 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2378 #endif
2379 
2380 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2381 static unsigned long max_tsc_khz;
2382 
adjust_tsc_khz(u32 khz,s32 ppm)2383 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2384 {
2385 	u64 v = (u64)khz * (1000000 + ppm);
2386 	do_div(v, 1000000);
2387 	return v;
2388 }
2389 
2390 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2391 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2392 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2393 {
2394 	u64 ratio;
2395 
2396 	/* Guest TSC same frequency as host TSC? */
2397 	if (!scale) {
2398 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2399 		return 0;
2400 	}
2401 
2402 	/* TSC scaling supported? */
2403 	if (!kvm_caps.has_tsc_control) {
2404 		if (user_tsc_khz > tsc_khz) {
2405 			vcpu->arch.tsc_catchup = 1;
2406 			vcpu->arch.tsc_always_catchup = 1;
2407 			return 0;
2408 		} else {
2409 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2410 			return -1;
2411 		}
2412 	}
2413 
2414 	/* TSC scaling required  - calculate ratio */
2415 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2416 				user_tsc_khz, tsc_khz);
2417 
2418 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2419 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2420 			            user_tsc_khz);
2421 		return -1;
2422 	}
2423 
2424 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2425 	return 0;
2426 }
2427 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2428 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2429 {
2430 	u32 thresh_lo, thresh_hi;
2431 	int use_scaling = 0;
2432 
2433 	/* tsc_khz can be zero if TSC calibration fails */
2434 	if (user_tsc_khz == 0) {
2435 		/* set tsc_scaling_ratio to a safe value */
2436 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2437 		return -1;
2438 	}
2439 
2440 	/* Compute a scale to convert nanoseconds in TSC cycles */
2441 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2442 			   &vcpu->arch.virtual_tsc_shift,
2443 			   &vcpu->arch.virtual_tsc_mult);
2444 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2445 
2446 	/*
2447 	 * Compute the variation in TSC rate which is acceptable
2448 	 * within the range of tolerance and decide if the
2449 	 * rate being applied is within that bounds of the hardware
2450 	 * rate.  If so, no scaling or compensation need be done.
2451 	 */
2452 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2453 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2454 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2455 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2456 			 user_tsc_khz, thresh_lo, thresh_hi);
2457 		use_scaling = 1;
2458 	}
2459 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2460 }
2461 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2462 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2463 {
2464 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2465 				      vcpu->arch.virtual_tsc_mult,
2466 				      vcpu->arch.virtual_tsc_shift);
2467 	tsc += vcpu->arch.this_tsc_write;
2468 	return tsc;
2469 }
2470 
2471 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2472 static inline bool gtod_is_based_on_tsc(int mode)
2473 {
2474 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2475 }
2476 #endif
2477 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2478 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2479 {
2480 #ifdef CONFIG_X86_64
2481 	struct kvm_arch *ka = &vcpu->kvm->arch;
2482 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2483 
2484 	/*
2485 	 * To use the masterclock, the host clocksource must be based on TSC
2486 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
2487 	 * vCPUs doesn't include the reference vCPU, hence "+1".
2488 	 */
2489 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2490 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
2491 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2492 
2493 	/*
2494 	 * Request a masterclock update if the masterclock needs to be toggled
2495 	 * on/off, or when starting a new generation and the masterclock is
2496 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2497 	 * taken _after_ the new generation is created).
2498 	 */
2499 	if ((ka->use_master_clock && new_generation) ||
2500 	    (ka->use_master_clock != use_master_clock))
2501 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2502 
2503 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2504 			    atomic_read(&vcpu->kvm->online_vcpus),
2505 		            ka->use_master_clock, gtod->clock.vclock_mode);
2506 #endif
2507 }
2508 
2509 /*
2510  * Multiply tsc by a fixed point number represented by ratio.
2511  *
2512  * The most significant 64-N bits (mult) of ratio represent the
2513  * integral part of the fixed point number; the remaining N bits
2514  * (frac) represent the fractional part, ie. ratio represents a fixed
2515  * point number (mult + frac * 2^(-N)).
2516  *
2517  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2518  */
__scale_tsc(u64 ratio,u64 tsc)2519 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2520 {
2521 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2522 }
2523 
kvm_scale_tsc(u64 tsc,u64 ratio)2524 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2525 {
2526 	u64 _tsc = tsc;
2527 
2528 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
2529 		_tsc = __scale_tsc(ratio, tsc);
2530 
2531 	return _tsc;
2532 }
2533 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2534 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2535 {
2536 	u64 tsc;
2537 
2538 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2539 
2540 	return target_tsc - tsc;
2541 }
2542 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2543 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2544 {
2545 	return vcpu->arch.l1_tsc_offset +
2546 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2547 }
2548 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2549 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2550 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2551 {
2552 	u64 nested_offset;
2553 
2554 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2555 		nested_offset = l1_offset;
2556 	else
2557 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2558 						kvm_caps.tsc_scaling_ratio_frac_bits);
2559 
2560 	nested_offset += l2_offset;
2561 	return nested_offset;
2562 }
2563 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2564 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2565 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2566 {
2567 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2568 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2569 				       kvm_caps.tsc_scaling_ratio_frac_bits);
2570 
2571 	return l1_multiplier;
2572 }
2573 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2574 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2575 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2576 {
2577 	if (vcpu->arch.guest_tsc_protected)
2578 		return;
2579 
2580 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2581 				   vcpu->arch.l1_tsc_offset,
2582 				   l1_offset);
2583 
2584 	vcpu->arch.l1_tsc_offset = l1_offset;
2585 
2586 	/*
2587 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2588 	 * according to the spec this should set L1's TSC (as opposed to
2589 	 * setting L1's offset for L2).
2590 	 */
2591 	if (is_guest_mode(vcpu))
2592 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2593 			l1_offset,
2594 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
2595 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2596 	else
2597 		vcpu->arch.tsc_offset = l1_offset;
2598 
2599 	kvm_x86_call(write_tsc_offset)(vcpu);
2600 }
2601 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2602 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2603 {
2604 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2605 
2606 	/* Userspace is changing the multiplier while L2 is active */
2607 	if (is_guest_mode(vcpu))
2608 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2609 			l1_multiplier,
2610 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2611 	else
2612 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2613 
2614 	if (kvm_caps.has_tsc_control)
2615 		kvm_x86_call(write_tsc_multiplier)(vcpu);
2616 }
2617 
kvm_check_tsc_unstable(void)2618 static inline bool kvm_check_tsc_unstable(void)
2619 {
2620 #ifdef CONFIG_X86_64
2621 	/*
2622 	 * TSC is marked unstable when we're running on Hyper-V,
2623 	 * 'TSC page' clocksource is good.
2624 	 */
2625 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2626 		return false;
2627 #endif
2628 	return check_tsc_unstable();
2629 }
2630 
2631 /*
2632  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2633  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2634  * participates in.
2635  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2636 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2637 				  u64 ns, bool matched, bool user_set_tsc)
2638 {
2639 	struct kvm *kvm = vcpu->kvm;
2640 
2641 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2642 
2643 	if (vcpu->arch.guest_tsc_protected)
2644 		return;
2645 
2646 	if (user_set_tsc)
2647 		vcpu->kvm->arch.user_set_tsc = true;
2648 
2649 	/*
2650 	 * We also track th most recent recorded KHZ, write and time to
2651 	 * allow the matching interval to be extended at each write.
2652 	 */
2653 	kvm->arch.last_tsc_nsec = ns;
2654 	kvm->arch.last_tsc_write = tsc;
2655 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2656 	kvm->arch.last_tsc_offset = offset;
2657 
2658 	vcpu->arch.last_guest_tsc = tsc;
2659 
2660 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2661 
2662 	if (!matched) {
2663 		/*
2664 		 * We split periods of matched TSC writes into generations.
2665 		 * For each generation, we track the original measured
2666 		 * nanosecond time, offset, and write, so if TSCs are in
2667 		 * sync, we can match exact offset, and if not, we can match
2668 		 * exact software computation in compute_guest_tsc()
2669 		 *
2670 		 * These values are tracked in kvm->arch.cur_xxx variables.
2671 		 */
2672 		kvm->arch.cur_tsc_generation++;
2673 		kvm->arch.cur_tsc_nsec = ns;
2674 		kvm->arch.cur_tsc_write = tsc;
2675 		kvm->arch.cur_tsc_offset = offset;
2676 		kvm->arch.nr_vcpus_matched_tsc = 0;
2677 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2678 		kvm->arch.nr_vcpus_matched_tsc++;
2679 	}
2680 
2681 	/* Keep track of which generation this VCPU has synchronized to */
2682 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2683 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2684 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2685 
2686 	kvm_track_tsc_matching(vcpu, !matched);
2687 }
2688 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2689 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2690 {
2691 	u64 data = user_value ? *user_value : 0;
2692 	struct kvm *kvm = vcpu->kvm;
2693 	u64 offset, ns, elapsed;
2694 	unsigned long flags;
2695 	bool matched = false;
2696 	bool synchronizing = false;
2697 
2698 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2699 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2700 	ns = get_kvmclock_base_ns();
2701 	elapsed = ns - kvm->arch.last_tsc_nsec;
2702 
2703 	if (vcpu->arch.virtual_tsc_khz) {
2704 		if (data == 0) {
2705 			/*
2706 			 * Force synchronization when creating a vCPU, or when
2707 			 * userspace explicitly writes a zero value.
2708 			 */
2709 			synchronizing = true;
2710 		} else if (kvm->arch.user_set_tsc) {
2711 			u64 tsc_exp = kvm->arch.last_tsc_write +
2712 						nsec_to_cycles(vcpu, elapsed);
2713 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2714 			/*
2715 			 * Here lies UAPI baggage: when a user-initiated TSC write has
2716 			 * a small delta (1 second) of virtual cycle time against the
2717 			 * previously set vCPU, we assume that they were intended to be
2718 			 * in sync and the delta was only due to the racy nature of the
2719 			 * legacy API.
2720 			 *
2721 			 * This trick falls down when restoring a guest which genuinely
2722 			 * has been running for less time than the 1 second of imprecision
2723 			 * which we allow for in the legacy API. In this case, the first
2724 			 * value written by userspace (on any vCPU) should not be subject
2725 			 * to this 'correction' to make it sync up with values that only
2726 			 * come from the kernel's default vCPU creation. Make the 1-second
2727 			 * slop hack only trigger if the user_set_tsc flag is already set.
2728 			 */
2729 			synchronizing = data < tsc_exp + tsc_hz &&
2730 					data + tsc_hz > tsc_exp;
2731 		}
2732 	}
2733 
2734 
2735 	/*
2736 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2737 	 * TSC, we add elapsed time in this computation.  We could let the
2738 	 * compensation code attempt to catch up if we fall behind, but
2739 	 * it's better to try to match offsets from the beginning.
2740          */
2741 	if (synchronizing &&
2742 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2743 		if (!kvm_check_tsc_unstable()) {
2744 			offset = kvm->arch.cur_tsc_offset;
2745 		} else {
2746 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2747 			data += delta;
2748 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2749 		}
2750 		matched = true;
2751 	}
2752 
2753 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2754 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2755 }
2756 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2757 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2758 					   s64 adjustment)
2759 {
2760 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2761 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2762 }
2763 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2764 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2765 {
2766 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2767 		WARN_ON(adjustment < 0);
2768 	adjustment = kvm_scale_tsc((u64) adjustment,
2769 				   vcpu->arch.l1_tsc_scaling_ratio);
2770 	adjust_tsc_offset_guest(vcpu, adjustment);
2771 }
2772 
2773 #ifdef CONFIG_X86_64
2774 
read_tsc(void)2775 static u64 read_tsc(void)
2776 {
2777 	u64 ret = (u64)rdtsc_ordered();
2778 	u64 last = pvclock_gtod_data.clock.cycle_last;
2779 
2780 	if (likely(ret >= last))
2781 		return ret;
2782 
2783 	/*
2784 	 * GCC likes to generate cmov here, but this branch is extremely
2785 	 * predictable (it's just a function of time and the likely is
2786 	 * very likely) and there's a data dependence, so force GCC
2787 	 * to generate a branch instead.  I don't barrier() because
2788 	 * we don't actually need a barrier, and if this function
2789 	 * ever gets inlined it will generate worse code.
2790 	 */
2791 	asm volatile ("");
2792 	return last;
2793 }
2794 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2795 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2796 			  int *mode)
2797 {
2798 	u64 tsc_pg_val;
2799 	long v;
2800 
2801 	switch (clock->vclock_mode) {
2802 	case VDSO_CLOCKMODE_HVCLOCK:
2803 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2804 					 tsc_timestamp, &tsc_pg_val)) {
2805 			/* TSC page valid */
2806 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2807 			v = (tsc_pg_val - clock->cycle_last) &
2808 				clock->mask;
2809 		} else {
2810 			/* TSC page invalid */
2811 			*mode = VDSO_CLOCKMODE_NONE;
2812 		}
2813 		break;
2814 	case VDSO_CLOCKMODE_TSC:
2815 		*mode = VDSO_CLOCKMODE_TSC;
2816 		*tsc_timestamp = read_tsc();
2817 		v = (*tsc_timestamp - clock->cycle_last) &
2818 			clock->mask;
2819 		break;
2820 	default:
2821 		*mode = VDSO_CLOCKMODE_NONE;
2822 	}
2823 
2824 	if (*mode == VDSO_CLOCKMODE_NONE)
2825 		*tsc_timestamp = v = 0;
2826 
2827 	return v * clock->mult;
2828 }
2829 
2830 /*
2831  * As with get_kvmclock_base_ns(), this counts from boot time, at the
2832  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2833  */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2834 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2835 {
2836 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2837 	unsigned long seq;
2838 	int mode;
2839 	u64 ns;
2840 
2841 	do {
2842 		seq = read_seqcount_begin(&gtod->seq);
2843 		ns = gtod->raw_clock.base_cycles;
2844 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2845 		ns >>= gtod->raw_clock.shift;
2846 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2847 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2848 	*t = ns;
2849 
2850 	return mode;
2851 }
2852 
2853 /*
2854  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2855  * no boot time offset.
2856  */
do_monotonic(s64 * t,u64 * tsc_timestamp)2857 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2858 {
2859 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2860 	unsigned long seq;
2861 	int mode;
2862 	u64 ns;
2863 
2864 	do {
2865 		seq = read_seqcount_begin(&gtod->seq);
2866 		ns = gtod->clock.base_cycles;
2867 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2868 		ns >>= gtod->clock.shift;
2869 		ns += ktime_to_ns(gtod->clock.offset);
2870 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2871 	*t = ns;
2872 
2873 	return mode;
2874 }
2875 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2876 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2877 {
2878 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2879 	unsigned long seq;
2880 	int mode;
2881 	u64 ns;
2882 
2883 	do {
2884 		seq = read_seqcount_begin(&gtod->seq);
2885 		ts->tv_sec = gtod->wall_time_sec;
2886 		ns = gtod->clock.base_cycles;
2887 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2888 		ns >>= gtod->clock.shift;
2889 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2890 
2891 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2892 	ts->tv_nsec = ns;
2893 
2894 	return mode;
2895 }
2896 
2897 /*
2898  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2899  * reports the TSC value from which it do so. Returns true if host is
2900  * using TSC based clocksource.
2901  */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2902 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2903 {
2904 	/* checked again under seqlock below */
2905 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2906 		return false;
2907 
2908 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2909 						     tsc_timestamp));
2910 }
2911 
2912 /*
2913  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2914  * so. Returns true if host is using TSC based clocksource.
2915  */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2916 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2917 {
2918 	/* checked again under seqlock below */
2919 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2920 		return false;
2921 
2922 	return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
2923 						 tsc_timestamp));
2924 }
2925 
2926 /*
2927  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2928  * so. Returns true if host is using TSC based clocksource.
2929  *
2930  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2931  * for that.
2932  */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)2933 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2934 					   u64 *tsc_timestamp)
2935 {
2936 	/* checked again under seqlock below */
2937 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2938 		return false;
2939 
2940 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2941 }
2942 #endif
2943 
2944 /*
2945  *
2946  * Assuming a stable TSC across physical CPUS, and a stable TSC
2947  * across virtual CPUs, the following condition is possible.
2948  * Each numbered line represents an event visible to both
2949  * CPUs at the next numbered event.
2950  *
2951  * "timespecX" represents host monotonic time. "tscX" represents
2952  * RDTSC value.
2953  *
2954  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
2955  *
2956  * 1.  read timespec0,tsc0
2957  * 2.					| timespec1 = timespec0 + N
2958  * 					| tsc1 = tsc0 + M
2959  * 3. transition to guest		| transition to guest
2960  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2961  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
2962  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2963  *
2964  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2965  *
2966  * 	- ret0 < ret1
2967  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2968  *		...
2969  *	- 0 < N - M => M < N
2970  *
2971  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2972  * always the case (the difference between two distinct xtime instances
2973  * might be smaller then the difference between corresponding TSC reads,
2974  * when updating guest vcpus pvclock areas).
2975  *
2976  * To avoid that problem, do not allow visibility of distinct
2977  * system_timestamp/tsc_timestamp values simultaneously: use a master
2978  * copy of host monotonic time values. Update that master copy
2979  * in lockstep.
2980  *
2981  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2982  *
2983  */
2984 
pvclock_update_vm_gtod_copy(struct kvm * kvm)2985 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2986 {
2987 #ifdef CONFIG_X86_64
2988 	struct kvm_arch *ka = &kvm->arch;
2989 	int vclock_mode;
2990 	bool host_tsc_clocksource, vcpus_matched;
2991 
2992 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2993 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2994 			atomic_read(&kvm->online_vcpus));
2995 
2996 	/*
2997 	 * If the host uses TSC clock, then passthrough TSC as stable
2998 	 * to the guest.
2999 	 */
3000 	host_tsc_clocksource = kvm_get_time_and_clockread(
3001 					&ka->master_kernel_ns,
3002 					&ka->master_cycle_now);
3003 
3004 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3005 				&& !ka->backwards_tsc_observed
3006 				&& !ka->boot_vcpu_runs_old_kvmclock;
3007 
3008 	if (ka->use_master_clock)
3009 		atomic_set(&kvm_guest_has_master_clock, 1);
3010 
3011 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3012 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3013 					vcpus_matched);
3014 #endif
3015 }
3016 
kvm_make_mclock_inprogress_request(struct kvm * kvm)3017 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3018 {
3019 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3020 }
3021 
__kvm_start_pvclock_update(struct kvm * kvm)3022 static void __kvm_start_pvclock_update(struct kvm *kvm)
3023 {
3024 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3025 	write_seqcount_begin(&kvm->arch.pvclock_sc);
3026 }
3027 
kvm_start_pvclock_update(struct kvm * kvm)3028 static void kvm_start_pvclock_update(struct kvm *kvm)
3029 {
3030 	kvm_make_mclock_inprogress_request(kvm);
3031 
3032 	/* no guest entries from this point */
3033 	__kvm_start_pvclock_update(kvm);
3034 }
3035 
kvm_end_pvclock_update(struct kvm * kvm)3036 static void kvm_end_pvclock_update(struct kvm *kvm)
3037 {
3038 	struct kvm_arch *ka = &kvm->arch;
3039 	struct kvm_vcpu *vcpu;
3040 	unsigned long i;
3041 
3042 	write_seqcount_end(&ka->pvclock_sc);
3043 	raw_spin_unlock_irq(&ka->tsc_write_lock);
3044 	kvm_for_each_vcpu(i, vcpu, kvm)
3045 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3046 
3047 	/* guest entries allowed */
3048 	kvm_for_each_vcpu(i, vcpu, kvm)
3049 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3050 }
3051 
kvm_update_masterclock(struct kvm * kvm)3052 static void kvm_update_masterclock(struct kvm *kvm)
3053 {
3054 	kvm_hv_request_tsc_page_update(kvm);
3055 	kvm_start_pvclock_update(kvm);
3056 	pvclock_update_vm_gtod_copy(kvm);
3057 	kvm_end_pvclock_update(kvm);
3058 }
3059 
3060 /*
3061  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3062  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
3063  * can change during boot even if the TSC is constant, as it's possible for KVM
3064  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
3065  * notification when calibration completes, but practically speaking calibration
3066  * will complete before userspace is alive enough to create VMs.
3067  */
get_cpu_tsc_khz(void)3068 static unsigned long get_cpu_tsc_khz(void)
3069 {
3070 	if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3071 		return tsc_khz;
3072 	else
3073 		return __this_cpu_read(cpu_tsc_khz);
3074 }
3075 
3076 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3077 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3078 {
3079 	struct kvm_arch *ka = &kvm->arch;
3080 	struct pvclock_vcpu_time_info hv_clock;
3081 
3082 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
3083 	get_cpu();
3084 
3085 	data->flags = 0;
3086 	if (ka->use_master_clock &&
3087 	    (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3088 #ifdef CONFIG_X86_64
3089 		struct timespec64 ts;
3090 
3091 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3092 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3093 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3094 		} else
3095 #endif
3096 		data->host_tsc = rdtsc();
3097 
3098 		data->flags |= KVM_CLOCK_TSC_STABLE;
3099 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3100 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3101 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3102 				   &hv_clock.tsc_shift,
3103 				   &hv_clock.tsc_to_system_mul);
3104 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3105 	} else {
3106 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3107 	}
3108 
3109 	put_cpu();
3110 }
3111 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3112 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3113 {
3114 	struct kvm_arch *ka = &kvm->arch;
3115 	unsigned seq;
3116 
3117 	do {
3118 		seq = read_seqcount_begin(&ka->pvclock_sc);
3119 		__get_kvmclock(kvm, data);
3120 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3121 }
3122 
get_kvmclock_ns(struct kvm * kvm)3123 u64 get_kvmclock_ns(struct kvm *kvm)
3124 {
3125 	struct kvm_clock_data data;
3126 
3127 	get_kvmclock(kvm, &data);
3128 	return data.clock;
3129 }
3130 
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)3131 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3132 				    struct kvm_vcpu *vcpu,
3133 				    struct gfn_to_pfn_cache *gpc,
3134 				    unsigned int offset)
3135 {
3136 	struct pvclock_vcpu_time_info *guest_hv_clock;
3137 	struct pvclock_vcpu_time_info hv_clock;
3138 	unsigned long flags;
3139 
3140 	memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3141 
3142 	read_lock_irqsave(&gpc->lock, flags);
3143 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3144 		read_unlock_irqrestore(&gpc->lock, flags);
3145 
3146 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3147 			return;
3148 
3149 		read_lock_irqsave(&gpc->lock, flags);
3150 	}
3151 
3152 	guest_hv_clock = (void *)(gpc->khva + offset);
3153 
3154 	/*
3155 	 * This VCPU is paused, but it's legal for a guest to read another
3156 	 * VCPU's kvmclock, so we really have to follow the specification where
3157 	 * it says that version is odd if data is being modified, and even after
3158 	 * it is consistent.
3159 	 */
3160 
3161 	guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3162 	smp_wmb();
3163 
3164 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3165 	hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3166 
3167 	memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3168 
3169 	smp_wmb();
3170 
3171 	guest_hv_clock->version = ++hv_clock.version;
3172 
3173 	kvm_gpc_mark_dirty_in_slot(gpc);
3174 	read_unlock_irqrestore(&gpc->lock, flags);
3175 
3176 	trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3177 }
3178 
kvm_guest_time_update(struct kvm_vcpu * v)3179 int kvm_guest_time_update(struct kvm_vcpu *v)
3180 {
3181 	struct pvclock_vcpu_time_info hv_clock = {};
3182 	unsigned long flags, tgt_tsc_khz;
3183 	unsigned seq;
3184 	struct kvm_vcpu_arch *vcpu = &v->arch;
3185 	struct kvm_arch *ka = &v->kvm->arch;
3186 	s64 kernel_ns;
3187 	u64 tsc_timestamp, host_tsc;
3188 	bool use_master_clock;
3189 
3190 	kernel_ns = 0;
3191 	host_tsc = 0;
3192 
3193 	/*
3194 	 * If the host uses TSC clock, then passthrough TSC as stable
3195 	 * to the guest.
3196 	 */
3197 	do {
3198 		seq = read_seqcount_begin(&ka->pvclock_sc);
3199 		use_master_clock = ka->use_master_clock;
3200 		if (use_master_clock) {
3201 			host_tsc = ka->master_cycle_now;
3202 			kernel_ns = ka->master_kernel_ns;
3203 		}
3204 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3205 
3206 	/* Keep irq disabled to prevent changes to the clock */
3207 	local_irq_save(flags);
3208 	tgt_tsc_khz = get_cpu_tsc_khz();
3209 	if (unlikely(tgt_tsc_khz == 0)) {
3210 		local_irq_restore(flags);
3211 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3212 		return 1;
3213 	}
3214 	if (!use_master_clock) {
3215 		host_tsc = rdtsc();
3216 		kernel_ns = get_kvmclock_base_ns();
3217 	}
3218 
3219 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3220 
3221 	/*
3222 	 * We may have to catch up the TSC to match elapsed wall clock
3223 	 * time for two reasons, even if kvmclock is used.
3224 	 *   1) CPU could have been running below the maximum TSC rate
3225 	 *   2) Broken TSC compensation resets the base at each VCPU
3226 	 *      entry to avoid unknown leaps of TSC even when running
3227 	 *      again on the same CPU.  This may cause apparent elapsed
3228 	 *      time to disappear, and the guest to stand still or run
3229 	 *	very slowly.
3230 	 */
3231 	if (vcpu->tsc_catchup) {
3232 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3233 		if (tsc > tsc_timestamp) {
3234 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3235 			tsc_timestamp = tsc;
3236 		}
3237 	}
3238 
3239 	local_irq_restore(flags);
3240 
3241 	/* With all the info we got, fill in the values */
3242 
3243 	if (kvm_caps.has_tsc_control)
3244 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3245 					    v->arch.l1_tsc_scaling_ratio);
3246 
3247 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3248 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3249 				   &vcpu->pvclock_tsc_shift,
3250 				   &vcpu->pvclock_tsc_mul);
3251 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3252 	}
3253 
3254 	hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3255 	hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3256 	hv_clock.tsc_timestamp = tsc_timestamp;
3257 	hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3258 	vcpu->last_guest_tsc = tsc_timestamp;
3259 
3260 	/* If the host uses TSC clocksource, then it is stable */
3261 	hv_clock.flags = 0;
3262 	if (use_master_clock)
3263 		hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3264 
3265 	if (vcpu->pv_time.active) {
3266 		/*
3267 		 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3268 		 * historic behavior is to only process the request if kvmclock
3269 		 * is active/enabled.
3270 		 */
3271 		if (vcpu->pvclock_set_guest_stopped_request) {
3272 			hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3273 			vcpu->pvclock_set_guest_stopped_request = false;
3274 		}
3275 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3276 
3277 		hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3278 	}
3279 
3280 	kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3281 
3282 #ifdef CONFIG_KVM_XEN
3283 	/*
3284 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3285 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3286 	 * This default behaviour led to bugs in some guest kernels which cause
3287 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3288 	 *
3289 	 * Note!  Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3290 	 */
3291 	if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3292 		hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3293 
3294 	if (vcpu->xen.vcpu_info_cache.active)
3295 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3296 					offsetof(struct compat_vcpu_info, time));
3297 	if (vcpu->xen.vcpu_time_info_cache.active)
3298 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3299 #endif
3300 	return 0;
3301 }
3302 
3303 /*
3304  * The pvclock_wall_clock ABI tells the guest the wall clock time at
3305  * which it started (i.e. its epoch, when its kvmclock was zero).
3306  *
3307  * In fact those clocks are subtly different; wall clock frequency is
3308  * adjusted by NTP and has leap seconds, while the kvmclock is a
3309  * simple function of the TSC without any such adjustment.
3310  *
3311  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3312  * that and kvmclock, but even that would be subject to change over
3313  * time.
3314  *
3315  * Attempt to calculate the epoch at a given moment using the *same*
3316  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3317  * wallclock and kvmclock times, and subtracting one from the other.
3318  *
3319  * Fall back to using their values at slightly different moments by
3320  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3321  */
kvm_get_wall_clock_epoch(struct kvm * kvm)3322 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3323 {
3324 #ifdef CONFIG_X86_64
3325 	struct pvclock_vcpu_time_info hv_clock;
3326 	struct kvm_arch *ka = &kvm->arch;
3327 	unsigned long seq, local_tsc_khz;
3328 	struct timespec64 ts;
3329 	uint64_t host_tsc;
3330 
3331 	do {
3332 		seq = read_seqcount_begin(&ka->pvclock_sc);
3333 
3334 		local_tsc_khz = 0;
3335 		if (!ka->use_master_clock)
3336 			break;
3337 
3338 		/*
3339 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
3340 		 * on the same CPU.
3341 		 */
3342 		get_cpu();
3343 
3344 		local_tsc_khz = get_cpu_tsc_khz();
3345 
3346 		if (local_tsc_khz &&
3347 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3348 			local_tsc_khz = 0; /* Fall back to old method */
3349 
3350 		put_cpu();
3351 
3352 		/*
3353 		 * These values must be snapshotted within the seqcount loop.
3354 		 * After that, it's just mathematics which can happen on any
3355 		 * CPU at any time.
3356 		 */
3357 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3358 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3359 
3360 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3361 
3362 	/*
3363 	 * If the conditions were right, and obtaining the wallclock+TSC was
3364 	 * successful, calculate the KVM clock at the corresponding time and
3365 	 * subtract one from the other to get the guest's epoch in nanoseconds
3366 	 * since 1970-01-01.
3367 	 */
3368 	if (local_tsc_khz) {
3369 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3370 				   &hv_clock.tsc_shift,
3371 				   &hv_clock.tsc_to_system_mul);
3372 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3373 			__pvclock_read_cycles(&hv_clock, host_tsc);
3374 	}
3375 #endif
3376 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3377 }
3378 
3379 /*
3380  * kvmclock updates which are isolated to a given vcpu, such as
3381  * vcpu->cpu migration, should not allow system_timestamp from
3382  * the rest of the vcpus to remain static. Otherwise ntp frequency
3383  * correction applies to one vcpu's system_timestamp but not
3384  * the others.
3385  *
3386  * So in those cases, request a kvmclock update for all vcpus.
3387  * We need to rate-limit these requests though, as they can
3388  * considerably slow guests that have a large number of vcpus.
3389  * The time for a remote vcpu to update its kvmclock is bound
3390  * by the delay we use to rate-limit the updates.
3391  */
3392 
3393 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3394 
kvmclock_update_fn(struct work_struct * work)3395 static void kvmclock_update_fn(struct work_struct *work)
3396 {
3397 	unsigned long i;
3398 	struct delayed_work *dwork = to_delayed_work(work);
3399 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3400 					   kvmclock_update_work);
3401 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3402 	struct kvm_vcpu *vcpu;
3403 
3404 	kvm_for_each_vcpu(i, vcpu, kvm) {
3405 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3406 		kvm_vcpu_kick(vcpu);
3407 	}
3408 }
3409 
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3410 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3411 {
3412 	struct kvm *kvm = v->kvm;
3413 
3414 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3415 	schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3416 					KVMCLOCK_UPDATE_DELAY);
3417 }
3418 
3419 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3420 
kvmclock_sync_fn(struct work_struct * work)3421 static void kvmclock_sync_fn(struct work_struct *work)
3422 {
3423 	struct delayed_work *dwork = to_delayed_work(work);
3424 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3425 					   kvmclock_sync_work);
3426 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3427 
3428 	schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3429 	schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3430 					KVMCLOCK_SYNC_PERIOD);
3431 }
3432 
3433 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3434 static bool is_mci_control_msr(u32 msr)
3435 {
3436 	return (msr & 3) == 0;
3437 }
is_mci_status_msr(u32 msr)3438 static bool is_mci_status_msr(u32 msr)
3439 {
3440 	return (msr & 3) == 1;
3441 }
3442 
3443 /*
3444  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3445  */
can_set_mci_status(struct kvm_vcpu * vcpu)3446 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3447 {
3448 	/* McStatusWrEn enabled? */
3449 	if (guest_cpuid_is_amd_compatible(vcpu))
3450 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3451 
3452 	return false;
3453 }
3454 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3455 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3456 {
3457 	u64 mcg_cap = vcpu->arch.mcg_cap;
3458 	unsigned bank_num = mcg_cap & 0xff;
3459 	u32 msr = msr_info->index;
3460 	u64 data = msr_info->data;
3461 	u32 offset, last_msr;
3462 
3463 	switch (msr) {
3464 	case MSR_IA32_MCG_STATUS:
3465 		vcpu->arch.mcg_status = data;
3466 		break;
3467 	case MSR_IA32_MCG_CTL:
3468 		if (!(mcg_cap & MCG_CTL_P) &&
3469 		    (data || !msr_info->host_initiated))
3470 			return 1;
3471 		if (data != 0 && data != ~(u64)0)
3472 			return 1;
3473 		vcpu->arch.mcg_ctl = data;
3474 		break;
3475 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3476 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3477 		if (msr > last_msr)
3478 			return 1;
3479 
3480 		if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3481 			return 1;
3482 		/* An attempt to write a 1 to a reserved bit raises #GP */
3483 		if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3484 			return 1;
3485 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3486 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
3487 		vcpu->arch.mci_ctl2_banks[offset] = data;
3488 		break;
3489 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3490 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3491 		if (msr > last_msr)
3492 			return 1;
3493 
3494 		/*
3495 		 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3496 		 * values are architecturally undefined.  But, some Linux
3497 		 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3498 		 * issue on AMD K8s, allow bit 10 to be clear when setting all
3499 		 * other bits in order to avoid an uncaught #GP in the guest.
3500 		 *
3501 		 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3502 		 * single-bit ECC data errors.
3503 		 */
3504 		if (is_mci_control_msr(msr) &&
3505 		    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3506 			return 1;
3507 
3508 		/*
3509 		 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3510 		 * AMD-based CPUs allow non-zero values, but if and only if
3511 		 * HWCR[McStatusWrEn] is set.
3512 		 */
3513 		if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3514 		    data != 0 && !can_set_mci_status(vcpu))
3515 			return 1;
3516 
3517 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3518 					    last_msr + 1 - MSR_IA32_MC0_CTL);
3519 		vcpu->arch.mce_banks[offset] = data;
3520 		break;
3521 	default:
3522 		return 1;
3523 	}
3524 	return 0;
3525 }
3526 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3527 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3528 {
3529 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3530 
3531 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
3532 }
3533 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3534 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3535 {
3536 	gpa_t gpa = data & ~0x3f;
3537 
3538 	/* Bits 4:5 are reserved, Should be zero */
3539 	if (data & 0x30)
3540 		return 1;
3541 
3542 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3543 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3544 		return 1;
3545 
3546 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3547 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3548 		return 1;
3549 
3550 	if (!lapic_in_kernel(vcpu))
3551 		return data ? 1 : 0;
3552 
3553 	vcpu->arch.apf.msr_en_val = data;
3554 
3555 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3556 		kvm_clear_async_pf_completion_queue(vcpu);
3557 		kvm_async_pf_hash_reset(vcpu);
3558 		return 0;
3559 	}
3560 
3561 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3562 					sizeof(u64)))
3563 		return 1;
3564 
3565 	vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3566 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3567 
3568 	kvm_async_pf_wakeup_all(vcpu);
3569 
3570 	return 0;
3571 }
3572 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3573 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3574 {
3575 	/* Bits 8-63 are reserved */
3576 	if (data >> 8)
3577 		return 1;
3578 
3579 	if (!lapic_in_kernel(vcpu))
3580 		return 1;
3581 
3582 	vcpu->arch.apf.msr_int_val = data;
3583 
3584 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3585 
3586 	return 0;
3587 }
3588 
kvmclock_reset(struct kvm_vcpu * vcpu)3589 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3590 {
3591 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
3592 	vcpu->arch.time = 0;
3593 }
3594 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3595 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3596 {
3597 	++vcpu->stat.tlb_flush;
3598 	kvm_x86_call(flush_tlb_all)(vcpu);
3599 
3600 	/* Flushing all ASIDs flushes the current ASID... */
3601 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3602 }
3603 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3604 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3605 {
3606 	++vcpu->stat.tlb_flush;
3607 
3608 	if (!tdp_enabled) {
3609 		/*
3610 		 * A TLB flush on behalf of the guest is equivalent to
3611 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3612 		 * a forced sync of the shadow page tables.  Ensure all the
3613 		 * roots are synced and the guest TLB in hardware is clean.
3614 		 */
3615 		kvm_mmu_sync_roots(vcpu);
3616 		kvm_mmu_sync_prev_roots(vcpu);
3617 	}
3618 
3619 	kvm_x86_call(flush_tlb_guest)(vcpu);
3620 
3621 	/*
3622 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3623 	 * grained flushing.
3624 	 */
3625 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
3626 }
3627 
3628 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3629 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3630 {
3631 	++vcpu->stat.tlb_flush;
3632 	kvm_x86_call(flush_tlb_current)(vcpu);
3633 }
3634 
3635 /*
3636  * Service "local" TLB flush requests, which are specific to the current MMU
3637  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3638  * TLB flushes that are targeted at an MMU context also need to be serviced
3639  * prior before nested VM-Enter/VM-Exit.
3640  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3641 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3642 {
3643 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3644 		kvm_vcpu_flush_tlb_current(vcpu);
3645 
3646 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3647 		kvm_vcpu_flush_tlb_guest(vcpu);
3648 }
3649 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3650 
record_steal_time(struct kvm_vcpu * vcpu)3651 static void record_steal_time(struct kvm_vcpu *vcpu)
3652 {
3653 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3654 	struct kvm_steal_time __user *st;
3655 	struct kvm_memslots *slots;
3656 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3657 	u64 steal;
3658 	u32 version;
3659 
3660 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3661 		kvm_xen_runstate_set_running(vcpu);
3662 		return;
3663 	}
3664 
3665 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3666 		return;
3667 
3668 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3669 		return;
3670 
3671 	slots = kvm_memslots(vcpu->kvm);
3672 
3673 	if (unlikely(slots->generation != ghc->generation ||
3674 		     gpa != ghc->gpa ||
3675 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3676 		/* We rely on the fact that it fits in a single page. */
3677 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3678 
3679 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3680 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3681 			return;
3682 	}
3683 
3684 	st = (struct kvm_steal_time __user *)ghc->hva;
3685 	/*
3686 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3687 	 * expensive IPIs.
3688 	 */
3689 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3690 		u8 st_preempted = 0;
3691 		int err = -EFAULT;
3692 
3693 		if (!user_access_begin(st, sizeof(*st)))
3694 			return;
3695 
3696 		asm volatile("1: xchgb %0, %2\n"
3697 			     "xor %1, %1\n"
3698 			     "2:\n"
3699 			     _ASM_EXTABLE_UA(1b, 2b)
3700 			     : "+q" (st_preempted),
3701 			       "+&r" (err),
3702 			       "+m" (st->preempted));
3703 		if (err)
3704 			goto out;
3705 
3706 		user_access_end();
3707 
3708 		vcpu->arch.st.preempted = 0;
3709 
3710 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3711 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3712 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3713 			kvm_vcpu_flush_tlb_guest(vcpu);
3714 
3715 		if (!user_access_begin(st, sizeof(*st)))
3716 			goto dirty;
3717 	} else {
3718 		if (!user_access_begin(st, sizeof(*st)))
3719 			return;
3720 
3721 		unsafe_put_user(0, &st->preempted, out);
3722 		vcpu->arch.st.preempted = 0;
3723 	}
3724 
3725 	unsafe_get_user(version, &st->version, out);
3726 	if (version & 1)
3727 		version += 1;  /* first time write, random junk */
3728 
3729 	version += 1;
3730 	unsafe_put_user(version, &st->version, out);
3731 
3732 	smp_wmb();
3733 
3734 	unsafe_get_user(steal, &st->steal, out);
3735 	steal += current->sched_info.run_delay -
3736 		vcpu->arch.st.last_steal;
3737 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3738 	unsafe_put_user(steal, &st->steal, out);
3739 
3740 	version += 1;
3741 	unsafe_put_user(version, &st->version, out);
3742 
3743  out:
3744 	user_access_end();
3745  dirty:
3746 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3747 }
3748 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3749 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3750 {
3751 	u32 msr = msr_info->index;
3752 	u64 data = msr_info->data;
3753 
3754 	/*
3755 	 * Do not allow host-initiated writes to trigger the Xen hypercall
3756 	 * page setup; it could incur locking paths which are not expected
3757 	 * if userspace sets the MSR in an unusual location.
3758 	 */
3759 	if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3760 	    !msr_info->host_initiated)
3761 		return kvm_xen_write_hypercall_page(vcpu, data);
3762 
3763 	switch (msr) {
3764 	case MSR_AMD64_NB_CFG:
3765 	case MSR_IA32_UCODE_WRITE:
3766 	case MSR_VM_HSAVE_PA:
3767 	case MSR_AMD64_PATCH_LOADER:
3768 	case MSR_AMD64_BU_CFG2:
3769 	case MSR_AMD64_DC_CFG:
3770 	case MSR_AMD64_TW_CFG:
3771 	case MSR_F15H_EX_CFG:
3772 		break;
3773 
3774 	case MSR_IA32_UCODE_REV:
3775 		if (msr_info->host_initiated)
3776 			vcpu->arch.microcode_version = data;
3777 		break;
3778 	case MSR_IA32_ARCH_CAPABILITIES:
3779 		if (!msr_info->host_initiated ||
3780 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3781 			return KVM_MSR_RET_UNSUPPORTED;
3782 		vcpu->arch.arch_capabilities = data;
3783 		break;
3784 	case MSR_IA32_PERF_CAPABILITIES:
3785 		if (!msr_info->host_initiated ||
3786 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3787 			return KVM_MSR_RET_UNSUPPORTED;
3788 
3789 		if (data & ~kvm_caps.supported_perf_cap)
3790 			return 1;
3791 
3792 		/*
3793 		 * Note, this is not just a performance optimization!  KVM
3794 		 * disallows changing feature MSRs after the vCPU has run; PMU
3795 		 * refresh will bug the VM if called after the vCPU has run.
3796 		 */
3797 		if (vcpu->arch.perf_capabilities == data)
3798 			break;
3799 
3800 		vcpu->arch.perf_capabilities = data;
3801 		kvm_pmu_refresh(vcpu);
3802 		break;
3803 	case MSR_IA32_PRED_CMD: {
3804 		u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3805 
3806 		if (!msr_info->host_initiated) {
3807 			if ((!guest_has_pred_cmd_msr(vcpu)))
3808 				return 1;
3809 
3810 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3811 			    !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3812 				reserved_bits |= PRED_CMD_IBPB;
3813 
3814 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3815 				reserved_bits |= PRED_CMD_SBPB;
3816 		}
3817 
3818 		if (!boot_cpu_has(X86_FEATURE_IBPB))
3819 			reserved_bits |= PRED_CMD_IBPB;
3820 
3821 		if (!boot_cpu_has(X86_FEATURE_SBPB))
3822 			reserved_bits |= PRED_CMD_SBPB;
3823 
3824 		if (data & reserved_bits)
3825 			return 1;
3826 
3827 		if (!data)
3828 			break;
3829 
3830 		wrmsrl(MSR_IA32_PRED_CMD, data);
3831 		break;
3832 	}
3833 	case MSR_IA32_FLUSH_CMD:
3834 		if (!msr_info->host_initiated &&
3835 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3836 			return 1;
3837 
3838 		if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3839 			return 1;
3840 		if (!data)
3841 			break;
3842 
3843 		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3844 		break;
3845 	case MSR_EFER:
3846 		return set_efer(vcpu, msr_info);
3847 	case MSR_K7_HWCR:
3848 		data &= ~(u64)0x40;	/* ignore flush filter disable */
3849 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
3850 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
3851 
3852 		/*
3853 		 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3854 		 * through at least v6.6 whine if TscFreqSel is clear,
3855 		 * depending on F/M/S.
3856 		 */
3857 		if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
3858 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3859 			return 1;
3860 		}
3861 		vcpu->arch.msr_hwcr = data;
3862 		break;
3863 	case MSR_FAM10H_MMIO_CONF_BASE:
3864 		if (data != 0) {
3865 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3866 			return 1;
3867 		}
3868 		break;
3869 	case MSR_IA32_CR_PAT:
3870 		if (!kvm_pat_valid(data))
3871 			return 1;
3872 
3873 		vcpu->arch.pat = data;
3874 		break;
3875 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3876 	case MSR_MTRRdefType:
3877 		return kvm_mtrr_set_msr(vcpu, msr, data);
3878 	case MSR_IA32_APICBASE:
3879 		return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
3880 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3881 		return kvm_x2apic_msr_write(vcpu, msr, data);
3882 	case MSR_IA32_TSC_DEADLINE:
3883 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
3884 		break;
3885 	case MSR_IA32_TSC_ADJUST:
3886 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3887 			if (!msr_info->host_initiated) {
3888 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3889 				adjust_tsc_offset_guest(vcpu, adj);
3890 				/* Before back to guest, tsc_timestamp must be adjusted
3891 				 * as well, otherwise guest's percpu pvclock time could jump.
3892 				 */
3893 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3894 			}
3895 			vcpu->arch.ia32_tsc_adjust_msr = data;
3896 		}
3897 		break;
3898 	case MSR_IA32_MISC_ENABLE: {
3899 		u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3900 
3901 		if (!msr_info->host_initiated) {
3902 			/* RO bits */
3903 			if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3904 				return 1;
3905 
3906 			/* R bits, i.e. writes are ignored, but don't fault. */
3907 			data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3908 			data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3909 		}
3910 
3911 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3912 		    ((old_val ^ data)  & MSR_IA32_MISC_ENABLE_MWAIT)) {
3913 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
3914 				return 1;
3915 			vcpu->arch.ia32_misc_enable_msr = data;
3916 			vcpu->arch.cpuid_dynamic_bits_dirty = true;
3917 		} else {
3918 			vcpu->arch.ia32_misc_enable_msr = data;
3919 		}
3920 		break;
3921 	}
3922 	case MSR_IA32_SMBASE:
3923 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
3924 			return 1;
3925 		vcpu->arch.smbase = data;
3926 		break;
3927 	case MSR_IA32_POWER_CTL:
3928 		vcpu->arch.msr_ia32_power_ctl = data;
3929 		break;
3930 	case MSR_IA32_TSC:
3931 		if (msr_info->host_initiated) {
3932 			kvm_synchronize_tsc(vcpu, &data);
3933 		} else if (!vcpu->arch.guest_tsc_protected) {
3934 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3935 			adjust_tsc_offset_guest(vcpu, adj);
3936 			vcpu->arch.ia32_tsc_adjust_msr += adj;
3937 		}
3938 		break;
3939 	case MSR_IA32_XSS:
3940 		if (!msr_info->host_initiated &&
3941 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3942 			return 1;
3943 		/*
3944 		 * KVM supports exposing PT to the guest, but does not support
3945 		 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3946 		 * XSAVES/XRSTORS to save/restore PT MSRs.
3947 		 */
3948 		if (data & ~kvm_caps.supported_xss)
3949 			return 1;
3950 		vcpu->arch.ia32_xss = data;
3951 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
3952 		break;
3953 	case MSR_SMI_COUNT:
3954 		if (!msr_info->host_initiated)
3955 			return 1;
3956 		vcpu->arch.smi_count = data;
3957 		break;
3958 	case MSR_KVM_WALL_CLOCK_NEW:
3959 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3960 			return 1;
3961 
3962 		vcpu->kvm->arch.wall_clock = data;
3963 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3964 		break;
3965 	case MSR_KVM_WALL_CLOCK:
3966 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3967 			return 1;
3968 
3969 		vcpu->kvm->arch.wall_clock = data;
3970 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3971 		break;
3972 	case MSR_KVM_SYSTEM_TIME_NEW:
3973 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3974 			return 1;
3975 
3976 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3977 		break;
3978 	case MSR_KVM_SYSTEM_TIME:
3979 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3980 			return 1;
3981 
3982 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
3983 		break;
3984 	case MSR_KVM_ASYNC_PF_EN:
3985 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3986 			return 1;
3987 
3988 		if (kvm_pv_enable_async_pf(vcpu, data))
3989 			return 1;
3990 		break;
3991 	case MSR_KVM_ASYNC_PF_INT:
3992 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3993 			return 1;
3994 
3995 		if (kvm_pv_enable_async_pf_int(vcpu, data))
3996 			return 1;
3997 		break;
3998 	case MSR_KVM_ASYNC_PF_ACK:
3999 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4000 			return 1;
4001 		if (data & 0x1) {
4002 			vcpu->arch.apf.pageready_pending = false;
4003 			kvm_check_async_pf_completion(vcpu);
4004 		}
4005 		break;
4006 	case MSR_KVM_STEAL_TIME:
4007 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4008 			return 1;
4009 
4010 		if (unlikely(!sched_info_on()))
4011 			return 1;
4012 
4013 		if (data & KVM_STEAL_RESERVED_MASK)
4014 			return 1;
4015 
4016 		vcpu->arch.st.msr_val = data;
4017 
4018 		if (!(data & KVM_MSR_ENABLED))
4019 			break;
4020 
4021 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4022 
4023 		break;
4024 	case MSR_KVM_PV_EOI_EN:
4025 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4026 			return 1;
4027 
4028 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4029 			return 1;
4030 		break;
4031 
4032 	case MSR_KVM_POLL_CONTROL:
4033 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4034 			return 1;
4035 
4036 		/* only enable bit supported */
4037 		if (data & (-1ULL << 1))
4038 			return 1;
4039 
4040 		vcpu->arch.msr_kvm_poll_control = data;
4041 		break;
4042 
4043 	case MSR_IA32_MCG_CTL:
4044 	case MSR_IA32_MCG_STATUS:
4045 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4046 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4047 		return set_msr_mce(vcpu, msr_info);
4048 
4049 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4050 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4051 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4052 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4053 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4054 			return kvm_pmu_set_msr(vcpu, msr_info);
4055 
4056 		if (data)
4057 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4058 		break;
4059 	case MSR_K7_CLK_CTL:
4060 		/*
4061 		 * Ignore all writes to this no longer documented MSR.
4062 		 * Writes are only relevant for old K7 processors,
4063 		 * all pre-dating SVM, but a recommended workaround from
4064 		 * AMD for these chips. It is possible to specify the
4065 		 * affected processor models on the command line, hence
4066 		 * the need to ignore the workaround.
4067 		 */
4068 		break;
4069 #ifdef CONFIG_KVM_HYPERV
4070 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4071 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4072 	case HV_X64_MSR_SYNDBG_OPTIONS:
4073 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4074 	case HV_X64_MSR_CRASH_CTL:
4075 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4076 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4077 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4078 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4079 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4080 		return kvm_hv_set_msr_common(vcpu, msr, data,
4081 					     msr_info->host_initiated);
4082 #endif
4083 	case MSR_IA32_BBL_CR_CTL3:
4084 		/* Drop writes to this legacy MSR -- see rdmsr
4085 		 * counterpart for further detail.
4086 		 */
4087 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4088 		break;
4089 	case MSR_AMD64_OSVW_ID_LENGTH:
4090 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4091 			return 1;
4092 		vcpu->arch.osvw.length = data;
4093 		break;
4094 	case MSR_AMD64_OSVW_STATUS:
4095 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4096 			return 1;
4097 		vcpu->arch.osvw.status = data;
4098 		break;
4099 	case MSR_PLATFORM_INFO:
4100 		if (!msr_info->host_initiated)
4101 			return 1;
4102 		vcpu->arch.msr_platform_info = data;
4103 		break;
4104 	case MSR_MISC_FEATURES_ENABLES:
4105 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4106 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4107 		     !supports_cpuid_fault(vcpu)))
4108 			return 1;
4109 		vcpu->arch.msr_misc_features_enables = data;
4110 		break;
4111 #ifdef CONFIG_X86_64
4112 	case MSR_IA32_XFD:
4113 		if (!msr_info->host_initiated &&
4114 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4115 			return 1;
4116 
4117 		if (data & ~kvm_guest_supported_xfd(vcpu))
4118 			return 1;
4119 
4120 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4121 		break;
4122 	case MSR_IA32_XFD_ERR:
4123 		if (!msr_info->host_initiated &&
4124 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4125 			return 1;
4126 
4127 		if (data & ~kvm_guest_supported_xfd(vcpu))
4128 			return 1;
4129 
4130 		vcpu->arch.guest_fpu.xfd_err = data;
4131 		break;
4132 #endif
4133 	default:
4134 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4135 			return kvm_pmu_set_msr(vcpu, msr_info);
4136 
4137 		return KVM_MSR_RET_UNSUPPORTED;
4138 	}
4139 	return 0;
4140 }
4141 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4142 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4143 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4144 {
4145 	u64 data;
4146 	u64 mcg_cap = vcpu->arch.mcg_cap;
4147 	unsigned bank_num = mcg_cap & 0xff;
4148 	u32 offset, last_msr;
4149 
4150 	switch (msr) {
4151 	case MSR_IA32_P5_MC_ADDR:
4152 	case MSR_IA32_P5_MC_TYPE:
4153 		data = 0;
4154 		break;
4155 	case MSR_IA32_MCG_CAP:
4156 		data = vcpu->arch.mcg_cap;
4157 		break;
4158 	case MSR_IA32_MCG_CTL:
4159 		if (!(mcg_cap & MCG_CTL_P) && !host)
4160 			return 1;
4161 		data = vcpu->arch.mcg_ctl;
4162 		break;
4163 	case MSR_IA32_MCG_STATUS:
4164 		data = vcpu->arch.mcg_status;
4165 		break;
4166 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4167 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4168 		if (msr > last_msr)
4169 			return 1;
4170 
4171 		if (!(mcg_cap & MCG_CMCI_P) && !host)
4172 			return 1;
4173 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4174 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
4175 		data = vcpu->arch.mci_ctl2_banks[offset];
4176 		break;
4177 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4178 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4179 		if (msr > last_msr)
4180 			return 1;
4181 
4182 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4183 					    last_msr + 1 - MSR_IA32_MC0_CTL);
4184 		data = vcpu->arch.mce_banks[offset];
4185 		break;
4186 	default:
4187 		return 1;
4188 	}
4189 	*pdata = data;
4190 	return 0;
4191 }
4192 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4193 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4194 {
4195 	switch (msr_info->index) {
4196 	case MSR_IA32_PLATFORM_ID:
4197 	case MSR_IA32_EBL_CR_POWERON:
4198 	case MSR_IA32_LASTBRANCHFROMIP:
4199 	case MSR_IA32_LASTBRANCHTOIP:
4200 	case MSR_IA32_LASTINTFROMIP:
4201 	case MSR_IA32_LASTINTTOIP:
4202 	case MSR_AMD64_SYSCFG:
4203 	case MSR_K8_TSEG_ADDR:
4204 	case MSR_K8_TSEG_MASK:
4205 	case MSR_VM_HSAVE_PA:
4206 	case MSR_K8_INT_PENDING_MSG:
4207 	case MSR_AMD64_NB_CFG:
4208 	case MSR_FAM10H_MMIO_CONF_BASE:
4209 	case MSR_AMD64_BU_CFG2:
4210 	case MSR_IA32_PERF_CTL:
4211 	case MSR_AMD64_DC_CFG:
4212 	case MSR_AMD64_TW_CFG:
4213 	case MSR_F15H_EX_CFG:
4214 	/*
4215 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4216 	 * limit) MSRs. Just return 0, as we do not want to expose the host
4217 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
4218 	 * so for existing CPU-specific MSRs.
4219 	 */
4220 	case MSR_RAPL_POWER_UNIT:
4221 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
4222 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
4223 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
4224 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
4225 		msr_info->data = 0;
4226 		break;
4227 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4228 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4229 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4230 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4231 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4232 			return kvm_pmu_get_msr(vcpu, msr_info);
4233 		msr_info->data = 0;
4234 		break;
4235 	case MSR_IA32_UCODE_REV:
4236 		msr_info->data = vcpu->arch.microcode_version;
4237 		break;
4238 	case MSR_IA32_ARCH_CAPABILITIES:
4239 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4240 			return KVM_MSR_RET_UNSUPPORTED;
4241 		msr_info->data = vcpu->arch.arch_capabilities;
4242 		break;
4243 	case MSR_IA32_PERF_CAPABILITIES:
4244 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4245 			return KVM_MSR_RET_UNSUPPORTED;
4246 		msr_info->data = vcpu->arch.perf_capabilities;
4247 		break;
4248 	case MSR_IA32_POWER_CTL:
4249 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4250 		break;
4251 	case MSR_IA32_TSC: {
4252 		/*
4253 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4254 		 * even when not intercepted. AMD manual doesn't explicitly
4255 		 * state this but appears to behave the same.
4256 		 *
4257 		 * On userspace reads and writes, however, we unconditionally
4258 		 * return L1's TSC value to ensure backwards-compatible
4259 		 * behavior for migration.
4260 		 */
4261 		u64 offset, ratio;
4262 
4263 		if (msr_info->host_initiated) {
4264 			offset = vcpu->arch.l1_tsc_offset;
4265 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
4266 		} else {
4267 			offset = vcpu->arch.tsc_offset;
4268 			ratio = vcpu->arch.tsc_scaling_ratio;
4269 		}
4270 
4271 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4272 		break;
4273 	}
4274 	case MSR_IA32_CR_PAT:
4275 		msr_info->data = vcpu->arch.pat;
4276 		break;
4277 	case MSR_MTRRcap:
4278 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4279 	case MSR_MTRRdefType:
4280 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4281 	case 0xcd: /* fsb frequency */
4282 		msr_info->data = 3;
4283 		break;
4284 		/*
4285 		 * MSR_EBC_FREQUENCY_ID
4286 		 * Conservative value valid for even the basic CPU models.
4287 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4288 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4289 		 * and 266MHz for model 3, or 4. Set Core Clock
4290 		 * Frequency to System Bus Frequency Ratio to 1 (bits
4291 		 * 31:24) even though these are only valid for CPU
4292 		 * models > 2, however guests may end up dividing or
4293 		 * multiplying by zero otherwise.
4294 		 */
4295 	case MSR_EBC_FREQUENCY_ID:
4296 		msr_info->data = 1 << 24;
4297 		break;
4298 	case MSR_IA32_APICBASE:
4299 		msr_info->data = vcpu->arch.apic_base;
4300 		break;
4301 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4302 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4303 	case MSR_IA32_TSC_DEADLINE:
4304 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4305 		break;
4306 	case MSR_IA32_TSC_ADJUST:
4307 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4308 		break;
4309 	case MSR_IA32_MISC_ENABLE:
4310 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4311 		break;
4312 	case MSR_IA32_SMBASE:
4313 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4314 			return 1;
4315 		msr_info->data = vcpu->arch.smbase;
4316 		break;
4317 	case MSR_SMI_COUNT:
4318 		msr_info->data = vcpu->arch.smi_count;
4319 		break;
4320 	case MSR_IA32_PERF_STATUS:
4321 		/* TSC increment by tick */
4322 		msr_info->data = 1000ULL;
4323 		/* CPU multiplier */
4324 		msr_info->data |= (((uint64_t)4ULL) << 40);
4325 		break;
4326 	case MSR_EFER:
4327 		msr_info->data = vcpu->arch.efer;
4328 		break;
4329 	case MSR_KVM_WALL_CLOCK:
4330 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4331 			return 1;
4332 
4333 		msr_info->data = vcpu->kvm->arch.wall_clock;
4334 		break;
4335 	case MSR_KVM_WALL_CLOCK_NEW:
4336 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4337 			return 1;
4338 
4339 		msr_info->data = vcpu->kvm->arch.wall_clock;
4340 		break;
4341 	case MSR_KVM_SYSTEM_TIME:
4342 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4343 			return 1;
4344 
4345 		msr_info->data = vcpu->arch.time;
4346 		break;
4347 	case MSR_KVM_SYSTEM_TIME_NEW:
4348 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4349 			return 1;
4350 
4351 		msr_info->data = vcpu->arch.time;
4352 		break;
4353 	case MSR_KVM_ASYNC_PF_EN:
4354 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4355 			return 1;
4356 
4357 		msr_info->data = vcpu->arch.apf.msr_en_val;
4358 		break;
4359 	case MSR_KVM_ASYNC_PF_INT:
4360 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4361 			return 1;
4362 
4363 		msr_info->data = vcpu->arch.apf.msr_int_val;
4364 		break;
4365 	case MSR_KVM_ASYNC_PF_ACK:
4366 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4367 			return 1;
4368 
4369 		msr_info->data = 0;
4370 		break;
4371 	case MSR_KVM_STEAL_TIME:
4372 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4373 			return 1;
4374 
4375 		msr_info->data = vcpu->arch.st.msr_val;
4376 		break;
4377 	case MSR_KVM_PV_EOI_EN:
4378 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4379 			return 1;
4380 
4381 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4382 		break;
4383 	case MSR_KVM_POLL_CONTROL:
4384 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4385 			return 1;
4386 
4387 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4388 		break;
4389 	case MSR_IA32_P5_MC_ADDR:
4390 	case MSR_IA32_P5_MC_TYPE:
4391 	case MSR_IA32_MCG_CAP:
4392 	case MSR_IA32_MCG_CTL:
4393 	case MSR_IA32_MCG_STATUS:
4394 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4395 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4396 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4397 				   msr_info->host_initiated);
4398 	case MSR_IA32_XSS:
4399 		if (!msr_info->host_initiated &&
4400 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4401 			return 1;
4402 		msr_info->data = vcpu->arch.ia32_xss;
4403 		break;
4404 	case MSR_K7_CLK_CTL:
4405 		/*
4406 		 * Provide expected ramp-up count for K7. All other
4407 		 * are set to zero, indicating minimum divisors for
4408 		 * every field.
4409 		 *
4410 		 * This prevents guest kernels on AMD host with CPU
4411 		 * type 6, model 8 and higher from exploding due to
4412 		 * the rdmsr failing.
4413 		 */
4414 		msr_info->data = 0x20000000;
4415 		break;
4416 #ifdef CONFIG_KVM_HYPERV
4417 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4418 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4419 	case HV_X64_MSR_SYNDBG_OPTIONS:
4420 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4421 	case HV_X64_MSR_CRASH_CTL:
4422 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4423 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4424 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4425 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4426 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4427 		return kvm_hv_get_msr_common(vcpu,
4428 					     msr_info->index, &msr_info->data,
4429 					     msr_info->host_initiated);
4430 #endif
4431 	case MSR_IA32_BBL_CR_CTL3:
4432 		/* This legacy MSR exists but isn't fully documented in current
4433 		 * silicon.  It is however accessed by winxp in very narrow
4434 		 * scenarios where it sets bit #19, itself documented as
4435 		 * a "reserved" bit.  Best effort attempt to source coherent
4436 		 * read data here should the balance of the register be
4437 		 * interpreted by the guest:
4438 		 *
4439 		 * L2 cache control register 3: 64GB range, 256KB size,
4440 		 * enabled, latency 0x1, configured
4441 		 */
4442 		msr_info->data = 0xbe702111;
4443 		break;
4444 	case MSR_AMD64_OSVW_ID_LENGTH:
4445 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4446 			return 1;
4447 		msr_info->data = vcpu->arch.osvw.length;
4448 		break;
4449 	case MSR_AMD64_OSVW_STATUS:
4450 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4451 			return 1;
4452 		msr_info->data = vcpu->arch.osvw.status;
4453 		break;
4454 	case MSR_PLATFORM_INFO:
4455 		if (!msr_info->host_initiated &&
4456 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4457 			return 1;
4458 		msr_info->data = vcpu->arch.msr_platform_info;
4459 		break;
4460 	case MSR_MISC_FEATURES_ENABLES:
4461 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4462 		break;
4463 	case MSR_K7_HWCR:
4464 		msr_info->data = vcpu->arch.msr_hwcr;
4465 		break;
4466 #ifdef CONFIG_X86_64
4467 	case MSR_IA32_XFD:
4468 		if (!msr_info->host_initiated &&
4469 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4470 			return 1;
4471 
4472 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4473 		break;
4474 	case MSR_IA32_XFD_ERR:
4475 		if (!msr_info->host_initiated &&
4476 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4477 			return 1;
4478 
4479 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4480 		break;
4481 #endif
4482 	default:
4483 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4484 			return kvm_pmu_get_msr(vcpu, msr_info);
4485 
4486 		return KVM_MSR_RET_UNSUPPORTED;
4487 	}
4488 	return 0;
4489 }
4490 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4491 
4492 /*
4493  * Read or write a bunch of msrs. All parameters are kernel addresses.
4494  *
4495  * @return number of msrs set successfully.
4496  */
__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))4497 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4498 		    struct kvm_msr_entry *entries,
4499 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4500 				  unsigned index, u64 *data))
4501 {
4502 	int i;
4503 
4504 	for (i = 0; i < msrs->nmsrs; ++i)
4505 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4506 			break;
4507 
4508 	return i;
4509 }
4510 
4511 /*
4512  * Read or write a bunch of msrs. Parameters are user addresses.
4513  *
4514  * @return number of msrs set successfully.
4515  */
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)4516 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4517 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4518 				unsigned index, u64 *data),
4519 		  int writeback)
4520 {
4521 	struct kvm_msrs msrs;
4522 	struct kvm_msr_entry *entries;
4523 	unsigned size;
4524 	int r;
4525 
4526 	r = -EFAULT;
4527 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4528 		goto out;
4529 
4530 	r = -E2BIG;
4531 	if (msrs.nmsrs >= MAX_IO_MSRS)
4532 		goto out;
4533 
4534 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4535 	entries = memdup_user(user_msrs->entries, size);
4536 	if (IS_ERR(entries)) {
4537 		r = PTR_ERR(entries);
4538 		goto out;
4539 	}
4540 
4541 	r = __msr_io(vcpu, &msrs, entries, do_msr);
4542 
4543 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4544 		r = -EFAULT;
4545 
4546 	kfree(entries);
4547 out:
4548 	return r;
4549 }
4550 
kvm_can_mwait_in_guest(void)4551 static inline bool kvm_can_mwait_in_guest(void)
4552 {
4553 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4554 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4555 		boot_cpu_has(X86_FEATURE_ARAT);
4556 }
4557 
kvm_get_allowed_disable_exits(void)4558 static u64 kvm_get_allowed_disable_exits(void)
4559 {
4560 	u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4561 
4562 	if (!mitigate_smt_rsb) {
4563 		r |= KVM_X86_DISABLE_EXITS_HLT |
4564 			KVM_X86_DISABLE_EXITS_CSTATE;
4565 
4566 		if (kvm_can_mwait_in_guest())
4567 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
4568 	}
4569 	return r;
4570 }
4571 
4572 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4573 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4574 					    struct kvm_cpuid2 __user *cpuid_arg)
4575 {
4576 	struct kvm_cpuid2 cpuid;
4577 	int r;
4578 
4579 	r = -EFAULT;
4580 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4581 		return r;
4582 
4583 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4584 	if (r)
4585 		return r;
4586 
4587 	r = -EFAULT;
4588 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4589 		return r;
4590 
4591 	return 0;
4592 }
4593 #endif
4594 
kvm_is_vm_type_supported(unsigned long type)4595 static bool kvm_is_vm_type_supported(unsigned long type)
4596 {
4597 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4598 }
4599 
kvm_sync_valid_fields(struct kvm * kvm)4600 static inline u32 kvm_sync_valid_fields(struct kvm *kvm)
4601 {
4602 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4603 }
4604 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4605 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4606 {
4607 	int r = 0;
4608 
4609 	switch (ext) {
4610 	case KVM_CAP_IRQCHIP:
4611 	case KVM_CAP_HLT:
4612 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4613 	case KVM_CAP_SET_TSS_ADDR:
4614 	case KVM_CAP_EXT_CPUID:
4615 	case KVM_CAP_EXT_EMUL_CPUID:
4616 	case KVM_CAP_CLOCKSOURCE:
4617 	case KVM_CAP_PIT:
4618 	case KVM_CAP_NOP_IO_DELAY:
4619 	case KVM_CAP_MP_STATE:
4620 	case KVM_CAP_SYNC_MMU:
4621 	case KVM_CAP_USER_NMI:
4622 	case KVM_CAP_REINJECT_CONTROL:
4623 	case KVM_CAP_IRQ_INJECT_STATUS:
4624 	case KVM_CAP_IOEVENTFD:
4625 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4626 	case KVM_CAP_PIT2:
4627 	case KVM_CAP_PIT_STATE2:
4628 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4629 	case KVM_CAP_VCPU_EVENTS:
4630 #ifdef CONFIG_KVM_HYPERV
4631 	case KVM_CAP_HYPERV:
4632 	case KVM_CAP_HYPERV_VAPIC:
4633 	case KVM_CAP_HYPERV_SPIN:
4634 	case KVM_CAP_HYPERV_TIME:
4635 	case KVM_CAP_HYPERV_SYNIC:
4636 	case KVM_CAP_HYPERV_SYNIC2:
4637 	case KVM_CAP_HYPERV_VP_INDEX:
4638 	case KVM_CAP_HYPERV_EVENTFD:
4639 	case KVM_CAP_HYPERV_TLBFLUSH:
4640 	case KVM_CAP_HYPERV_SEND_IPI:
4641 	case KVM_CAP_HYPERV_CPUID:
4642 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4643 	case KVM_CAP_SYS_HYPERV_CPUID:
4644 #endif
4645 	case KVM_CAP_PCI_SEGMENT:
4646 	case KVM_CAP_DEBUGREGS:
4647 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4648 	case KVM_CAP_XSAVE:
4649 	case KVM_CAP_ASYNC_PF:
4650 	case KVM_CAP_ASYNC_PF_INT:
4651 	case KVM_CAP_GET_TSC_KHZ:
4652 	case KVM_CAP_KVMCLOCK_CTRL:
4653 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4654 	case KVM_CAP_TSC_DEADLINE_TIMER:
4655 	case KVM_CAP_DISABLE_QUIRKS:
4656 	case KVM_CAP_SET_BOOT_CPU_ID:
4657  	case KVM_CAP_SPLIT_IRQCHIP:
4658 	case KVM_CAP_IMMEDIATE_EXIT:
4659 	case KVM_CAP_PMU_EVENT_FILTER:
4660 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4661 	case KVM_CAP_GET_MSR_FEATURES:
4662 	case KVM_CAP_MSR_PLATFORM_INFO:
4663 	case KVM_CAP_EXCEPTION_PAYLOAD:
4664 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4665 	case KVM_CAP_SET_GUEST_DEBUG:
4666 	case KVM_CAP_LAST_CPU:
4667 	case KVM_CAP_X86_USER_SPACE_MSR:
4668 	case KVM_CAP_X86_MSR_FILTER:
4669 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4670 #ifdef CONFIG_X86_SGX_KVM
4671 	case KVM_CAP_SGX_ATTRIBUTE:
4672 #endif
4673 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4674 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4675 	case KVM_CAP_SREGS2:
4676 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4677 	case KVM_CAP_VCPU_ATTRIBUTES:
4678 	case KVM_CAP_SYS_ATTRIBUTES:
4679 	case KVM_CAP_VAPIC:
4680 	case KVM_CAP_ENABLE_CAP:
4681 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4682 	case KVM_CAP_IRQFD_RESAMPLE:
4683 	case KVM_CAP_MEMORY_FAULT_INFO:
4684 	case KVM_CAP_X86_GUEST_MODE:
4685 		r = 1;
4686 		break;
4687 	case KVM_CAP_PRE_FAULT_MEMORY:
4688 		r = tdp_enabled;
4689 		break;
4690 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4691 		r = APIC_BUS_CYCLE_NS_DEFAULT;
4692 		break;
4693 	case KVM_CAP_EXIT_HYPERCALL:
4694 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4695 		break;
4696 	case KVM_CAP_SET_GUEST_DEBUG2:
4697 		return KVM_GUESTDBG_VALID_MASK;
4698 #ifdef CONFIG_KVM_XEN
4699 	case KVM_CAP_XEN_HVM:
4700 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4701 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4702 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4703 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4704 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4705 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4706 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4707 		if (sched_info_on())
4708 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4709 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4710 		break;
4711 #endif
4712 	case KVM_CAP_SYNC_REGS:
4713 		r = kvm_sync_valid_fields(kvm);
4714 		break;
4715 	case KVM_CAP_ADJUST_CLOCK:
4716 		r = KVM_CLOCK_VALID_FLAGS;
4717 		break;
4718 	case KVM_CAP_X86_DISABLE_EXITS:
4719 		r = kvm_get_allowed_disable_exits();
4720 		break;
4721 	case KVM_CAP_X86_SMM:
4722 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4723 			break;
4724 
4725 		/* SMBASE is usually relocated above 1M on modern chipsets,
4726 		 * and SMM handlers might indeed rely on 4G segment limits,
4727 		 * so do not report SMM to be available if real mode is
4728 		 * emulated via vm86 mode.  Still, do not go to great lengths
4729 		 * to avoid userspace's usage of the feature, because it is a
4730 		 * fringe case that is not enabled except via specific settings
4731 		 * of the module parameters.
4732 		 */
4733 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4734 		break;
4735 	case KVM_CAP_NR_VCPUS:
4736 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4737 		break;
4738 	case KVM_CAP_MAX_VCPUS:
4739 		r = KVM_MAX_VCPUS;
4740 		break;
4741 	case KVM_CAP_MAX_VCPU_ID:
4742 		r = KVM_MAX_VCPU_IDS;
4743 		break;
4744 	case KVM_CAP_PV_MMU:	/* obsolete */
4745 		r = 0;
4746 		break;
4747 	case KVM_CAP_MCE:
4748 		r = KVM_MAX_MCE_BANKS;
4749 		break;
4750 	case KVM_CAP_XCRS:
4751 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4752 		break;
4753 	case KVM_CAP_TSC_CONTROL:
4754 	case KVM_CAP_VM_TSC_CONTROL:
4755 		r = kvm_caps.has_tsc_control;
4756 		break;
4757 	case KVM_CAP_X2APIC_API:
4758 		r = KVM_X2APIC_API_VALID_FLAGS;
4759 		break;
4760 	case KVM_CAP_NESTED_STATE:
4761 		r = kvm_x86_ops.nested_ops->get_state ?
4762 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4763 		break;
4764 #ifdef CONFIG_KVM_HYPERV
4765 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4766 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4767 		break;
4768 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4769 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4770 		break;
4771 #endif
4772 	case KVM_CAP_SMALLER_MAXPHYADDR:
4773 		r = (int) allow_smaller_maxphyaddr;
4774 		break;
4775 	case KVM_CAP_STEAL_TIME:
4776 		r = sched_info_on();
4777 		break;
4778 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4779 		if (kvm_caps.has_bus_lock_exit)
4780 			r = KVM_BUS_LOCK_DETECTION_OFF |
4781 			    KVM_BUS_LOCK_DETECTION_EXIT;
4782 		else
4783 			r = 0;
4784 		break;
4785 	case KVM_CAP_XSAVE2: {
4786 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4787 		if (r < sizeof(struct kvm_xsave))
4788 			r = sizeof(struct kvm_xsave);
4789 		break;
4790 	}
4791 	case KVM_CAP_PMU_CAPABILITY:
4792 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4793 		break;
4794 	case KVM_CAP_DISABLE_QUIRKS2:
4795 		r = KVM_X86_VALID_QUIRKS;
4796 		break;
4797 	case KVM_CAP_X86_NOTIFY_VMEXIT:
4798 		r = kvm_caps.has_notify_vmexit;
4799 		break;
4800 	case KVM_CAP_VM_TYPES:
4801 		r = kvm_caps.supported_vm_types;
4802 		break;
4803 	case KVM_CAP_READONLY_MEM:
4804 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4805 		break;
4806 	default:
4807 		break;
4808 	}
4809 	return r;
4810 }
4811 
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4812 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4813 {
4814 	if (attr->group) {
4815 		if (kvm_x86_ops.dev_get_attr)
4816 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4817 		return -ENXIO;
4818 	}
4819 
4820 	switch (attr->attr) {
4821 	case KVM_X86_XCOMP_GUEST_SUPP:
4822 		*val = kvm_caps.supported_xcr0;
4823 		return 0;
4824 	default:
4825 		return -ENXIO;
4826 	}
4827 }
4828 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)4829 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4830 {
4831 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4832 	int r;
4833 	u64 val;
4834 
4835 	r = __kvm_x86_dev_get_attr(attr, &val);
4836 	if (r < 0)
4837 		return r;
4838 
4839 	if (put_user(val, uaddr))
4840 		return -EFAULT;
4841 
4842 	return 0;
4843 }
4844 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)4845 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4846 {
4847 	u64 val;
4848 
4849 	return __kvm_x86_dev_get_attr(attr, &val);
4850 }
4851 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4852 long kvm_arch_dev_ioctl(struct file *filp,
4853 			unsigned int ioctl, unsigned long arg)
4854 {
4855 	void __user *argp = (void __user *)arg;
4856 	long r;
4857 
4858 	switch (ioctl) {
4859 	case KVM_GET_MSR_INDEX_LIST: {
4860 		struct kvm_msr_list __user *user_msr_list = argp;
4861 		struct kvm_msr_list msr_list;
4862 		unsigned n;
4863 
4864 		r = -EFAULT;
4865 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4866 			goto out;
4867 		n = msr_list.nmsrs;
4868 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4869 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4870 			goto out;
4871 		r = -E2BIG;
4872 		if (n < msr_list.nmsrs)
4873 			goto out;
4874 		r = -EFAULT;
4875 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4876 				 num_msrs_to_save * sizeof(u32)))
4877 			goto out;
4878 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4879 				 &emulated_msrs,
4880 				 num_emulated_msrs * sizeof(u32)))
4881 			goto out;
4882 		r = 0;
4883 		break;
4884 	}
4885 	case KVM_GET_SUPPORTED_CPUID:
4886 	case KVM_GET_EMULATED_CPUID: {
4887 		struct kvm_cpuid2 __user *cpuid_arg = argp;
4888 		struct kvm_cpuid2 cpuid;
4889 
4890 		r = -EFAULT;
4891 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4892 			goto out;
4893 
4894 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4895 					    ioctl);
4896 		if (r)
4897 			goto out;
4898 
4899 		r = -EFAULT;
4900 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4901 			goto out;
4902 		r = 0;
4903 		break;
4904 	}
4905 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
4906 		r = -EFAULT;
4907 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4908 				 sizeof(kvm_caps.supported_mce_cap)))
4909 			goto out;
4910 		r = 0;
4911 		break;
4912 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4913 		struct kvm_msr_list __user *user_msr_list = argp;
4914 		struct kvm_msr_list msr_list;
4915 		unsigned int n;
4916 
4917 		r = -EFAULT;
4918 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4919 			goto out;
4920 		n = msr_list.nmsrs;
4921 		msr_list.nmsrs = num_msr_based_features;
4922 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4923 			goto out;
4924 		r = -E2BIG;
4925 		if (n < msr_list.nmsrs)
4926 			goto out;
4927 		r = -EFAULT;
4928 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
4929 				 num_msr_based_features * sizeof(u32)))
4930 			goto out;
4931 		r = 0;
4932 		break;
4933 	}
4934 	case KVM_GET_MSRS:
4935 		r = msr_io(NULL, argp, do_get_feature_msr, 1);
4936 		break;
4937 #ifdef CONFIG_KVM_HYPERV
4938 	case KVM_GET_SUPPORTED_HV_CPUID:
4939 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4940 		break;
4941 #endif
4942 	case KVM_GET_DEVICE_ATTR: {
4943 		struct kvm_device_attr attr;
4944 		r = -EFAULT;
4945 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4946 			break;
4947 		r = kvm_x86_dev_get_attr(&attr);
4948 		break;
4949 	}
4950 	case KVM_HAS_DEVICE_ATTR: {
4951 		struct kvm_device_attr attr;
4952 		r = -EFAULT;
4953 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4954 			break;
4955 		r = kvm_x86_dev_has_attr(&attr);
4956 		break;
4957 	}
4958 	default:
4959 		r = -EINVAL;
4960 		break;
4961 	}
4962 out:
4963 	return r;
4964 }
4965 
wbinvd_ipi(void * garbage)4966 static void wbinvd_ipi(void *garbage)
4967 {
4968 	wbinvd();
4969 }
4970 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)4971 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4972 {
4973 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4974 }
4975 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)4976 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4977 {
4978 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
4979 
4980 	vcpu->arch.l1tf_flush_l1d = true;
4981 
4982 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
4983 		pmu->need_cleanup = true;
4984 		kvm_make_request(KVM_REQ_PMU, vcpu);
4985 	}
4986 
4987 	/* Address WBINVD may be executed by guest */
4988 	if (need_emulate_wbinvd(vcpu)) {
4989 		if (kvm_x86_call(has_wbinvd_exit)())
4990 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4991 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4992 			smp_call_function_single(vcpu->cpu,
4993 					wbinvd_ipi, NULL, 1);
4994 	}
4995 
4996 	kvm_x86_call(vcpu_load)(vcpu, cpu);
4997 
4998 	/* Save host pkru register if supported */
4999 	vcpu->arch.host_pkru = read_pkru();
5000 
5001 	/* Apply any externally detected TSC adjustments (due to suspend) */
5002 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5003 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5004 		vcpu->arch.tsc_offset_adjustment = 0;
5005 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5006 	}
5007 
5008 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5009 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5010 				rdtsc() - vcpu->arch.last_host_tsc;
5011 		if (tsc_delta < 0)
5012 			mark_tsc_unstable("KVM discovered backwards TSC");
5013 
5014 		if (kvm_check_tsc_unstable()) {
5015 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5016 						vcpu->arch.last_guest_tsc);
5017 			kvm_vcpu_write_tsc_offset(vcpu, offset);
5018 			if (!vcpu->arch.guest_tsc_protected)
5019 				vcpu->arch.tsc_catchup = 1;
5020 		}
5021 
5022 		if (kvm_lapic_hv_timer_in_use(vcpu))
5023 			kvm_lapic_restart_hv_timer(vcpu);
5024 
5025 		/*
5026 		 * On a host with synchronized TSC, there is no need to update
5027 		 * kvmclock on vcpu->cpu migration
5028 		 */
5029 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5030 			kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5031 		if (vcpu->cpu != cpu)
5032 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5033 		vcpu->cpu = cpu;
5034 	}
5035 
5036 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5037 }
5038 
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5039 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5040 {
5041 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5042 	struct kvm_steal_time __user *st;
5043 	struct kvm_memslots *slots;
5044 	static const u8 preempted = KVM_VCPU_PREEMPTED;
5045 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5046 
5047 	/*
5048 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
5049 	 * an instruction boundary and will not trigger guest emulation of any
5050 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
5051 	 * when this is true, for example allowing the vCPU to be marked
5052 	 * preempted if and only if the VM-Exit was due to a host interrupt.
5053 	 */
5054 	if (!vcpu->arch.at_instruction_boundary) {
5055 		vcpu->stat.preemption_other++;
5056 		return;
5057 	}
5058 
5059 	vcpu->stat.preemption_reported++;
5060 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5061 		return;
5062 
5063 	if (vcpu->arch.st.preempted)
5064 		return;
5065 
5066 	/* This happens on process exit */
5067 	if (unlikely(current->mm != vcpu->kvm->mm))
5068 		return;
5069 
5070 	slots = kvm_memslots(vcpu->kvm);
5071 
5072 	if (unlikely(slots->generation != ghc->generation ||
5073 		     gpa != ghc->gpa ||
5074 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5075 		return;
5076 
5077 	st = (struct kvm_steal_time __user *)ghc->hva;
5078 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5079 
5080 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5081 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5082 
5083 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5084 }
5085 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5086 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5087 {
5088 	int idx;
5089 
5090 	if (vcpu->preempted) {
5091 		/*
5092 		 * Assume protected guests are in-kernel.  Inefficient yielding
5093 		 * due to false positives is preferable to never yielding due
5094 		 * to false negatives.
5095 		 */
5096 		vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5097 						 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5098 
5099 		/*
5100 		 * Take the srcu lock as memslots will be accessed to check the gfn
5101 		 * cache generation against the memslots generation.
5102 		 */
5103 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5104 		if (kvm_xen_msr_enabled(vcpu->kvm))
5105 			kvm_xen_runstate_set_preempted(vcpu);
5106 		else
5107 			kvm_steal_time_set_preempted(vcpu);
5108 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5109 	}
5110 
5111 	kvm_x86_call(vcpu_put)(vcpu);
5112 	vcpu->arch.last_host_tsc = rdtsc();
5113 }
5114 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5115 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5116 				    struct kvm_lapic_state *s)
5117 {
5118 	kvm_x86_call(sync_pir_to_irr)(vcpu);
5119 
5120 	return kvm_apic_get_state(vcpu, s);
5121 }
5122 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5123 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5124 				    struct kvm_lapic_state *s)
5125 {
5126 	int r;
5127 
5128 	r = kvm_apic_set_state(vcpu, s);
5129 	if (r)
5130 		return r;
5131 	update_cr8_intercept(vcpu);
5132 
5133 	return 0;
5134 }
5135 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5136 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5137 {
5138 	/*
5139 	 * We can accept userspace's request for interrupt injection
5140 	 * as long as we have a place to store the interrupt number.
5141 	 * The actual injection will happen when the CPU is able to
5142 	 * deliver the interrupt.
5143 	 */
5144 	if (kvm_cpu_has_extint(vcpu))
5145 		return false;
5146 
5147 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
5148 	return (!lapic_in_kernel(vcpu) ||
5149 		kvm_apic_accept_pic_intr(vcpu));
5150 }
5151 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5152 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5153 {
5154 	/*
5155 	 * Do not cause an interrupt window exit if an exception
5156 	 * is pending or an event needs reinjection; userspace
5157 	 * might want to inject the interrupt manually using KVM_SET_REGS
5158 	 * or KVM_SET_SREGS.  For that to work, we must be at an
5159 	 * instruction boundary and with no events half-injected.
5160 	 */
5161 	return (kvm_arch_interrupt_allowed(vcpu) &&
5162 		kvm_cpu_accept_dm_intr(vcpu) &&
5163 		!kvm_event_needs_reinjection(vcpu) &&
5164 		!kvm_is_exception_pending(vcpu));
5165 }
5166 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5167 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5168 				    struct kvm_interrupt *irq)
5169 {
5170 	if (irq->irq >= KVM_NR_INTERRUPTS)
5171 		return -EINVAL;
5172 
5173 	if (!irqchip_in_kernel(vcpu->kvm)) {
5174 		kvm_queue_interrupt(vcpu, irq->irq, false);
5175 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5176 		return 0;
5177 	}
5178 
5179 	/*
5180 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5181 	 * fail for in-kernel 8259.
5182 	 */
5183 	if (pic_in_kernel(vcpu->kvm))
5184 		return -ENXIO;
5185 
5186 	if (vcpu->arch.pending_external_vector != -1)
5187 		return -EEXIST;
5188 
5189 	vcpu->arch.pending_external_vector = irq->irq;
5190 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5191 	return 0;
5192 }
5193 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5194 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5195 {
5196 	kvm_inject_nmi(vcpu);
5197 
5198 	return 0;
5199 }
5200 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5201 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5202 					   struct kvm_tpr_access_ctl *tac)
5203 {
5204 	if (tac->flags)
5205 		return -EINVAL;
5206 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
5207 	return 0;
5208 }
5209 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5210 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5211 					u64 mcg_cap)
5212 {
5213 	int r;
5214 	unsigned bank_num = mcg_cap & 0xff, bank;
5215 
5216 	r = -EINVAL;
5217 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5218 		goto out;
5219 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5220 		goto out;
5221 	r = 0;
5222 	vcpu->arch.mcg_cap = mcg_cap;
5223 	/* Init IA32_MCG_CTL to all 1s */
5224 	if (mcg_cap & MCG_CTL_P)
5225 		vcpu->arch.mcg_ctl = ~(u64)0;
5226 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5227 	for (bank = 0; bank < bank_num; bank++) {
5228 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5229 		if (mcg_cap & MCG_CMCI_P)
5230 			vcpu->arch.mci_ctl2_banks[bank] = 0;
5231 	}
5232 
5233 	kvm_apic_after_set_mcg_cap(vcpu);
5234 
5235 	kvm_x86_call(setup_mce)(vcpu);
5236 out:
5237 	return r;
5238 }
5239 
5240 /*
5241  * Validate this is an UCNA (uncorrectable no action) error by checking the
5242  * MCG_STATUS and MCi_STATUS registers:
5243  * - none of the bits for Machine Check Exceptions are set
5244  * - both the VAL (valid) and UC (uncorrectable) bits are set
5245  * MCI_STATUS_PCC - Processor Context Corrupted
5246  * MCI_STATUS_S - Signaled as a Machine Check Exception
5247  * MCI_STATUS_AR - Software recoverable Action Required
5248  */
is_ucna(struct kvm_x86_mce * mce)5249 static bool is_ucna(struct kvm_x86_mce *mce)
5250 {
5251 	return	!mce->mcg_status &&
5252 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5253 		(mce->status & MCI_STATUS_VAL) &&
5254 		(mce->status & MCI_STATUS_UC);
5255 }
5256 
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5257 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5258 {
5259 	u64 mcg_cap = vcpu->arch.mcg_cap;
5260 
5261 	banks[1] = mce->status;
5262 	banks[2] = mce->addr;
5263 	banks[3] = mce->misc;
5264 	vcpu->arch.mcg_status = mce->mcg_status;
5265 
5266 	if (!(mcg_cap & MCG_CMCI_P) ||
5267 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5268 		return 0;
5269 
5270 	if (lapic_in_kernel(vcpu))
5271 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5272 
5273 	return 0;
5274 }
5275 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5276 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5277 				      struct kvm_x86_mce *mce)
5278 {
5279 	u64 mcg_cap = vcpu->arch.mcg_cap;
5280 	unsigned bank_num = mcg_cap & 0xff;
5281 	u64 *banks = vcpu->arch.mce_banks;
5282 
5283 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5284 		return -EINVAL;
5285 
5286 	banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5287 
5288 	if (is_ucna(mce))
5289 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5290 
5291 	/*
5292 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5293 	 * reporting is disabled
5294 	 */
5295 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5296 	    vcpu->arch.mcg_ctl != ~(u64)0)
5297 		return 0;
5298 	/*
5299 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5300 	 * reporting is disabled for the bank
5301 	 */
5302 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5303 		return 0;
5304 	if (mce->status & MCI_STATUS_UC) {
5305 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5306 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5307 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5308 			return 0;
5309 		}
5310 		if (banks[1] & MCI_STATUS_VAL)
5311 			mce->status |= MCI_STATUS_OVER;
5312 		banks[2] = mce->addr;
5313 		banks[3] = mce->misc;
5314 		vcpu->arch.mcg_status = mce->mcg_status;
5315 		banks[1] = mce->status;
5316 		kvm_queue_exception(vcpu, MC_VECTOR);
5317 	} else if (!(banks[1] & MCI_STATUS_VAL)
5318 		   || !(banks[1] & MCI_STATUS_UC)) {
5319 		if (banks[1] & MCI_STATUS_VAL)
5320 			mce->status |= MCI_STATUS_OVER;
5321 		banks[2] = mce->addr;
5322 		banks[3] = mce->misc;
5323 		banks[1] = mce->status;
5324 	} else
5325 		banks[1] |= MCI_STATUS_OVER;
5326 	return 0;
5327 }
5328 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5329 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5330 					       struct kvm_vcpu_events *events)
5331 {
5332 	struct kvm_queued_exception *ex;
5333 
5334 	process_nmi(vcpu);
5335 
5336 #ifdef CONFIG_KVM_SMM
5337 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
5338 		process_smi(vcpu);
5339 #endif
5340 
5341 	/*
5342 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
5343 	 * the only time there can be two queued exceptions is if there's a
5344 	 * non-exiting _injected_ exception, and a pending exiting exception.
5345 	 * In that case, ignore the VM-Exiting exception as it's an extension
5346 	 * of the injected exception.
5347 	 */
5348 	if (vcpu->arch.exception_vmexit.pending &&
5349 	    !vcpu->arch.exception.pending &&
5350 	    !vcpu->arch.exception.injected)
5351 		ex = &vcpu->arch.exception_vmexit;
5352 	else
5353 		ex = &vcpu->arch.exception;
5354 
5355 	/*
5356 	 * In guest mode, payload delivery should be deferred if the exception
5357 	 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5358 	 * intercepts #PF, ditto for DR6 and #DBs.  If the per-VM capability,
5359 	 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5360 	 * propagate the payload and so it cannot be safely deferred.  Deliver
5361 	 * the payload if the capability hasn't been requested.
5362 	 */
5363 	if (!vcpu->kvm->arch.exception_payload_enabled &&
5364 	    ex->pending && ex->has_payload)
5365 		kvm_deliver_exception_payload(vcpu, ex);
5366 
5367 	memset(events, 0, sizeof(*events));
5368 
5369 	/*
5370 	 * The API doesn't provide the instruction length for software
5371 	 * exceptions, so don't report them. As long as the guest RIP
5372 	 * isn't advanced, we should expect to encounter the exception
5373 	 * again.
5374 	 */
5375 	if (!kvm_exception_is_soft(ex->vector)) {
5376 		events->exception.injected = ex->injected;
5377 		events->exception.pending = ex->pending;
5378 		/*
5379 		 * For ABI compatibility, deliberately conflate
5380 		 * pending and injected exceptions when
5381 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5382 		 */
5383 		if (!vcpu->kvm->arch.exception_payload_enabled)
5384 			events->exception.injected |= ex->pending;
5385 	}
5386 	events->exception.nr = ex->vector;
5387 	events->exception.has_error_code = ex->has_error_code;
5388 	events->exception.error_code = ex->error_code;
5389 	events->exception_has_payload = ex->has_payload;
5390 	events->exception_payload = ex->payload;
5391 
5392 	events->interrupt.injected =
5393 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5394 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5395 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5396 
5397 	events->nmi.injected = vcpu->arch.nmi_injected;
5398 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5399 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5400 
5401 	/* events->sipi_vector is never valid when reporting to user space */
5402 
5403 #ifdef CONFIG_KVM_SMM
5404 	events->smi.smm = is_smm(vcpu);
5405 	events->smi.pending = vcpu->arch.smi_pending;
5406 	events->smi.smm_inside_nmi =
5407 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5408 #endif
5409 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5410 
5411 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5412 			 | KVM_VCPUEVENT_VALID_SHADOW
5413 			 | KVM_VCPUEVENT_VALID_SMM);
5414 	if (vcpu->kvm->arch.exception_payload_enabled)
5415 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5416 	if (vcpu->kvm->arch.triple_fault_event) {
5417 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5418 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5419 	}
5420 }
5421 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5422 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5423 					      struct kvm_vcpu_events *events)
5424 {
5425 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5426 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5427 			      | KVM_VCPUEVENT_VALID_SHADOW
5428 			      | KVM_VCPUEVENT_VALID_SMM
5429 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5430 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5431 		return -EINVAL;
5432 
5433 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5434 		if (!vcpu->kvm->arch.exception_payload_enabled)
5435 			return -EINVAL;
5436 		if (events->exception.pending)
5437 			events->exception.injected = 0;
5438 		else
5439 			events->exception_has_payload = 0;
5440 	} else {
5441 		events->exception.pending = 0;
5442 		events->exception_has_payload = 0;
5443 	}
5444 
5445 	if ((events->exception.injected || events->exception.pending) &&
5446 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5447 		return -EINVAL;
5448 
5449 	/* INITs are latched while in SMM */
5450 	if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5451 	    (events->smi.smm || events->smi.pending) &&
5452 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5453 		return -EINVAL;
5454 
5455 	process_nmi(vcpu);
5456 
5457 	/*
5458 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5459 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5460 	 * pending exceptions, already-injected exceptions are not subject to
5461 	 * intercpetion.  Note, userspace that conflates pending and injected
5462 	 * is hosed, and will incorrectly convert an injected exception into a
5463 	 * pending exception, which in turn may cause a spurious VM-Exit.
5464 	 */
5465 	vcpu->arch.exception_from_userspace = events->exception.pending;
5466 
5467 	vcpu->arch.exception_vmexit.pending = false;
5468 
5469 	vcpu->arch.exception.injected = events->exception.injected;
5470 	vcpu->arch.exception.pending = events->exception.pending;
5471 	vcpu->arch.exception.vector = events->exception.nr;
5472 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5473 	vcpu->arch.exception.error_code = events->exception.error_code;
5474 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5475 	vcpu->arch.exception.payload = events->exception_payload;
5476 
5477 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5478 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5479 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5480 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5481 		kvm_x86_call(set_interrupt_shadow)(vcpu,
5482 						   events->interrupt.shadow);
5483 
5484 	vcpu->arch.nmi_injected = events->nmi.injected;
5485 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5486 		vcpu->arch.nmi_pending = 0;
5487 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5488 		if (events->nmi.pending)
5489 			kvm_make_request(KVM_REQ_NMI, vcpu);
5490 	}
5491 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5492 
5493 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5494 	    lapic_in_kernel(vcpu))
5495 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5496 
5497 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5498 #ifdef CONFIG_KVM_SMM
5499 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5500 			kvm_leave_nested(vcpu);
5501 			kvm_smm_changed(vcpu, events->smi.smm);
5502 		}
5503 
5504 		vcpu->arch.smi_pending = events->smi.pending;
5505 
5506 		if (events->smi.smm) {
5507 			if (events->smi.smm_inside_nmi)
5508 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5509 			else
5510 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5511 		}
5512 
5513 #else
5514 		if (events->smi.smm || events->smi.pending ||
5515 		    events->smi.smm_inside_nmi)
5516 			return -EINVAL;
5517 #endif
5518 
5519 		if (lapic_in_kernel(vcpu)) {
5520 			if (events->smi.latched_init)
5521 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5522 			else
5523 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5524 		}
5525 	}
5526 
5527 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5528 		if (!vcpu->kvm->arch.triple_fault_event)
5529 			return -EINVAL;
5530 		if (events->triple_fault.pending)
5531 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5532 		else
5533 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5534 	}
5535 
5536 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5537 
5538 	return 0;
5539 }
5540 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5541 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5542 					    struct kvm_debugregs *dbgregs)
5543 {
5544 	unsigned int i;
5545 
5546 	if (vcpu->kvm->arch.has_protected_state &&
5547 	    vcpu->arch.guest_state_protected)
5548 		return -EINVAL;
5549 
5550 	memset(dbgregs, 0, sizeof(*dbgregs));
5551 
5552 	BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5553 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5554 		dbgregs->db[i] = vcpu->arch.db[i];
5555 
5556 	dbgregs->dr6 = vcpu->arch.dr6;
5557 	dbgregs->dr7 = vcpu->arch.dr7;
5558 	return 0;
5559 }
5560 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5561 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5562 					    struct kvm_debugregs *dbgregs)
5563 {
5564 	unsigned int i;
5565 
5566 	if (vcpu->kvm->arch.has_protected_state &&
5567 	    vcpu->arch.guest_state_protected)
5568 		return -EINVAL;
5569 
5570 	if (dbgregs->flags)
5571 		return -EINVAL;
5572 
5573 	if (!kvm_dr6_valid(dbgregs->dr6))
5574 		return -EINVAL;
5575 	if (!kvm_dr7_valid(dbgregs->dr7))
5576 		return -EINVAL;
5577 
5578 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5579 		vcpu->arch.db[i] = dbgregs->db[i];
5580 
5581 	kvm_update_dr0123(vcpu);
5582 	vcpu->arch.dr6 = dbgregs->dr6;
5583 	vcpu->arch.dr7 = dbgregs->dr7;
5584 	kvm_update_dr7(vcpu);
5585 
5586 	return 0;
5587 }
5588 
5589 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5590 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5591 					 u8 *state, unsigned int size)
5592 {
5593 	/*
5594 	 * Only copy state for features that are enabled for the guest.  The
5595 	 * state itself isn't problematic, but setting bits in the header for
5596 	 * features that are supported in *this* host but not exposed to the
5597 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5598 	 * compatible host without the features that are NOT exposed to the
5599 	 * guest.
5600 	 *
5601 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5602 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5603 	 * supported by the host.
5604 	 */
5605 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5606 			     XFEATURE_MASK_FPSSE;
5607 
5608 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5609 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5610 
5611 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5612 				       supported_xcr0, vcpu->arch.pkru);
5613 	return 0;
5614 }
5615 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5616 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5617 					struct kvm_xsave *guest_xsave)
5618 {
5619 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5620 					     sizeof(guest_xsave->region));
5621 }
5622 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5623 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5624 					struct kvm_xsave *guest_xsave)
5625 {
5626 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5627 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5628 
5629 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5630 					      guest_xsave->region,
5631 					      kvm_caps.supported_xcr0,
5632 					      &vcpu->arch.pkru);
5633 }
5634 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5635 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5636 				       struct kvm_xcrs *guest_xcrs)
5637 {
5638 	if (vcpu->kvm->arch.has_protected_state &&
5639 	    vcpu->arch.guest_state_protected)
5640 		return -EINVAL;
5641 
5642 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5643 		guest_xcrs->nr_xcrs = 0;
5644 		return 0;
5645 	}
5646 
5647 	guest_xcrs->nr_xcrs = 1;
5648 	guest_xcrs->flags = 0;
5649 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5650 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5651 	return 0;
5652 }
5653 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5654 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5655 				       struct kvm_xcrs *guest_xcrs)
5656 {
5657 	int i, r = 0;
5658 
5659 	if (vcpu->kvm->arch.has_protected_state &&
5660 	    vcpu->arch.guest_state_protected)
5661 		return -EINVAL;
5662 
5663 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5664 		return -EINVAL;
5665 
5666 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5667 		return -EINVAL;
5668 
5669 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5670 		/* Only support XCR0 currently */
5671 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5672 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5673 				guest_xcrs->xcrs[i].value);
5674 			break;
5675 		}
5676 	if (r)
5677 		r = -EINVAL;
5678 	return r;
5679 }
5680 
5681 /*
5682  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5683  * stopped by the hypervisor.  This function will be called from the host only.
5684  * EINVAL is returned when the host attempts to set the flag for a guest that
5685  * does not support pv clocks.
5686  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5687 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5688 {
5689 	if (!vcpu->arch.pv_time.active)
5690 		return -EINVAL;
5691 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5692 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5693 	return 0;
5694 }
5695 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5696 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5697 				 struct kvm_device_attr *attr)
5698 {
5699 	int r;
5700 
5701 	switch (attr->attr) {
5702 	case KVM_VCPU_TSC_OFFSET:
5703 		r = 0;
5704 		break;
5705 	default:
5706 		r = -ENXIO;
5707 	}
5708 
5709 	return r;
5710 }
5711 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5712 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5713 				 struct kvm_device_attr *attr)
5714 {
5715 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5716 	int r;
5717 
5718 	switch (attr->attr) {
5719 	case KVM_VCPU_TSC_OFFSET:
5720 		r = -EFAULT;
5721 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5722 			break;
5723 		r = 0;
5724 		break;
5725 	default:
5726 		r = -ENXIO;
5727 	}
5728 
5729 	return r;
5730 }
5731 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5732 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5733 				 struct kvm_device_attr *attr)
5734 {
5735 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5736 	struct kvm *kvm = vcpu->kvm;
5737 	int r;
5738 
5739 	switch (attr->attr) {
5740 	case KVM_VCPU_TSC_OFFSET: {
5741 		u64 offset, tsc, ns;
5742 		unsigned long flags;
5743 		bool matched;
5744 
5745 		r = -EFAULT;
5746 		if (get_user(offset, uaddr))
5747 			break;
5748 
5749 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5750 
5751 		matched = (vcpu->arch.virtual_tsc_khz &&
5752 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5753 			   kvm->arch.last_tsc_offset == offset);
5754 
5755 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5756 		ns = get_kvmclock_base_ns();
5757 
5758 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5759 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5760 
5761 		r = 0;
5762 		break;
5763 	}
5764 	default:
5765 		r = -ENXIO;
5766 	}
5767 
5768 	return r;
5769 }
5770 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5771 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5772 				      unsigned int ioctl,
5773 				      void __user *argp)
5774 {
5775 	struct kvm_device_attr attr;
5776 	int r;
5777 
5778 	if (copy_from_user(&attr, argp, sizeof(attr)))
5779 		return -EFAULT;
5780 
5781 	if (attr.group != KVM_VCPU_TSC_CTRL)
5782 		return -ENXIO;
5783 
5784 	switch (ioctl) {
5785 	case KVM_HAS_DEVICE_ATTR:
5786 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5787 		break;
5788 	case KVM_GET_DEVICE_ATTR:
5789 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5790 		break;
5791 	case KVM_SET_DEVICE_ATTR:
5792 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5793 		break;
5794 	}
5795 
5796 	return r;
5797 }
5798 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5799 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5800 				     struct kvm_enable_cap *cap)
5801 {
5802 	if (cap->flags)
5803 		return -EINVAL;
5804 
5805 	switch (cap->cap) {
5806 #ifdef CONFIG_KVM_HYPERV
5807 	case KVM_CAP_HYPERV_SYNIC2:
5808 		if (cap->args[0])
5809 			return -EINVAL;
5810 		fallthrough;
5811 
5812 	case KVM_CAP_HYPERV_SYNIC:
5813 		if (!irqchip_in_kernel(vcpu->kvm))
5814 			return -EINVAL;
5815 		return kvm_hv_activate_synic(vcpu, cap->cap ==
5816 					     KVM_CAP_HYPERV_SYNIC2);
5817 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5818 		{
5819 			int r;
5820 			uint16_t vmcs_version;
5821 			void __user *user_ptr;
5822 
5823 			if (!kvm_x86_ops.nested_ops->enable_evmcs)
5824 				return -ENOTTY;
5825 			r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5826 			if (!r) {
5827 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
5828 				if (copy_to_user(user_ptr, &vmcs_version,
5829 						 sizeof(vmcs_version)))
5830 					r = -EFAULT;
5831 			}
5832 			return r;
5833 		}
5834 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5835 		if (!kvm_x86_ops.enable_l2_tlb_flush)
5836 			return -ENOTTY;
5837 
5838 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
5839 
5840 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
5841 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5842 #endif
5843 
5844 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5845 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
5846 		return 0;
5847 	default:
5848 		return -EINVAL;
5849 	}
5850 }
5851 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5852 long kvm_arch_vcpu_ioctl(struct file *filp,
5853 			 unsigned int ioctl, unsigned long arg)
5854 {
5855 	struct kvm_vcpu *vcpu = filp->private_data;
5856 	void __user *argp = (void __user *)arg;
5857 	int r;
5858 	union {
5859 		struct kvm_sregs2 *sregs2;
5860 		struct kvm_lapic_state *lapic;
5861 		struct kvm_xsave *xsave;
5862 		struct kvm_xcrs *xcrs;
5863 		void *buffer;
5864 	} u;
5865 
5866 	vcpu_load(vcpu);
5867 
5868 	u.buffer = NULL;
5869 	switch (ioctl) {
5870 	case KVM_GET_LAPIC: {
5871 		r = -EINVAL;
5872 		if (!lapic_in_kernel(vcpu))
5873 			goto out;
5874 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
5875 
5876 		r = -ENOMEM;
5877 		if (!u.lapic)
5878 			goto out;
5879 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5880 		if (r)
5881 			goto out;
5882 		r = -EFAULT;
5883 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5884 			goto out;
5885 		r = 0;
5886 		break;
5887 	}
5888 	case KVM_SET_LAPIC: {
5889 		r = -EINVAL;
5890 		if (!lapic_in_kernel(vcpu))
5891 			goto out;
5892 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
5893 		if (IS_ERR(u.lapic)) {
5894 			r = PTR_ERR(u.lapic);
5895 			goto out_nofree;
5896 		}
5897 
5898 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5899 		break;
5900 	}
5901 	case KVM_INTERRUPT: {
5902 		struct kvm_interrupt irq;
5903 
5904 		r = -EFAULT;
5905 		if (copy_from_user(&irq, argp, sizeof(irq)))
5906 			goto out;
5907 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5908 		break;
5909 	}
5910 	case KVM_NMI: {
5911 		r = kvm_vcpu_ioctl_nmi(vcpu);
5912 		break;
5913 	}
5914 	case KVM_SMI: {
5915 		r = kvm_inject_smi(vcpu);
5916 		break;
5917 	}
5918 	case KVM_SET_CPUID: {
5919 		struct kvm_cpuid __user *cpuid_arg = argp;
5920 		struct kvm_cpuid cpuid;
5921 
5922 		r = -EFAULT;
5923 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5924 			goto out;
5925 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5926 		break;
5927 	}
5928 	case KVM_SET_CPUID2: {
5929 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5930 		struct kvm_cpuid2 cpuid;
5931 
5932 		r = -EFAULT;
5933 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5934 			goto out;
5935 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5936 					      cpuid_arg->entries);
5937 		break;
5938 	}
5939 	case KVM_GET_CPUID2: {
5940 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5941 		struct kvm_cpuid2 cpuid;
5942 
5943 		r = -EFAULT;
5944 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5945 			goto out;
5946 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5947 					      cpuid_arg->entries);
5948 		if (r)
5949 			goto out;
5950 		r = -EFAULT;
5951 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5952 			goto out;
5953 		r = 0;
5954 		break;
5955 	}
5956 	case KVM_GET_MSRS: {
5957 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5958 		r = msr_io(vcpu, argp, do_get_msr, 1);
5959 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5960 		break;
5961 	}
5962 	case KVM_SET_MSRS: {
5963 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5964 		r = msr_io(vcpu, argp, do_set_msr, 0);
5965 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5966 		break;
5967 	}
5968 	case KVM_TPR_ACCESS_REPORTING: {
5969 		struct kvm_tpr_access_ctl tac;
5970 
5971 		r = -EFAULT;
5972 		if (copy_from_user(&tac, argp, sizeof(tac)))
5973 			goto out;
5974 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5975 		if (r)
5976 			goto out;
5977 		r = -EFAULT;
5978 		if (copy_to_user(argp, &tac, sizeof(tac)))
5979 			goto out;
5980 		r = 0;
5981 		break;
5982 	};
5983 	case KVM_SET_VAPIC_ADDR: {
5984 		struct kvm_vapic_addr va;
5985 		int idx;
5986 
5987 		r = -EINVAL;
5988 		if (!lapic_in_kernel(vcpu))
5989 			goto out;
5990 		r = -EFAULT;
5991 		if (copy_from_user(&va, argp, sizeof(va)))
5992 			goto out;
5993 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5994 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5995 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5996 		break;
5997 	}
5998 	case KVM_X86_SETUP_MCE: {
5999 		u64 mcg_cap;
6000 
6001 		r = -EFAULT;
6002 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6003 			goto out;
6004 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6005 		break;
6006 	}
6007 	case KVM_X86_SET_MCE: {
6008 		struct kvm_x86_mce mce;
6009 
6010 		r = -EFAULT;
6011 		if (copy_from_user(&mce, argp, sizeof(mce)))
6012 			goto out;
6013 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6014 		break;
6015 	}
6016 	case KVM_GET_VCPU_EVENTS: {
6017 		struct kvm_vcpu_events events;
6018 
6019 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6020 
6021 		r = -EFAULT;
6022 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6023 			break;
6024 		r = 0;
6025 		break;
6026 	}
6027 	case KVM_SET_VCPU_EVENTS: {
6028 		struct kvm_vcpu_events events;
6029 
6030 		r = -EFAULT;
6031 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6032 			break;
6033 
6034 		kvm_vcpu_srcu_read_lock(vcpu);
6035 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6036 		kvm_vcpu_srcu_read_unlock(vcpu);
6037 		break;
6038 	}
6039 	case KVM_GET_DEBUGREGS: {
6040 		struct kvm_debugregs dbgregs;
6041 
6042 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6043 		if (r < 0)
6044 			break;
6045 
6046 		r = -EFAULT;
6047 		if (copy_to_user(argp, &dbgregs,
6048 				 sizeof(struct kvm_debugregs)))
6049 			break;
6050 		r = 0;
6051 		break;
6052 	}
6053 	case KVM_SET_DEBUGREGS: {
6054 		struct kvm_debugregs dbgregs;
6055 
6056 		r = -EFAULT;
6057 		if (copy_from_user(&dbgregs, argp,
6058 				   sizeof(struct kvm_debugregs)))
6059 			break;
6060 
6061 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6062 		break;
6063 	}
6064 	case KVM_GET_XSAVE: {
6065 		r = -EINVAL;
6066 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6067 			break;
6068 
6069 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6070 		r = -ENOMEM;
6071 		if (!u.xsave)
6072 			break;
6073 
6074 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6075 		if (r < 0)
6076 			break;
6077 
6078 		r = -EFAULT;
6079 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6080 			break;
6081 		r = 0;
6082 		break;
6083 	}
6084 	case KVM_SET_XSAVE: {
6085 		int size = vcpu->arch.guest_fpu.uabi_size;
6086 
6087 		u.xsave = memdup_user(argp, size);
6088 		if (IS_ERR(u.xsave)) {
6089 			r = PTR_ERR(u.xsave);
6090 			goto out_nofree;
6091 		}
6092 
6093 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6094 		break;
6095 	}
6096 
6097 	case KVM_GET_XSAVE2: {
6098 		int size = vcpu->arch.guest_fpu.uabi_size;
6099 
6100 		u.xsave = kzalloc(size, GFP_KERNEL);
6101 		r = -ENOMEM;
6102 		if (!u.xsave)
6103 			break;
6104 
6105 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6106 		if (r < 0)
6107 			break;
6108 
6109 		r = -EFAULT;
6110 		if (copy_to_user(argp, u.xsave, size))
6111 			break;
6112 
6113 		r = 0;
6114 		break;
6115 	}
6116 
6117 	case KVM_GET_XCRS: {
6118 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6119 		r = -ENOMEM;
6120 		if (!u.xcrs)
6121 			break;
6122 
6123 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6124 		if (r < 0)
6125 			break;
6126 
6127 		r = -EFAULT;
6128 		if (copy_to_user(argp, u.xcrs,
6129 				 sizeof(struct kvm_xcrs)))
6130 			break;
6131 		r = 0;
6132 		break;
6133 	}
6134 	case KVM_SET_XCRS: {
6135 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6136 		if (IS_ERR(u.xcrs)) {
6137 			r = PTR_ERR(u.xcrs);
6138 			goto out_nofree;
6139 		}
6140 
6141 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6142 		break;
6143 	}
6144 	case KVM_SET_TSC_KHZ: {
6145 		u32 user_tsc_khz;
6146 
6147 		r = -EINVAL;
6148 		user_tsc_khz = (u32)arg;
6149 
6150 		if (kvm_caps.has_tsc_control &&
6151 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6152 			goto out;
6153 
6154 		if (user_tsc_khz == 0)
6155 			user_tsc_khz = tsc_khz;
6156 
6157 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6158 			r = 0;
6159 
6160 		goto out;
6161 	}
6162 	case KVM_GET_TSC_KHZ: {
6163 		r = vcpu->arch.virtual_tsc_khz;
6164 		goto out;
6165 	}
6166 	case KVM_KVMCLOCK_CTRL: {
6167 		r = kvm_set_guest_paused(vcpu);
6168 		goto out;
6169 	}
6170 	case KVM_ENABLE_CAP: {
6171 		struct kvm_enable_cap cap;
6172 
6173 		r = -EFAULT;
6174 		if (copy_from_user(&cap, argp, sizeof(cap)))
6175 			goto out;
6176 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6177 		break;
6178 	}
6179 	case KVM_GET_NESTED_STATE: {
6180 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6181 		u32 user_data_size;
6182 
6183 		r = -EINVAL;
6184 		if (!kvm_x86_ops.nested_ops->get_state)
6185 			break;
6186 
6187 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6188 		r = -EFAULT;
6189 		if (get_user(user_data_size, &user_kvm_nested_state->size))
6190 			break;
6191 
6192 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6193 						     user_data_size);
6194 		if (r < 0)
6195 			break;
6196 
6197 		if (r > user_data_size) {
6198 			if (put_user(r, &user_kvm_nested_state->size))
6199 				r = -EFAULT;
6200 			else
6201 				r = -E2BIG;
6202 			break;
6203 		}
6204 
6205 		r = 0;
6206 		break;
6207 	}
6208 	case KVM_SET_NESTED_STATE: {
6209 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6210 		struct kvm_nested_state kvm_state;
6211 		int idx;
6212 
6213 		r = -EINVAL;
6214 		if (!kvm_x86_ops.nested_ops->set_state)
6215 			break;
6216 
6217 		r = -EFAULT;
6218 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6219 			break;
6220 
6221 		r = -EINVAL;
6222 		if (kvm_state.size < sizeof(kvm_state))
6223 			break;
6224 
6225 		if (kvm_state.flags &
6226 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6227 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6228 		      | KVM_STATE_NESTED_GIF_SET))
6229 			break;
6230 
6231 		/* nested_run_pending implies guest_mode.  */
6232 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6233 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6234 			break;
6235 
6236 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6237 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6238 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6239 		break;
6240 	}
6241 #ifdef CONFIG_KVM_HYPERV
6242 	case KVM_GET_SUPPORTED_HV_CPUID:
6243 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6244 		break;
6245 #endif
6246 #ifdef CONFIG_KVM_XEN
6247 	case KVM_XEN_VCPU_GET_ATTR: {
6248 		struct kvm_xen_vcpu_attr xva;
6249 
6250 		r = -EFAULT;
6251 		if (copy_from_user(&xva, argp, sizeof(xva)))
6252 			goto out;
6253 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6254 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6255 			r = -EFAULT;
6256 		break;
6257 	}
6258 	case KVM_XEN_VCPU_SET_ATTR: {
6259 		struct kvm_xen_vcpu_attr xva;
6260 
6261 		r = -EFAULT;
6262 		if (copy_from_user(&xva, argp, sizeof(xva)))
6263 			goto out;
6264 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6265 		break;
6266 	}
6267 #endif
6268 	case KVM_GET_SREGS2: {
6269 		r = -EINVAL;
6270 		if (vcpu->kvm->arch.has_protected_state &&
6271 		    vcpu->arch.guest_state_protected)
6272 			goto out;
6273 
6274 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6275 		r = -ENOMEM;
6276 		if (!u.sregs2)
6277 			goto out;
6278 		__get_sregs2(vcpu, u.sregs2);
6279 		r = -EFAULT;
6280 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6281 			goto out;
6282 		r = 0;
6283 		break;
6284 	}
6285 	case KVM_SET_SREGS2: {
6286 		r = -EINVAL;
6287 		if (vcpu->kvm->arch.has_protected_state &&
6288 		    vcpu->arch.guest_state_protected)
6289 			goto out;
6290 
6291 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6292 		if (IS_ERR(u.sregs2)) {
6293 			r = PTR_ERR(u.sregs2);
6294 			u.sregs2 = NULL;
6295 			goto out;
6296 		}
6297 		r = __set_sregs2(vcpu, u.sregs2);
6298 		break;
6299 	}
6300 	case KVM_HAS_DEVICE_ATTR:
6301 	case KVM_GET_DEVICE_ATTR:
6302 	case KVM_SET_DEVICE_ATTR:
6303 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6304 		break;
6305 	default:
6306 		r = -EINVAL;
6307 	}
6308 out:
6309 	kfree(u.buffer);
6310 out_nofree:
6311 	vcpu_put(vcpu);
6312 	return r;
6313 }
6314 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6315 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6316 {
6317 	return VM_FAULT_SIGBUS;
6318 }
6319 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6320 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6321 {
6322 	int ret;
6323 
6324 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
6325 		return -EINVAL;
6326 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6327 	return ret;
6328 }
6329 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6330 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6331 					      u64 ident_addr)
6332 {
6333 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6334 }
6335 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6336 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6337 					 unsigned long kvm_nr_mmu_pages)
6338 {
6339 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6340 		return -EINVAL;
6341 
6342 	mutex_lock(&kvm->slots_lock);
6343 
6344 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6345 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6346 
6347 	mutex_unlock(&kvm->slots_lock);
6348 	return 0;
6349 }
6350 
kvm_vm_ioctl_get_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6351 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6352 {
6353 	struct kvm_pic *pic = kvm->arch.vpic;
6354 	int r;
6355 
6356 	r = 0;
6357 	switch (chip->chip_id) {
6358 	case KVM_IRQCHIP_PIC_MASTER:
6359 		memcpy(&chip->chip.pic, &pic->pics[0],
6360 			sizeof(struct kvm_pic_state));
6361 		break;
6362 	case KVM_IRQCHIP_PIC_SLAVE:
6363 		memcpy(&chip->chip.pic, &pic->pics[1],
6364 			sizeof(struct kvm_pic_state));
6365 		break;
6366 	case KVM_IRQCHIP_IOAPIC:
6367 		kvm_get_ioapic(kvm, &chip->chip.ioapic);
6368 		break;
6369 	default:
6370 		r = -EINVAL;
6371 		break;
6372 	}
6373 	return r;
6374 }
6375 
kvm_vm_ioctl_set_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6376 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6377 {
6378 	struct kvm_pic *pic = kvm->arch.vpic;
6379 	int r;
6380 
6381 	r = 0;
6382 	switch (chip->chip_id) {
6383 	case KVM_IRQCHIP_PIC_MASTER:
6384 		spin_lock(&pic->lock);
6385 		memcpy(&pic->pics[0], &chip->chip.pic,
6386 			sizeof(struct kvm_pic_state));
6387 		spin_unlock(&pic->lock);
6388 		break;
6389 	case KVM_IRQCHIP_PIC_SLAVE:
6390 		spin_lock(&pic->lock);
6391 		memcpy(&pic->pics[1], &chip->chip.pic,
6392 			sizeof(struct kvm_pic_state));
6393 		spin_unlock(&pic->lock);
6394 		break;
6395 	case KVM_IRQCHIP_IOAPIC:
6396 		kvm_set_ioapic(kvm, &chip->chip.ioapic);
6397 		break;
6398 	default:
6399 		r = -EINVAL;
6400 		break;
6401 	}
6402 	kvm_pic_update_irq(pic);
6403 	return r;
6404 }
6405 
kvm_vm_ioctl_get_pit(struct kvm * kvm,struct kvm_pit_state * ps)6406 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6407 {
6408 	struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6409 
6410 	BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6411 
6412 	mutex_lock(&kps->lock);
6413 	memcpy(ps, &kps->channels, sizeof(*ps));
6414 	mutex_unlock(&kps->lock);
6415 	return 0;
6416 }
6417 
kvm_vm_ioctl_set_pit(struct kvm * kvm,struct kvm_pit_state * ps)6418 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6419 {
6420 	int i;
6421 	struct kvm_pit *pit = kvm->arch.vpit;
6422 
6423 	mutex_lock(&pit->pit_state.lock);
6424 	memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6425 	for (i = 0; i < 3; i++)
6426 		kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6427 	mutex_unlock(&pit->pit_state.lock);
6428 	return 0;
6429 }
6430 
kvm_vm_ioctl_get_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6431 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6432 {
6433 	mutex_lock(&kvm->arch.vpit->pit_state.lock);
6434 	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6435 		sizeof(ps->channels));
6436 	ps->flags = kvm->arch.vpit->pit_state.flags;
6437 	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6438 	memset(&ps->reserved, 0, sizeof(ps->reserved));
6439 	return 0;
6440 }
6441 
kvm_vm_ioctl_set_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6442 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6443 {
6444 	int start = 0;
6445 	int i;
6446 	u32 prev_legacy, cur_legacy;
6447 	struct kvm_pit *pit = kvm->arch.vpit;
6448 
6449 	mutex_lock(&pit->pit_state.lock);
6450 	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6451 	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6452 	if (!prev_legacy && cur_legacy)
6453 		start = 1;
6454 	memcpy(&pit->pit_state.channels, &ps->channels,
6455 	       sizeof(pit->pit_state.channels));
6456 	pit->pit_state.flags = ps->flags;
6457 	for (i = 0; i < 3; i++)
6458 		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6459 				   start && i == 0);
6460 	mutex_unlock(&pit->pit_state.lock);
6461 	return 0;
6462 }
6463 
kvm_vm_ioctl_reinject(struct kvm * kvm,struct kvm_reinject_control * control)6464 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6465 				 struct kvm_reinject_control *control)
6466 {
6467 	struct kvm_pit *pit = kvm->arch.vpit;
6468 
6469 	/* pit->pit_state.lock was overloaded to prevent userspace from getting
6470 	 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6471 	 * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
6472 	 */
6473 	mutex_lock(&pit->pit_state.lock);
6474 	kvm_pit_set_reinject(pit, control->pit_reinject);
6475 	mutex_unlock(&pit->pit_state.lock);
6476 
6477 	return 0;
6478 }
6479 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6480 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6481 {
6482 
6483 	/*
6484 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6485 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6486 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6487 	 * VM-Exit.
6488 	 */
6489 	struct kvm_vcpu *vcpu;
6490 	unsigned long i;
6491 
6492 	if (!kvm_x86_ops.cpu_dirty_log_size)
6493 		return;
6494 
6495 	kvm_for_each_vcpu(i, vcpu, kvm)
6496 		kvm_vcpu_kick(vcpu);
6497 }
6498 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_event,bool line_status)6499 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6500 			bool line_status)
6501 {
6502 	if (!irqchip_in_kernel(kvm))
6503 		return -ENXIO;
6504 
6505 	irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6506 					irq_event->irq, irq_event->level,
6507 					line_status);
6508 	return 0;
6509 }
6510 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6511 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6512 			    struct kvm_enable_cap *cap)
6513 {
6514 	int r;
6515 
6516 	if (cap->flags)
6517 		return -EINVAL;
6518 
6519 	switch (cap->cap) {
6520 	case KVM_CAP_DISABLE_QUIRKS2:
6521 		r = -EINVAL;
6522 		if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6523 			break;
6524 		fallthrough;
6525 	case KVM_CAP_DISABLE_QUIRKS:
6526 		kvm->arch.disabled_quirks = cap->args[0];
6527 		r = 0;
6528 		break;
6529 	case KVM_CAP_SPLIT_IRQCHIP: {
6530 		mutex_lock(&kvm->lock);
6531 		r = -EINVAL;
6532 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6533 			goto split_irqchip_unlock;
6534 		r = -EEXIST;
6535 		if (irqchip_in_kernel(kvm))
6536 			goto split_irqchip_unlock;
6537 		if (kvm->created_vcpus)
6538 			goto split_irqchip_unlock;
6539 		/* Pairs with irqchip_in_kernel. */
6540 		smp_wmb();
6541 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6542 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6543 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6544 		r = 0;
6545 split_irqchip_unlock:
6546 		mutex_unlock(&kvm->lock);
6547 		break;
6548 	}
6549 	case KVM_CAP_X2APIC_API:
6550 		r = -EINVAL;
6551 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6552 			break;
6553 
6554 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6555 			kvm->arch.x2apic_format = true;
6556 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6557 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6558 
6559 		r = 0;
6560 		break;
6561 	case KVM_CAP_X86_DISABLE_EXITS:
6562 		r = -EINVAL;
6563 		if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6564 			break;
6565 
6566 		mutex_lock(&kvm->lock);
6567 		if (kvm->created_vcpus)
6568 			goto disable_exits_unlock;
6569 
6570 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6571 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6572 
6573 		if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6574 		    cpu_smt_possible() &&
6575 		    (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6576 			pr_warn_once(SMT_RSB_MSG);
6577 
6578 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6579 			kvm->arch.pause_in_guest = true;
6580 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT)
6581 			kvm->arch.mwait_in_guest = true;
6582 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6583 			kvm->arch.hlt_in_guest = true;
6584 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6585 			kvm->arch.cstate_in_guest = true;
6586 		r = 0;
6587 disable_exits_unlock:
6588 		mutex_unlock(&kvm->lock);
6589 		break;
6590 	case KVM_CAP_MSR_PLATFORM_INFO:
6591 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6592 		r = 0;
6593 		break;
6594 	case KVM_CAP_EXCEPTION_PAYLOAD:
6595 		kvm->arch.exception_payload_enabled = cap->args[0];
6596 		r = 0;
6597 		break;
6598 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6599 		kvm->arch.triple_fault_event = cap->args[0];
6600 		r = 0;
6601 		break;
6602 	case KVM_CAP_X86_USER_SPACE_MSR:
6603 		r = -EINVAL;
6604 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6605 			break;
6606 		kvm->arch.user_space_msr_mask = cap->args[0];
6607 		r = 0;
6608 		break;
6609 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6610 		r = -EINVAL;
6611 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6612 			break;
6613 
6614 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6615 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6616 			break;
6617 
6618 		if (kvm_caps.has_bus_lock_exit &&
6619 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6620 			kvm->arch.bus_lock_detection_enabled = true;
6621 		r = 0;
6622 		break;
6623 #ifdef CONFIG_X86_SGX_KVM
6624 	case KVM_CAP_SGX_ATTRIBUTE: {
6625 		unsigned long allowed_attributes = 0;
6626 
6627 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6628 		if (r)
6629 			break;
6630 
6631 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6632 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6633 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6634 			kvm->arch.sgx_provisioning_allowed = true;
6635 		else
6636 			r = -EINVAL;
6637 		break;
6638 	}
6639 #endif
6640 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6641 		r = -EINVAL;
6642 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6643 			break;
6644 
6645 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6646 		break;
6647 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6648 		r = -EINVAL;
6649 		if (!kvm_x86_ops.vm_move_enc_context_from)
6650 			break;
6651 
6652 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6653 		break;
6654 	case KVM_CAP_EXIT_HYPERCALL:
6655 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6656 			r = -EINVAL;
6657 			break;
6658 		}
6659 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6660 		r = 0;
6661 		break;
6662 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6663 		r = -EINVAL;
6664 		if (cap->args[0] & ~1)
6665 			break;
6666 		kvm->arch.exit_on_emulation_error = cap->args[0];
6667 		r = 0;
6668 		break;
6669 	case KVM_CAP_PMU_CAPABILITY:
6670 		r = -EINVAL;
6671 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6672 			break;
6673 
6674 		mutex_lock(&kvm->lock);
6675 		if (!kvm->created_vcpus) {
6676 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6677 			r = 0;
6678 		}
6679 		mutex_unlock(&kvm->lock);
6680 		break;
6681 	case KVM_CAP_MAX_VCPU_ID:
6682 		r = -EINVAL;
6683 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6684 			break;
6685 
6686 		mutex_lock(&kvm->lock);
6687 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6688 			;
6689 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6690 			r = 0;
6691 		} else if (!kvm->arch.max_vcpu_ids) {
6692 			kvm->arch.max_vcpu_ids = cap->args[0];
6693 			r = 0;
6694 		}
6695 		mutex_unlock(&kvm->lock);
6696 		break;
6697 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6698 		r = -EINVAL;
6699 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6700 			break;
6701 		if (!kvm_caps.has_notify_vmexit)
6702 			break;
6703 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6704 			break;
6705 		mutex_lock(&kvm->lock);
6706 		if (!kvm->created_vcpus) {
6707 			kvm->arch.notify_window = cap->args[0] >> 32;
6708 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6709 			r = 0;
6710 		}
6711 		mutex_unlock(&kvm->lock);
6712 		break;
6713 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6714 		r = -EINVAL;
6715 
6716 		/*
6717 		 * Since the risk of disabling NX hugepages is a guest crashing
6718 		 * the system, ensure the userspace process has permission to
6719 		 * reboot the system.
6720 		 *
6721 		 * Note that unlike the reboot() syscall, the process must have
6722 		 * this capability in the root namespace because exposing
6723 		 * /dev/kvm into a container does not limit the scope of the
6724 		 * iTLB multihit bug to that container. In other words,
6725 		 * this must use capable(), not ns_capable().
6726 		 */
6727 		if (!capable(CAP_SYS_BOOT)) {
6728 			r = -EPERM;
6729 			break;
6730 		}
6731 
6732 		if (cap->args[0])
6733 			break;
6734 
6735 		mutex_lock(&kvm->lock);
6736 		if (!kvm->created_vcpus) {
6737 			kvm->arch.disable_nx_huge_pages = true;
6738 			r = 0;
6739 		}
6740 		mutex_unlock(&kvm->lock);
6741 		break;
6742 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6743 		u64 bus_cycle_ns = cap->args[0];
6744 		u64 unused;
6745 
6746 		/*
6747 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
6748 		 * divide value that can be programmed in APIC_TDCR.
6749 		 */
6750 		r = -EINVAL;
6751 		if (!bus_cycle_ns ||
6752 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6753 			break;
6754 
6755 		r = 0;
6756 		mutex_lock(&kvm->lock);
6757 		if (!irqchip_in_kernel(kvm))
6758 			r = -ENXIO;
6759 		else if (kvm->created_vcpus)
6760 			r = -EINVAL;
6761 		else
6762 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6763 		mutex_unlock(&kvm->lock);
6764 		break;
6765 	}
6766 	default:
6767 		r = -EINVAL;
6768 		break;
6769 	}
6770 	return r;
6771 }
6772 
kvm_alloc_msr_filter(bool default_allow)6773 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6774 {
6775 	struct kvm_x86_msr_filter *msr_filter;
6776 
6777 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6778 	if (!msr_filter)
6779 		return NULL;
6780 
6781 	msr_filter->default_allow = default_allow;
6782 	return msr_filter;
6783 }
6784 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6785 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6786 {
6787 	u32 i;
6788 
6789 	if (!msr_filter)
6790 		return;
6791 
6792 	for (i = 0; i < msr_filter->count; i++)
6793 		kfree(msr_filter->ranges[i].bitmap);
6794 
6795 	kfree(msr_filter);
6796 }
6797 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6798 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6799 			      struct kvm_msr_filter_range *user_range)
6800 {
6801 	unsigned long *bitmap;
6802 	size_t bitmap_size;
6803 
6804 	if (!user_range->nmsrs)
6805 		return 0;
6806 
6807 	if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6808 		return -EINVAL;
6809 
6810 	if (!user_range->flags)
6811 		return -EINVAL;
6812 
6813 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6814 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6815 		return -EINVAL;
6816 
6817 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6818 	if (IS_ERR(bitmap))
6819 		return PTR_ERR(bitmap);
6820 
6821 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6822 		.flags = user_range->flags,
6823 		.base = user_range->base,
6824 		.nmsrs = user_range->nmsrs,
6825 		.bitmap = bitmap,
6826 	};
6827 
6828 	msr_filter->count++;
6829 	return 0;
6830 }
6831 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)6832 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6833 				       struct kvm_msr_filter *filter)
6834 {
6835 	struct kvm_x86_msr_filter *new_filter, *old_filter;
6836 	bool default_allow;
6837 	bool empty = true;
6838 	int r;
6839 	u32 i;
6840 
6841 	if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
6842 		return -EINVAL;
6843 
6844 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6845 		empty &= !filter->ranges[i].nmsrs;
6846 
6847 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6848 	if (empty && !default_allow)
6849 		return -EINVAL;
6850 
6851 	new_filter = kvm_alloc_msr_filter(default_allow);
6852 	if (!new_filter)
6853 		return -ENOMEM;
6854 
6855 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6856 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6857 		if (r) {
6858 			kvm_free_msr_filter(new_filter);
6859 			return r;
6860 		}
6861 	}
6862 
6863 	mutex_lock(&kvm->lock);
6864 	old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6865 					 mutex_is_locked(&kvm->lock));
6866 	mutex_unlock(&kvm->lock);
6867 	synchronize_srcu(&kvm->srcu);
6868 
6869 	kvm_free_msr_filter(old_filter);
6870 
6871 	kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6872 
6873 	return 0;
6874 }
6875 
6876 #ifdef CONFIG_KVM_COMPAT
6877 /* for KVM_X86_SET_MSR_FILTER */
6878 struct kvm_msr_filter_range_compat {
6879 	__u32 flags;
6880 	__u32 nmsrs;
6881 	__u32 base;
6882 	__u32 bitmap;
6883 };
6884 
6885 struct kvm_msr_filter_compat {
6886 	__u32 flags;
6887 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6888 };
6889 
6890 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6891 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6892 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6893 			      unsigned long arg)
6894 {
6895 	void __user *argp = (void __user *)arg;
6896 	struct kvm *kvm = filp->private_data;
6897 	long r = -ENOTTY;
6898 
6899 	switch (ioctl) {
6900 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
6901 		struct kvm_msr_filter __user *user_msr_filter = argp;
6902 		struct kvm_msr_filter_compat filter_compat;
6903 		struct kvm_msr_filter filter;
6904 		int i;
6905 
6906 		if (copy_from_user(&filter_compat, user_msr_filter,
6907 				   sizeof(filter_compat)))
6908 			return -EFAULT;
6909 
6910 		filter.flags = filter_compat.flags;
6911 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6912 			struct kvm_msr_filter_range_compat *cr;
6913 
6914 			cr = &filter_compat.ranges[i];
6915 			filter.ranges[i] = (struct kvm_msr_filter_range) {
6916 				.flags = cr->flags,
6917 				.nmsrs = cr->nmsrs,
6918 				.base = cr->base,
6919 				.bitmap = (__u8 *)(ulong)cr->bitmap,
6920 			};
6921 		}
6922 
6923 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6924 		break;
6925 	}
6926 	}
6927 
6928 	return r;
6929 }
6930 #endif
6931 
6932 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)6933 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6934 {
6935 	struct kvm_vcpu *vcpu;
6936 	unsigned long i;
6937 
6938 	/*
6939 	 * Ignore the return, marking the guest paused only "fails" if the vCPU
6940 	 * isn't using kvmclock; continuing on is correct and desirable.
6941 	 */
6942 	kvm_for_each_vcpu(i, vcpu, kvm)
6943 		(void)kvm_set_guest_paused(vcpu);
6944 
6945 	return NOTIFY_DONE;
6946 }
6947 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)6948 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6949 {
6950 	switch (state) {
6951 	case PM_HIBERNATION_PREPARE:
6952 	case PM_SUSPEND_PREPARE:
6953 		return kvm_arch_suspend_notifier(kvm);
6954 	}
6955 
6956 	return NOTIFY_DONE;
6957 }
6958 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6959 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)6960 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6961 {
6962 	struct kvm_clock_data data = { 0 };
6963 
6964 	get_kvmclock(kvm, &data);
6965 	if (copy_to_user(argp, &data, sizeof(data)))
6966 		return -EFAULT;
6967 
6968 	return 0;
6969 }
6970 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)6971 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6972 {
6973 	struct kvm_arch *ka = &kvm->arch;
6974 	struct kvm_clock_data data;
6975 	u64 now_raw_ns;
6976 
6977 	if (copy_from_user(&data, argp, sizeof(data)))
6978 		return -EFAULT;
6979 
6980 	/*
6981 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6982 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6983 	 */
6984 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6985 		return -EINVAL;
6986 
6987 	kvm_hv_request_tsc_page_update(kvm);
6988 	kvm_start_pvclock_update(kvm);
6989 	pvclock_update_vm_gtod_copy(kvm);
6990 
6991 	/*
6992 	 * This pairs with kvm_guest_time_update(): when masterclock is
6993 	 * in use, we use master_kernel_ns + kvmclock_offset to set
6994 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6995 	 * is slightly ahead) here we risk going negative on unsigned
6996 	 * 'system_time' when 'data.clock' is very small.
6997 	 */
6998 	if (data.flags & KVM_CLOCK_REALTIME) {
6999 		u64 now_real_ns = ktime_get_real_ns();
7000 
7001 		/*
7002 		 * Avoid stepping the kvmclock backwards.
7003 		 */
7004 		if (now_real_ns > data.realtime)
7005 			data.clock += now_real_ns - data.realtime;
7006 	}
7007 
7008 	if (ka->use_master_clock)
7009 		now_raw_ns = ka->master_kernel_ns;
7010 	else
7011 		now_raw_ns = get_kvmclock_base_ns();
7012 	ka->kvmclock_offset = data.clock - now_raw_ns;
7013 	kvm_end_pvclock_update(kvm);
7014 	return 0;
7015 }
7016 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7017 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7018 {
7019 	struct kvm *kvm = filp->private_data;
7020 	void __user *argp = (void __user *)arg;
7021 	int r = -ENOTTY;
7022 	/*
7023 	 * This union makes it completely explicit to gcc-3.x
7024 	 * that these two variables' stack usage should be
7025 	 * combined, not added together.
7026 	 */
7027 	union {
7028 		struct kvm_pit_state ps;
7029 		struct kvm_pit_state2 ps2;
7030 		struct kvm_pit_config pit_config;
7031 	} u;
7032 
7033 	switch (ioctl) {
7034 	case KVM_SET_TSS_ADDR:
7035 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7036 		break;
7037 	case KVM_SET_IDENTITY_MAP_ADDR: {
7038 		u64 ident_addr;
7039 
7040 		mutex_lock(&kvm->lock);
7041 		r = -EINVAL;
7042 		if (kvm->created_vcpus)
7043 			goto set_identity_unlock;
7044 		r = -EFAULT;
7045 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7046 			goto set_identity_unlock;
7047 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7048 set_identity_unlock:
7049 		mutex_unlock(&kvm->lock);
7050 		break;
7051 	}
7052 	case KVM_SET_NR_MMU_PAGES:
7053 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7054 		break;
7055 	case KVM_CREATE_IRQCHIP: {
7056 		mutex_lock(&kvm->lock);
7057 
7058 		r = -EEXIST;
7059 		if (irqchip_in_kernel(kvm))
7060 			goto create_irqchip_unlock;
7061 
7062 		r = -EINVAL;
7063 		if (kvm->created_vcpus)
7064 			goto create_irqchip_unlock;
7065 
7066 		r = kvm_pic_init(kvm);
7067 		if (r)
7068 			goto create_irqchip_unlock;
7069 
7070 		r = kvm_ioapic_init(kvm);
7071 		if (r) {
7072 			kvm_pic_destroy(kvm);
7073 			goto create_irqchip_unlock;
7074 		}
7075 
7076 		r = kvm_setup_default_irq_routing(kvm);
7077 		if (r) {
7078 			kvm_ioapic_destroy(kvm);
7079 			kvm_pic_destroy(kvm);
7080 			goto create_irqchip_unlock;
7081 		}
7082 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7083 		smp_wmb();
7084 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7085 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7086 	create_irqchip_unlock:
7087 		mutex_unlock(&kvm->lock);
7088 		break;
7089 	}
7090 	case KVM_CREATE_PIT:
7091 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7092 		goto create_pit;
7093 	case KVM_CREATE_PIT2:
7094 		r = -EFAULT;
7095 		if (copy_from_user(&u.pit_config, argp,
7096 				   sizeof(struct kvm_pit_config)))
7097 			goto out;
7098 	create_pit:
7099 		mutex_lock(&kvm->lock);
7100 		r = -EEXIST;
7101 		if (kvm->arch.vpit)
7102 			goto create_pit_unlock;
7103 		r = -ENOENT;
7104 		if (!pic_in_kernel(kvm))
7105 			goto create_pit_unlock;
7106 		r = -ENOMEM;
7107 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7108 		if (kvm->arch.vpit)
7109 			r = 0;
7110 	create_pit_unlock:
7111 		mutex_unlock(&kvm->lock);
7112 		break;
7113 	case KVM_GET_IRQCHIP: {
7114 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7115 		struct kvm_irqchip *chip;
7116 
7117 		chip = memdup_user(argp, sizeof(*chip));
7118 		if (IS_ERR(chip)) {
7119 			r = PTR_ERR(chip);
7120 			goto out;
7121 		}
7122 
7123 		r = -ENXIO;
7124 		if (!irqchip_kernel(kvm))
7125 			goto get_irqchip_out;
7126 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7127 		if (r)
7128 			goto get_irqchip_out;
7129 		r = -EFAULT;
7130 		if (copy_to_user(argp, chip, sizeof(*chip)))
7131 			goto get_irqchip_out;
7132 		r = 0;
7133 	get_irqchip_out:
7134 		kfree(chip);
7135 		break;
7136 	}
7137 	case KVM_SET_IRQCHIP: {
7138 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7139 		struct kvm_irqchip *chip;
7140 
7141 		chip = memdup_user(argp, sizeof(*chip));
7142 		if (IS_ERR(chip)) {
7143 			r = PTR_ERR(chip);
7144 			goto out;
7145 		}
7146 
7147 		r = -ENXIO;
7148 		if (!irqchip_kernel(kvm))
7149 			goto set_irqchip_out;
7150 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7151 	set_irqchip_out:
7152 		kfree(chip);
7153 		break;
7154 	}
7155 	case KVM_GET_PIT: {
7156 		r = -EFAULT;
7157 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7158 			goto out;
7159 		r = -ENXIO;
7160 		if (!kvm->arch.vpit)
7161 			goto out;
7162 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7163 		if (r)
7164 			goto out;
7165 		r = -EFAULT;
7166 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7167 			goto out;
7168 		r = 0;
7169 		break;
7170 	}
7171 	case KVM_SET_PIT: {
7172 		r = -EFAULT;
7173 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7174 			goto out;
7175 		mutex_lock(&kvm->lock);
7176 		r = -ENXIO;
7177 		if (!kvm->arch.vpit)
7178 			goto set_pit_out;
7179 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7180 set_pit_out:
7181 		mutex_unlock(&kvm->lock);
7182 		break;
7183 	}
7184 	case KVM_GET_PIT2: {
7185 		r = -ENXIO;
7186 		if (!kvm->arch.vpit)
7187 			goto out;
7188 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7189 		if (r)
7190 			goto out;
7191 		r = -EFAULT;
7192 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7193 			goto out;
7194 		r = 0;
7195 		break;
7196 	}
7197 	case KVM_SET_PIT2: {
7198 		r = -EFAULT;
7199 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7200 			goto out;
7201 		mutex_lock(&kvm->lock);
7202 		r = -ENXIO;
7203 		if (!kvm->arch.vpit)
7204 			goto set_pit2_out;
7205 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7206 set_pit2_out:
7207 		mutex_unlock(&kvm->lock);
7208 		break;
7209 	}
7210 	case KVM_REINJECT_CONTROL: {
7211 		struct kvm_reinject_control control;
7212 		r =  -EFAULT;
7213 		if (copy_from_user(&control, argp, sizeof(control)))
7214 			goto out;
7215 		r = -ENXIO;
7216 		if (!kvm->arch.vpit)
7217 			goto out;
7218 		r = kvm_vm_ioctl_reinject(kvm, &control);
7219 		break;
7220 	}
7221 	case KVM_SET_BOOT_CPU_ID:
7222 		r = 0;
7223 		mutex_lock(&kvm->lock);
7224 		if (kvm->created_vcpus)
7225 			r = -EBUSY;
7226 		else if (arg > KVM_MAX_VCPU_IDS ||
7227 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7228 			r = -EINVAL;
7229 		else
7230 			kvm->arch.bsp_vcpu_id = arg;
7231 		mutex_unlock(&kvm->lock);
7232 		break;
7233 #ifdef CONFIG_KVM_XEN
7234 	case KVM_XEN_HVM_CONFIG: {
7235 		struct kvm_xen_hvm_config xhc;
7236 		r = -EFAULT;
7237 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
7238 			goto out;
7239 		r = kvm_xen_hvm_config(kvm, &xhc);
7240 		break;
7241 	}
7242 	case KVM_XEN_HVM_GET_ATTR: {
7243 		struct kvm_xen_hvm_attr xha;
7244 
7245 		r = -EFAULT;
7246 		if (copy_from_user(&xha, argp, sizeof(xha)))
7247 			goto out;
7248 		r = kvm_xen_hvm_get_attr(kvm, &xha);
7249 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7250 			r = -EFAULT;
7251 		break;
7252 	}
7253 	case KVM_XEN_HVM_SET_ATTR: {
7254 		struct kvm_xen_hvm_attr xha;
7255 
7256 		r = -EFAULT;
7257 		if (copy_from_user(&xha, argp, sizeof(xha)))
7258 			goto out;
7259 		r = kvm_xen_hvm_set_attr(kvm, &xha);
7260 		break;
7261 	}
7262 	case KVM_XEN_HVM_EVTCHN_SEND: {
7263 		struct kvm_irq_routing_xen_evtchn uxe;
7264 
7265 		r = -EFAULT;
7266 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
7267 			goto out;
7268 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7269 		break;
7270 	}
7271 #endif
7272 	case KVM_SET_CLOCK:
7273 		r = kvm_vm_ioctl_set_clock(kvm, argp);
7274 		break;
7275 	case KVM_GET_CLOCK:
7276 		r = kvm_vm_ioctl_get_clock(kvm, argp);
7277 		break;
7278 	case KVM_SET_TSC_KHZ: {
7279 		u32 user_tsc_khz;
7280 
7281 		r = -EINVAL;
7282 		user_tsc_khz = (u32)arg;
7283 
7284 		if (kvm_caps.has_tsc_control &&
7285 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7286 			goto out;
7287 
7288 		if (user_tsc_khz == 0)
7289 			user_tsc_khz = tsc_khz;
7290 
7291 		WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7292 		r = 0;
7293 
7294 		goto out;
7295 	}
7296 	case KVM_GET_TSC_KHZ: {
7297 		r = READ_ONCE(kvm->arch.default_tsc_khz);
7298 		goto out;
7299 	}
7300 	case KVM_MEMORY_ENCRYPT_OP: {
7301 		r = -ENOTTY;
7302 		if (!kvm_x86_ops.mem_enc_ioctl)
7303 			goto out;
7304 
7305 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7306 		break;
7307 	}
7308 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
7309 		struct kvm_enc_region region;
7310 
7311 		r = -EFAULT;
7312 		if (copy_from_user(&region, argp, sizeof(region)))
7313 			goto out;
7314 
7315 		r = -ENOTTY;
7316 		if (!kvm_x86_ops.mem_enc_register_region)
7317 			goto out;
7318 
7319 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
7320 		break;
7321 	}
7322 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7323 		struct kvm_enc_region region;
7324 
7325 		r = -EFAULT;
7326 		if (copy_from_user(&region, argp, sizeof(region)))
7327 			goto out;
7328 
7329 		r = -ENOTTY;
7330 		if (!kvm_x86_ops.mem_enc_unregister_region)
7331 			goto out;
7332 
7333 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
7334 		break;
7335 	}
7336 #ifdef CONFIG_KVM_HYPERV
7337 	case KVM_HYPERV_EVENTFD: {
7338 		struct kvm_hyperv_eventfd hvevfd;
7339 
7340 		r = -EFAULT;
7341 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7342 			goto out;
7343 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7344 		break;
7345 	}
7346 #endif
7347 	case KVM_SET_PMU_EVENT_FILTER:
7348 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7349 		break;
7350 	case KVM_X86_SET_MSR_FILTER: {
7351 		struct kvm_msr_filter __user *user_msr_filter = argp;
7352 		struct kvm_msr_filter filter;
7353 
7354 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7355 			return -EFAULT;
7356 
7357 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7358 		break;
7359 	}
7360 	default:
7361 		r = -ENOTTY;
7362 	}
7363 out:
7364 	return r;
7365 }
7366 
kvm_probe_feature_msr(u32 msr_index)7367 static void kvm_probe_feature_msr(u32 msr_index)
7368 {
7369 	u64 data;
7370 
7371 	if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7372 		return;
7373 
7374 	msr_based_features[num_msr_based_features++] = msr_index;
7375 }
7376 
kvm_probe_msr_to_save(u32 msr_index)7377 static void kvm_probe_msr_to_save(u32 msr_index)
7378 {
7379 	u32 dummy[2];
7380 
7381 	if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7382 		return;
7383 
7384 	/*
7385 	 * Even MSRs that are valid in the host may not be exposed to guests in
7386 	 * some cases.
7387 	 */
7388 	switch (msr_index) {
7389 	case MSR_IA32_BNDCFGS:
7390 		if (!kvm_mpx_supported())
7391 			return;
7392 		break;
7393 	case MSR_TSC_AUX:
7394 		if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7395 		    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7396 			return;
7397 		break;
7398 	case MSR_IA32_UMWAIT_CONTROL:
7399 		if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7400 			return;
7401 		break;
7402 	case MSR_IA32_RTIT_CTL:
7403 	case MSR_IA32_RTIT_STATUS:
7404 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7405 			return;
7406 		break;
7407 	case MSR_IA32_RTIT_CR3_MATCH:
7408 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7409 		    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7410 			return;
7411 		break;
7412 	case MSR_IA32_RTIT_OUTPUT_BASE:
7413 	case MSR_IA32_RTIT_OUTPUT_MASK:
7414 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7415 		    (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7416 		     !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7417 			return;
7418 		break;
7419 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7420 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7421 		    (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7422 		     intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7423 			return;
7424 		break;
7425 	case MSR_ARCH_PERFMON_PERFCTR0 ...
7426 	     MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7427 		if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7428 		    kvm_pmu_cap.num_counters_gp)
7429 			return;
7430 		break;
7431 	case MSR_ARCH_PERFMON_EVENTSEL0 ...
7432 	     MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7433 		if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7434 		    kvm_pmu_cap.num_counters_gp)
7435 			return;
7436 		break;
7437 	case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7438 	     MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7439 		if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7440 		    kvm_pmu_cap.num_counters_fixed)
7441 			return;
7442 		break;
7443 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7444 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7445 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7446 		if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7447 			return;
7448 		break;
7449 	case MSR_IA32_XFD:
7450 	case MSR_IA32_XFD_ERR:
7451 		if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7452 			return;
7453 		break;
7454 	case MSR_IA32_TSX_CTRL:
7455 		if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7456 			return;
7457 		break;
7458 	default:
7459 		break;
7460 	}
7461 
7462 	msrs_to_save[num_msrs_to_save++] = msr_index;
7463 }
7464 
kvm_init_msr_lists(void)7465 static void kvm_init_msr_lists(void)
7466 {
7467 	unsigned i;
7468 
7469 	BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7470 			 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7471 
7472 	num_msrs_to_save = 0;
7473 	num_emulated_msrs = 0;
7474 	num_msr_based_features = 0;
7475 
7476 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7477 		kvm_probe_msr_to_save(msrs_to_save_base[i]);
7478 
7479 	if (enable_pmu) {
7480 		for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7481 			kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7482 	}
7483 
7484 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7485 		if (!kvm_x86_call(has_emulated_msr)(NULL,
7486 						    emulated_msrs_all[i]))
7487 			continue;
7488 
7489 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7490 	}
7491 
7492 	for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7493 		kvm_probe_feature_msr(i);
7494 
7495 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7496 		kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7497 }
7498 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7499 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7500 			   const void *v)
7501 {
7502 	int handled = 0;
7503 	int n;
7504 
7505 	do {
7506 		n = min(len, 8);
7507 		if (!(lapic_in_kernel(vcpu) &&
7508 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7509 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7510 			break;
7511 		handled += n;
7512 		addr += n;
7513 		len -= n;
7514 		v += n;
7515 	} while (len);
7516 
7517 	return handled;
7518 }
7519 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7520 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7521 {
7522 	int handled = 0;
7523 	int n;
7524 
7525 	do {
7526 		n = min(len, 8);
7527 		if (!(lapic_in_kernel(vcpu) &&
7528 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7529 					 addr, n, v))
7530 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7531 			break;
7532 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7533 		handled += n;
7534 		addr += n;
7535 		len -= n;
7536 		v += n;
7537 	} while (len);
7538 
7539 	return handled;
7540 }
7541 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7542 void kvm_set_segment(struct kvm_vcpu *vcpu,
7543 		     struct kvm_segment *var, int seg)
7544 {
7545 	kvm_x86_call(set_segment)(vcpu, var, seg);
7546 }
7547 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7548 void kvm_get_segment(struct kvm_vcpu *vcpu,
7549 		     struct kvm_segment *var, int seg)
7550 {
7551 	kvm_x86_call(get_segment)(vcpu, var, seg);
7552 }
7553 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7554 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7555 			   struct x86_exception *exception)
7556 {
7557 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7558 	gpa_t t_gpa;
7559 
7560 	BUG_ON(!mmu_is_nested(vcpu));
7561 
7562 	/* NPT walks are always user-walks */
7563 	access |= PFERR_USER_MASK;
7564 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7565 
7566 	return t_gpa;
7567 }
7568 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7569 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7570 			      struct x86_exception *exception)
7571 {
7572 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7573 
7574 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7575 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7576 }
7577 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7578 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7579 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7580 			       struct x86_exception *exception)
7581 {
7582 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7583 
7584 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7585 	access |= PFERR_WRITE_MASK;
7586 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7587 }
7588 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7589 
7590 /* 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)7591 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7592 				struct x86_exception *exception)
7593 {
7594 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7595 
7596 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7597 }
7598 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7599 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7600 				      struct kvm_vcpu *vcpu, u64 access,
7601 				      struct x86_exception *exception)
7602 {
7603 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7604 	void *data = val;
7605 	int r = X86EMUL_CONTINUE;
7606 
7607 	while (bytes) {
7608 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7609 		unsigned offset = addr & (PAGE_SIZE-1);
7610 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7611 		int ret;
7612 
7613 		if (gpa == INVALID_GPA)
7614 			return X86EMUL_PROPAGATE_FAULT;
7615 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7616 					       offset, toread);
7617 		if (ret < 0) {
7618 			r = X86EMUL_IO_NEEDED;
7619 			goto out;
7620 		}
7621 
7622 		bytes -= toread;
7623 		data += toread;
7624 		addr += toread;
7625 	}
7626 out:
7627 	return r;
7628 }
7629 
7630 /* 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)7631 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7632 				gva_t addr, void *val, unsigned int bytes,
7633 				struct x86_exception *exception)
7634 {
7635 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7636 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7637 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7638 	unsigned offset;
7639 	int ret;
7640 
7641 	/* Inline kvm_read_guest_virt_helper for speed.  */
7642 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7643 				    exception);
7644 	if (unlikely(gpa == INVALID_GPA))
7645 		return X86EMUL_PROPAGATE_FAULT;
7646 
7647 	offset = addr & (PAGE_SIZE-1);
7648 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7649 		bytes = (unsigned)PAGE_SIZE - offset;
7650 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7651 				       offset, bytes);
7652 	if (unlikely(ret < 0))
7653 		return X86EMUL_IO_NEEDED;
7654 
7655 	return X86EMUL_CONTINUE;
7656 }
7657 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7658 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7659 			       gva_t addr, void *val, unsigned int bytes,
7660 			       struct x86_exception *exception)
7661 {
7662 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7663 
7664 	/*
7665 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7666 	 * is returned, but our callers are not ready for that and they blindly
7667 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7668 	 * uninitialized kernel stack memory into cr2 and error code.
7669 	 */
7670 	memset(exception, 0, sizeof(*exception));
7671 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7672 					  exception);
7673 }
7674 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7675 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7676 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7677 			     gva_t addr, void *val, unsigned int bytes,
7678 			     struct x86_exception *exception, bool system)
7679 {
7680 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7681 	u64 access = 0;
7682 
7683 	if (system)
7684 		access |= PFERR_IMPLICIT_ACCESS;
7685 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7686 		access |= PFERR_USER_MASK;
7687 
7688 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7689 }
7690 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7691 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7692 				      struct kvm_vcpu *vcpu, u64 access,
7693 				      struct x86_exception *exception)
7694 {
7695 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7696 	void *data = val;
7697 	int r = X86EMUL_CONTINUE;
7698 
7699 	while (bytes) {
7700 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7701 		unsigned offset = addr & (PAGE_SIZE-1);
7702 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7703 		int ret;
7704 
7705 		if (gpa == INVALID_GPA)
7706 			return X86EMUL_PROPAGATE_FAULT;
7707 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7708 		if (ret < 0) {
7709 			r = X86EMUL_IO_NEEDED;
7710 			goto out;
7711 		}
7712 
7713 		bytes -= towrite;
7714 		data += towrite;
7715 		addr += towrite;
7716 	}
7717 out:
7718 	return r;
7719 }
7720 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7721 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7722 			      unsigned int bytes, struct x86_exception *exception,
7723 			      bool system)
7724 {
7725 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7726 	u64 access = PFERR_WRITE_MASK;
7727 
7728 	if (system)
7729 		access |= PFERR_IMPLICIT_ACCESS;
7730 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7731 		access |= PFERR_USER_MASK;
7732 
7733 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7734 					   access, exception);
7735 }
7736 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7737 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7738 				unsigned int bytes, struct x86_exception *exception)
7739 {
7740 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7741 	vcpu->arch.l1tf_flush_l1d = true;
7742 
7743 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7744 					   PFERR_WRITE_MASK, exception);
7745 }
7746 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7747 
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7748 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7749 				  void *insn, int insn_len)
7750 {
7751 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7752 						       insn, insn_len);
7753 }
7754 
handle_ud(struct kvm_vcpu * vcpu)7755 int handle_ud(struct kvm_vcpu *vcpu)
7756 {
7757 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7758 	int fep_flags = READ_ONCE(force_emulation_prefix);
7759 	int emul_type = EMULTYPE_TRAP_UD;
7760 	char sig[5]; /* ud2; .ascii "kvm" */
7761 	struct x86_exception e;
7762 	int r;
7763 
7764 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7765 	if (r != X86EMUL_CONTINUE)
7766 		return 1;
7767 
7768 	if (fep_flags &&
7769 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7770 				sig, sizeof(sig), &e) == 0 &&
7771 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7772 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7773 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7774 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7775 		emul_type = EMULTYPE_TRAP_UD_FORCED;
7776 	}
7777 
7778 	return kvm_emulate_instruction(vcpu, emul_type);
7779 }
7780 EXPORT_SYMBOL_GPL(handle_ud);
7781 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)7782 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7783 			    gpa_t gpa, bool write)
7784 {
7785 	/* For APIC access vmexit */
7786 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7787 		return 1;
7788 
7789 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7790 		trace_vcpu_match_mmio(gva, gpa, write, true);
7791 		return 1;
7792 	}
7793 
7794 	return 0;
7795 }
7796 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)7797 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7798 				gpa_t *gpa, struct x86_exception *exception,
7799 				bool write)
7800 {
7801 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7802 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7803 		     | (write ? PFERR_WRITE_MASK : 0);
7804 
7805 	/*
7806 	 * currently PKRU is only applied to ept enabled guest so
7807 	 * there is no pkey in EPT page table for L1 guest or EPT
7808 	 * shadow page table for L2 guest.
7809 	 */
7810 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7811 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
7812 			      vcpu->arch.mmio_access, 0, access))) {
7813 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7814 					(gva & (PAGE_SIZE - 1));
7815 		trace_vcpu_match_mmio(gva, *gpa, write, false);
7816 		return 1;
7817 	}
7818 
7819 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7820 
7821 	if (*gpa == INVALID_GPA)
7822 		return -1;
7823 
7824 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7825 }
7826 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)7827 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7828 			const void *val, int bytes)
7829 {
7830 	int ret;
7831 
7832 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7833 	if (ret < 0)
7834 		return 0;
7835 	kvm_page_track_write(vcpu, gpa, val, bytes);
7836 	return 1;
7837 }
7838 
7839 struct read_write_emulator_ops {
7840 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7841 				  int bytes);
7842 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7843 				  void *val, int bytes);
7844 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7845 			       int bytes, void *val);
7846 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7847 				    void *val, int bytes);
7848 	bool write;
7849 };
7850 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)7851 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7852 {
7853 	if (vcpu->mmio_read_completed) {
7854 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7855 			       vcpu->mmio_fragments[0].gpa, val);
7856 		vcpu->mmio_read_completed = 0;
7857 		return 1;
7858 	}
7859 
7860 	return 0;
7861 }
7862 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7863 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7864 			void *val, int bytes)
7865 {
7866 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7867 }
7868 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7869 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7870 			 void *val, int bytes)
7871 {
7872 	return emulator_write_phys(vcpu, gpa, val, bytes);
7873 }
7874 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)7875 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7876 {
7877 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7878 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
7879 }
7880 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7881 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7882 			  void *val, int bytes)
7883 {
7884 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7885 	return X86EMUL_IO_NEEDED;
7886 }
7887 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7888 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7889 			   void *val, int bytes)
7890 {
7891 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7892 
7893 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7894 	return X86EMUL_CONTINUE;
7895 }
7896 
7897 static const struct read_write_emulator_ops read_emultor = {
7898 	.read_write_prepare = read_prepare,
7899 	.read_write_emulate = read_emulate,
7900 	.read_write_mmio = vcpu_mmio_read,
7901 	.read_write_exit_mmio = read_exit_mmio,
7902 };
7903 
7904 static const struct read_write_emulator_ops write_emultor = {
7905 	.read_write_emulate = write_emulate,
7906 	.read_write_mmio = write_mmio,
7907 	.read_write_exit_mmio = write_exit_mmio,
7908 	.write = true,
7909 };
7910 
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)7911 static int emulator_read_write_onepage(unsigned long addr, void *val,
7912 				       unsigned int bytes,
7913 				       struct x86_exception *exception,
7914 				       struct kvm_vcpu *vcpu,
7915 				       const struct read_write_emulator_ops *ops)
7916 {
7917 	gpa_t gpa;
7918 	int handled, ret;
7919 	bool write = ops->write;
7920 	struct kvm_mmio_fragment *frag;
7921 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7922 
7923 	/*
7924 	 * If the exit was due to a NPF we may already have a GPA.
7925 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7926 	 * Note, this cannot be used on string operations since string
7927 	 * operation using rep will only have the initial GPA from the NPF
7928 	 * occurred.
7929 	 */
7930 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7931 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7932 		gpa = ctxt->gpa_val;
7933 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7934 	} else {
7935 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7936 		if (ret < 0)
7937 			return X86EMUL_PROPAGATE_FAULT;
7938 	}
7939 
7940 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7941 		return X86EMUL_CONTINUE;
7942 
7943 	/*
7944 	 * Is this MMIO handled locally?
7945 	 */
7946 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7947 	if (handled == bytes)
7948 		return X86EMUL_CONTINUE;
7949 
7950 	gpa += handled;
7951 	bytes -= handled;
7952 	val += handled;
7953 
7954 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7955 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7956 	frag->gpa = gpa;
7957 	frag->data = val;
7958 	frag->len = bytes;
7959 	return X86EMUL_CONTINUE;
7960 }
7961 
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)7962 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7963 			unsigned long addr,
7964 			void *val, unsigned int bytes,
7965 			struct x86_exception *exception,
7966 			const struct read_write_emulator_ops *ops)
7967 {
7968 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7969 	gpa_t gpa;
7970 	int rc;
7971 
7972 	if (ops->read_write_prepare &&
7973 		  ops->read_write_prepare(vcpu, val, bytes))
7974 		return X86EMUL_CONTINUE;
7975 
7976 	vcpu->mmio_nr_fragments = 0;
7977 
7978 	/* Crossing a page boundary? */
7979 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7980 		int now;
7981 
7982 		now = -addr & ~PAGE_MASK;
7983 		rc = emulator_read_write_onepage(addr, val, now, exception,
7984 						 vcpu, ops);
7985 
7986 		if (rc != X86EMUL_CONTINUE)
7987 			return rc;
7988 		addr += now;
7989 		if (ctxt->mode != X86EMUL_MODE_PROT64)
7990 			addr = (u32)addr;
7991 		val += now;
7992 		bytes -= now;
7993 	}
7994 
7995 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
7996 					 vcpu, ops);
7997 	if (rc != X86EMUL_CONTINUE)
7998 		return rc;
7999 
8000 	if (!vcpu->mmio_nr_fragments)
8001 		return rc;
8002 
8003 	gpa = vcpu->mmio_fragments[0].gpa;
8004 
8005 	vcpu->mmio_needed = 1;
8006 	vcpu->mmio_cur_fragment = 0;
8007 
8008 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8009 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8010 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
8011 	vcpu->run->mmio.phys_addr = gpa;
8012 
8013 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8014 }
8015 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8016 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8017 				  unsigned long addr,
8018 				  void *val,
8019 				  unsigned int bytes,
8020 				  struct x86_exception *exception)
8021 {
8022 	return emulator_read_write(ctxt, addr, val, bytes,
8023 				   exception, &read_emultor);
8024 }
8025 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8026 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8027 			    unsigned long addr,
8028 			    const void *val,
8029 			    unsigned int bytes,
8030 			    struct x86_exception *exception)
8031 {
8032 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
8033 				   exception, &write_emultor);
8034 }
8035 
8036 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8037 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8038 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8039 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8040 				     unsigned long addr,
8041 				     const void *old,
8042 				     const void *new,
8043 				     unsigned int bytes,
8044 				     struct x86_exception *exception)
8045 {
8046 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8047 	u64 page_line_mask;
8048 	unsigned long hva;
8049 	gpa_t gpa;
8050 	int r;
8051 
8052 	/* guests cmpxchg8b have to be emulated atomically */
8053 	if (bytes > 8 || (bytes & (bytes - 1)))
8054 		goto emul_write;
8055 
8056 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8057 
8058 	if (gpa == INVALID_GPA ||
8059 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8060 		goto emul_write;
8061 
8062 	/*
8063 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
8064 	 * enabled in the host and the access splits a cache line.
8065 	 */
8066 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8067 		page_line_mask = ~(cache_line_size() - 1);
8068 	else
8069 		page_line_mask = PAGE_MASK;
8070 
8071 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8072 		goto emul_write;
8073 
8074 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8075 	if (kvm_is_error_hva(hva))
8076 		goto emul_write;
8077 
8078 	hva += offset_in_page(gpa);
8079 
8080 	switch (bytes) {
8081 	case 1:
8082 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
8083 		break;
8084 	case 2:
8085 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
8086 		break;
8087 	case 4:
8088 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
8089 		break;
8090 	case 8:
8091 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
8092 		break;
8093 	default:
8094 		BUG();
8095 	}
8096 
8097 	if (r < 0)
8098 		return X86EMUL_UNHANDLEABLE;
8099 
8100 	/*
8101 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8102 	 * successful, as the old value is written back on failure.  Note, for
8103 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
8104 	 * back the original value and the access is atomic, but KVM's ABI is
8105 	 * that all writes are dirty logged, regardless of the value written.
8106 	 */
8107 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8108 
8109 	if (r)
8110 		return X86EMUL_CMPXCHG_FAILED;
8111 
8112 	kvm_page_track_write(vcpu, gpa, new, bytes);
8113 
8114 	return X86EMUL_CONTINUE;
8115 
8116 emul_write:
8117 	pr_warn_once("emulating exchange as write\n");
8118 
8119 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8120 }
8121 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8122 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8123 			       unsigned short port, void *data,
8124 			       unsigned int count, bool in)
8125 {
8126 	unsigned i;
8127 	int r;
8128 
8129 	WARN_ON_ONCE(vcpu->arch.pio.count);
8130 	for (i = 0; i < count; i++) {
8131 		if (in)
8132 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8133 		else
8134 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8135 
8136 		if (r) {
8137 			if (i == 0)
8138 				goto userspace_io;
8139 
8140 			/*
8141 			 * Userspace must have unregistered the device while PIO
8142 			 * was running.  Drop writes / read as 0.
8143 			 */
8144 			if (in)
8145 				memset(data, 0, size * (count - i));
8146 			break;
8147 		}
8148 
8149 		data += size;
8150 	}
8151 	return 1;
8152 
8153 userspace_io:
8154 	vcpu->arch.pio.port = port;
8155 	vcpu->arch.pio.in = in;
8156 	vcpu->arch.pio.count = count;
8157 	vcpu->arch.pio.size = size;
8158 
8159 	if (in)
8160 		memset(vcpu->arch.pio_data, 0, size * count);
8161 	else
8162 		memcpy(vcpu->arch.pio_data, data, size * count);
8163 
8164 	vcpu->run->exit_reason = KVM_EXIT_IO;
8165 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8166 	vcpu->run->io.size = size;
8167 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8168 	vcpu->run->io.count = count;
8169 	vcpu->run->io.port = port;
8170 	return 0;
8171 }
8172 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8173 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8174       			   unsigned short port, void *val, unsigned int count)
8175 {
8176 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8177 	if (r)
8178 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8179 
8180 	return r;
8181 }
8182 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8183 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8184 {
8185 	int size = vcpu->arch.pio.size;
8186 	unsigned int count = vcpu->arch.pio.count;
8187 	memcpy(val, vcpu->arch.pio_data, size * count);
8188 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8189 	vcpu->arch.pio.count = 0;
8190 }
8191 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8192 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8193 				    int size, unsigned short port, void *val,
8194 				    unsigned int count)
8195 {
8196 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8197 	if (vcpu->arch.pio.count) {
8198 		/*
8199 		 * Complete a previous iteration that required userspace I/O.
8200 		 * Note, @count isn't guaranteed to match pio.count as userspace
8201 		 * can modify ECX before rerunning the vCPU.  Ignore any such
8202 		 * shenanigans as KVM doesn't support modifying the rep count,
8203 		 * and the emulator ensures @count doesn't overflow the buffer.
8204 		 */
8205 		complete_emulator_pio_in(vcpu, val);
8206 		return 1;
8207 	}
8208 
8209 	return emulator_pio_in(vcpu, size, port, val, count);
8210 }
8211 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8212 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8213 			    unsigned short port, const void *val,
8214 			    unsigned int count)
8215 {
8216 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8217 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8218 }
8219 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8220 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8221 				     int size, unsigned short port,
8222 				     const void *val, unsigned int count)
8223 {
8224 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8225 }
8226 
get_segment_base(struct kvm_vcpu * vcpu,int seg)8227 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8228 {
8229 	return kvm_x86_call(get_segment_base)(vcpu, seg);
8230 }
8231 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8232 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8233 {
8234 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8235 }
8236 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8237 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8238 {
8239 	if (!need_emulate_wbinvd(vcpu))
8240 		return X86EMUL_CONTINUE;
8241 
8242 	if (kvm_x86_call(has_wbinvd_exit)()) {
8243 		int cpu = get_cpu();
8244 
8245 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8246 		on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
8247 				wbinvd_ipi, NULL, 1);
8248 		put_cpu();
8249 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8250 	} else
8251 		wbinvd();
8252 	return X86EMUL_CONTINUE;
8253 }
8254 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8255 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8256 {
8257 	kvm_emulate_wbinvd_noskip(vcpu);
8258 	return kvm_skip_emulated_instruction(vcpu);
8259 }
8260 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8261 
8262 
8263 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8264 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8265 {
8266 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8267 }
8268 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8269 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8270 {
8271 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8272 }
8273 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8274 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8275 			   unsigned long value)
8276 {
8277 
8278 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8279 }
8280 
mk_cr_64(u64 curr_cr,u32 new_val)8281 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8282 {
8283 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8284 }
8285 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8286 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8287 {
8288 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8289 	unsigned long value;
8290 
8291 	switch (cr) {
8292 	case 0:
8293 		value = kvm_read_cr0(vcpu);
8294 		break;
8295 	case 2:
8296 		value = vcpu->arch.cr2;
8297 		break;
8298 	case 3:
8299 		value = kvm_read_cr3(vcpu);
8300 		break;
8301 	case 4:
8302 		value = kvm_read_cr4(vcpu);
8303 		break;
8304 	case 8:
8305 		value = kvm_get_cr8(vcpu);
8306 		break;
8307 	default:
8308 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8309 		return 0;
8310 	}
8311 
8312 	return value;
8313 }
8314 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8315 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8316 {
8317 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8318 	int res = 0;
8319 
8320 	switch (cr) {
8321 	case 0:
8322 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8323 		break;
8324 	case 2:
8325 		vcpu->arch.cr2 = val;
8326 		break;
8327 	case 3:
8328 		res = kvm_set_cr3(vcpu, val);
8329 		break;
8330 	case 4:
8331 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8332 		break;
8333 	case 8:
8334 		res = kvm_set_cr8(vcpu, val);
8335 		break;
8336 	default:
8337 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8338 		res = -1;
8339 	}
8340 
8341 	return res;
8342 }
8343 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8344 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8345 {
8346 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8347 }
8348 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8349 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8350 {
8351 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8352 }
8353 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8354 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8355 {
8356 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8357 }
8358 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8359 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8360 {
8361 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8362 }
8363 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8364 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8365 {
8366 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8367 }
8368 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8369 static unsigned long emulator_get_cached_segment_base(
8370 	struct x86_emulate_ctxt *ctxt, int seg)
8371 {
8372 	return get_segment_base(emul_to_vcpu(ctxt), seg);
8373 }
8374 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8375 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8376 				 struct desc_struct *desc, u32 *base3,
8377 				 int seg)
8378 {
8379 	struct kvm_segment var;
8380 
8381 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8382 	*selector = var.selector;
8383 
8384 	if (var.unusable) {
8385 		memset(desc, 0, sizeof(*desc));
8386 		if (base3)
8387 			*base3 = 0;
8388 		return false;
8389 	}
8390 
8391 	if (var.g)
8392 		var.limit >>= 12;
8393 	set_desc_limit(desc, var.limit);
8394 	set_desc_base(desc, (unsigned long)var.base);
8395 #ifdef CONFIG_X86_64
8396 	if (base3)
8397 		*base3 = var.base >> 32;
8398 #endif
8399 	desc->type = var.type;
8400 	desc->s = var.s;
8401 	desc->dpl = var.dpl;
8402 	desc->p = var.present;
8403 	desc->avl = var.avl;
8404 	desc->l = var.l;
8405 	desc->d = var.db;
8406 	desc->g = var.g;
8407 
8408 	return true;
8409 }
8410 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8411 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8412 				 struct desc_struct *desc, u32 base3,
8413 				 int seg)
8414 {
8415 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8416 	struct kvm_segment var;
8417 
8418 	var.selector = selector;
8419 	var.base = get_desc_base(desc);
8420 #ifdef CONFIG_X86_64
8421 	var.base |= ((u64)base3) << 32;
8422 #endif
8423 	var.limit = get_desc_limit(desc);
8424 	if (desc->g)
8425 		var.limit = (var.limit << 12) | 0xfff;
8426 	var.type = desc->type;
8427 	var.dpl = desc->dpl;
8428 	var.db = desc->d;
8429 	var.s = desc->s;
8430 	var.l = desc->l;
8431 	var.g = desc->g;
8432 	var.avl = desc->avl;
8433 	var.present = desc->p;
8434 	var.unusable = !var.present;
8435 	var.padding = 0;
8436 
8437 	kvm_set_segment(vcpu, &var, seg);
8438 	return;
8439 }
8440 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8441 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8442 					u32 msr_index, u64 *pdata)
8443 {
8444 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8445 	int r;
8446 
8447 	r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8448 	if (r < 0)
8449 		return X86EMUL_UNHANDLEABLE;
8450 
8451 	if (r) {
8452 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8453 				       complete_emulated_rdmsr, r))
8454 			return X86EMUL_IO_NEEDED;
8455 
8456 		trace_kvm_msr_read_ex(msr_index);
8457 		return X86EMUL_PROPAGATE_FAULT;
8458 	}
8459 
8460 	trace_kvm_msr_read(msr_index, *pdata);
8461 	return X86EMUL_CONTINUE;
8462 }
8463 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8464 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8465 					u32 msr_index, u64 data)
8466 {
8467 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8468 	int r;
8469 
8470 	r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8471 	if (r < 0)
8472 		return X86EMUL_UNHANDLEABLE;
8473 
8474 	if (r) {
8475 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8476 				       complete_emulated_msr_access, r))
8477 			return X86EMUL_IO_NEEDED;
8478 
8479 		trace_kvm_msr_write_ex(msr_index, data);
8480 		return X86EMUL_PROPAGATE_FAULT;
8481 	}
8482 
8483 	trace_kvm_msr_write(msr_index, data);
8484 	return X86EMUL_CONTINUE;
8485 }
8486 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8487 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8488 			    u32 msr_index, u64 *pdata)
8489 {
8490 	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8491 }
8492 
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8493 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8494 {
8495 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8496 }
8497 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8498 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8499 			     u32 pmc, u64 *pdata)
8500 {
8501 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8502 }
8503 
emulator_halt(struct x86_emulate_ctxt * ctxt)8504 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8505 {
8506 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8507 }
8508 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8509 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8510 			      struct x86_instruction_info *info,
8511 			      enum x86_intercept_stage stage)
8512 {
8513 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8514 					     &ctxt->exception);
8515 }
8516 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8517 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8518 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8519 			      bool exact_only)
8520 {
8521 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8522 }
8523 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8524 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8525 {
8526 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8527 }
8528 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8529 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8530 {
8531 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8532 }
8533 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8534 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8535 {
8536 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8537 }
8538 
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8539 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8540 {
8541 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8542 }
8543 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8544 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8545 {
8546 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8547 }
8548 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8549 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8550 {
8551 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8552 }
8553 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8554 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8555 {
8556 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8557 }
8558 
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8559 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8560 {
8561 	return is_smm(emul_to_vcpu(ctxt));
8562 }
8563 
emulator_is_guest_mode(struct x86_emulate_ctxt * ctxt)8564 static bool emulator_is_guest_mode(struct x86_emulate_ctxt *ctxt)
8565 {
8566 	return is_guest_mode(emul_to_vcpu(ctxt));
8567 }
8568 
8569 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8570 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8571 {
8572 	WARN_ON_ONCE(1);
8573 	return X86EMUL_UNHANDLEABLE;
8574 }
8575 #endif
8576 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8577 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8578 {
8579 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8580 }
8581 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8582 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8583 {
8584 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8585 }
8586 
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8587 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8588 {
8589 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8590 
8591 	if (!kvm->vm_bugged)
8592 		kvm_vm_bugged(kvm);
8593 }
8594 
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8595 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8596 					gva_t addr, unsigned int flags)
8597 {
8598 	if (!kvm_x86_ops.get_untagged_addr)
8599 		return addr;
8600 
8601 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8602 					       addr, flags);
8603 }
8604 
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8605 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8606 				       gva_t addr, unsigned int flags)
8607 {
8608 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8609 }
8610 
8611 static const struct x86_emulate_ops emulate_ops = {
8612 	.vm_bugged           = emulator_vm_bugged,
8613 	.read_gpr            = emulator_read_gpr,
8614 	.write_gpr           = emulator_write_gpr,
8615 	.read_std            = emulator_read_std,
8616 	.write_std           = emulator_write_std,
8617 	.fetch               = kvm_fetch_guest_virt,
8618 	.read_emulated       = emulator_read_emulated,
8619 	.write_emulated      = emulator_write_emulated,
8620 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8621 	.invlpg              = emulator_invlpg,
8622 	.pio_in_emulated     = emulator_pio_in_emulated,
8623 	.pio_out_emulated    = emulator_pio_out_emulated,
8624 	.get_segment         = emulator_get_segment,
8625 	.set_segment         = emulator_set_segment,
8626 	.get_cached_segment_base = emulator_get_cached_segment_base,
8627 	.get_gdt             = emulator_get_gdt,
8628 	.get_idt	     = emulator_get_idt,
8629 	.set_gdt             = emulator_set_gdt,
8630 	.set_idt	     = emulator_set_idt,
8631 	.get_cr              = emulator_get_cr,
8632 	.set_cr              = emulator_set_cr,
8633 	.cpl                 = emulator_get_cpl,
8634 	.get_dr              = emulator_get_dr,
8635 	.set_dr              = emulator_set_dr,
8636 	.set_msr_with_filter = emulator_set_msr_with_filter,
8637 	.get_msr_with_filter = emulator_get_msr_with_filter,
8638 	.get_msr             = emulator_get_msr,
8639 	.check_rdpmc_early   = emulator_check_rdpmc_early,
8640 	.read_pmc            = emulator_read_pmc,
8641 	.halt                = emulator_halt,
8642 	.wbinvd              = emulator_wbinvd,
8643 	.fix_hypercall       = emulator_fix_hypercall,
8644 	.intercept           = emulator_intercept,
8645 	.get_cpuid           = emulator_get_cpuid,
8646 	.guest_has_movbe     = emulator_guest_has_movbe,
8647 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8648 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8649 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8650 	.set_nmi_mask        = emulator_set_nmi_mask,
8651 	.is_smm              = emulator_is_smm,
8652 	.is_guest_mode       = emulator_is_guest_mode,
8653 	.leave_smm           = emulator_leave_smm,
8654 	.triple_fault        = emulator_triple_fault,
8655 	.set_xcr             = emulator_set_xcr,
8656 	.get_untagged_addr   = emulator_get_untagged_addr,
8657 	.is_canonical_addr   = emulator_is_canonical_addr,
8658 };
8659 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8660 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8661 {
8662 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8663 	/*
8664 	 * an sti; sti; sequence only disable interrupts for the first
8665 	 * instruction. So, if the last instruction, be it emulated or
8666 	 * not, left the system with the INT_STI flag enabled, it
8667 	 * means that the last instruction is an sti. We should not
8668 	 * leave the flag on in this case. The same goes for mov ss
8669 	 */
8670 	if (int_shadow & mask)
8671 		mask = 0;
8672 	if (unlikely(int_shadow || mask)) {
8673 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8674 		if (!mask)
8675 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8676 	}
8677 }
8678 
inject_emulated_exception(struct kvm_vcpu * vcpu)8679 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8680 {
8681 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8682 
8683 	if (ctxt->exception.vector == PF_VECTOR)
8684 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8685 	else if (ctxt->exception.error_code_valid)
8686 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8687 				      ctxt->exception.error_code);
8688 	else
8689 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8690 }
8691 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8692 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8693 {
8694 	struct x86_emulate_ctxt *ctxt;
8695 
8696 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8697 	if (!ctxt) {
8698 		pr_err("failed to allocate vcpu's emulator\n");
8699 		return NULL;
8700 	}
8701 
8702 	ctxt->vcpu = vcpu;
8703 	ctxt->ops = &emulate_ops;
8704 	vcpu->arch.emulate_ctxt = ctxt;
8705 
8706 	return ctxt;
8707 }
8708 
init_emulate_ctxt(struct kvm_vcpu * vcpu)8709 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8710 {
8711 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8712 	int cs_db, cs_l;
8713 
8714 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8715 
8716 	ctxt->gpa_available = false;
8717 	ctxt->eflags = kvm_get_rflags(vcpu);
8718 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8719 
8720 	ctxt->eip = kvm_rip_read(vcpu);
8721 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8722 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8723 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8724 		     cs_db				? X86EMUL_MODE_PROT32 :
8725 							  X86EMUL_MODE_PROT16;
8726 	ctxt->interruptibility = 0;
8727 	ctxt->have_exception = false;
8728 	ctxt->exception.vector = -1;
8729 	ctxt->perm_ok = false;
8730 
8731 	init_decode_cache(ctxt);
8732 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8733 }
8734 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8735 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8736 {
8737 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8738 	int ret;
8739 
8740 	init_emulate_ctxt(vcpu);
8741 
8742 	ctxt->op_bytes = 2;
8743 	ctxt->ad_bytes = 2;
8744 	ctxt->_eip = ctxt->eip + inc_eip;
8745 	ret = emulate_int_real(ctxt, irq);
8746 
8747 	if (ret != X86EMUL_CONTINUE) {
8748 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8749 	} else {
8750 		ctxt->eip = ctxt->_eip;
8751 		kvm_rip_write(vcpu, ctxt->eip);
8752 		kvm_set_rflags(vcpu, ctxt->eflags);
8753 	}
8754 }
8755 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8756 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)8757 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8758 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
8759 {
8760 	struct kvm_run *run = vcpu->run;
8761 	u64 info[5];
8762 	u8 info_start;
8763 
8764 	/*
8765 	 * Zero the whole array used to retrieve the exit info, as casting to
8766 	 * u32 for select entries will leave some chunks uninitialized.
8767 	 */
8768 	memset(&info, 0, sizeof(info));
8769 
8770 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
8771 				    (u32 *)&info[3], (u32 *)&info[4]);
8772 
8773 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8774 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8775 
8776 	/*
8777 	 * There's currently space for 13 entries, but 5 are used for the exit
8778 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
8779 	 * when expanding kvm_run.emulation_failure in the future.
8780 	 */
8781 	if (WARN_ON_ONCE(ndata > 4))
8782 		ndata = 4;
8783 
8784 	/* Always include the flags as a 'data' entry. */
8785 	info_start = 1;
8786 	run->emulation_failure.flags = 0;
8787 
8788 	if (insn_size) {
8789 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8790 			      sizeof(run->emulation_failure.insn_bytes) != 16));
8791 		info_start += 2;
8792 		run->emulation_failure.flags |=
8793 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8794 		run->emulation_failure.insn_size = insn_size;
8795 		memset(run->emulation_failure.insn_bytes, 0x90,
8796 		       sizeof(run->emulation_failure.insn_bytes));
8797 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8798 	}
8799 
8800 	memcpy(&run->internal.data[info_start], info, sizeof(info));
8801 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8802 	       ndata * sizeof(data[0]));
8803 
8804 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8805 }
8806 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)8807 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8808 {
8809 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8810 
8811 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8812 				       ctxt->fetch.end - ctxt->fetch.data);
8813 }
8814 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)8815 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8816 					  u8 ndata)
8817 {
8818 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8819 }
8820 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8821 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)8822 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8823 {
8824 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8825 }
8826 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8827 
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)8828 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
8829 {
8830 	u32 reason, intr_info, error_code;
8831 	struct kvm_run *run = vcpu->run;
8832 	u64 info1, info2;
8833 	int ndata = 0;
8834 
8835 	kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
8836 				    &intr_info, &error_code);
8837 
8838 	run->internal.data[ndata++] = info2;
8839 	run->internal.data[ndata++] = reason;
8840 	run->internal.data[ndata++] = info1;
8841 	run->internal.data[ndata++] = gpa;
8842 	run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
8843 
8844 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8845 	run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8846 	run->internal.ndata = ndata;
8847 }
8848 EXPORT_SYMBOL_GPL(kvm_prepare_event_vectoring_exit);
8849 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)8850 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8851 {
8852 	struct kvm *kvm = vcpu->kvm;
8853 
8854 	++vcpu->stat.insn_emulation_fail;
8855 	trace_kvm_emulate_insn_failed(vcpu);
8856 
8857 	if (emulation_type & EMULTYPE_VMWARE_GP) {
8858 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8859 		return 1;
8860 	}
8861 
8862 	if (kvm->arch.exit_on_emulation_error ||
8863 	    (emulation_type & EMULTYPE_SKIP)) {
8864 		prepare_emulation_ctxt_failure_exit(vcpu);
8865 		return 0;
8866 	}
8867 
8868 	kvm_queue_exception(vcpu, UD_VECTOR);
8869 
8870 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
8871 		prepare_emulation_ctxt_failure_exit(vcpu);
8872 		return 0;
8873 	}
8874 
8875 	return 1;
8876 }
8877 
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)8878 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
8879 					       gpa_t cr2_or_gpa,
8880 					       int emulation_type)
8881 {
8882 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8883 		return false;
8884 
8885 	/*
8886 	 * If the failed instruction faulted on an access to page tables that
8887 	 * are used to translate any part of the instruction, KVM can't resolve
8888 	 * the issue by unprotecting the gfn, as zapping the shadow page will
8889 	 * result in the instruction taking a !PRESENT page fault and thus put
8890 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
8891 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8892 	 * then zap the SPTE to unprotect the gfn, and then do it all over
8893 	 * again.  Report the error to userspace.
8894 	 */
8895 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
8896 		return false;
8897 
8898 	/*
8899 	 * If emulation may have been triggered by a write to a shadowed page
8900 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8901 	 * guest to let the CPU re-execute the instruction in the hope that the
8902 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
8903 	 */
8904 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
8905 
8906 	/*
8907 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
8908 	 * all SPTEs were already zapped by a different task.  The alternative
8909 	 * is to report the error to userspace and likely terminate the guest,
8910 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
8911 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
8912 	 */
8913 	return true;
8914 }
8915 
8916 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8917 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8918 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)8919 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8920 				unsigned long *db)
8921 {
8922 	u32 dr6 = 0;
8923 	int i;
8924 	u32 enable, rwlen;
8925 
8926 	enable = dr7;
8927 	rwlen = dr7 >> 16;
8928 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8929 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8930 			dr6 |= (1 << i);
8931 	return dr6;
8932 }
8933 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)8934 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8935 {
8936 	struct kvm_run *kvm_run = vcpu->run;
8937 
8938 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8939 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8940 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8941 		kvm_run->debug.arch.exception = DB_VECTOR;
8942 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
8943 		return 0;
8944 	}
8945 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8946 	return 1;
8947 }
8948 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)8949 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8950 {
8951 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
8952 	int r;
8953 
8954 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
8955 	if (unlikely(!r))
8956 		return 0;
8957 
8958 	kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
8959 
8960 	/*
8961 	 * rflags is the old, "raw" value of the flags.  The new value has
8962 	 * not been saved yet.
8963 	 *
8964 	 * This is correct even for TF set by the guest, because "the
8965 	 * processor will not generate this exception after the instruction
8966 	 * that sets the TF flag".
8967 	 */
8968 	if (unlikely(rflags & X86_EFLAGS_TF))
8969 		r = kvm_vcpu_do_singlestep(vcpu);
8970 	return r;
8971 }
8972 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8973 
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)8974 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
8975 {
8976 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8977 		return true;
8978 
8979 	/*
8980 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
8981 	 * active, but AMD compatible CPUs do not.
8982 	 */
8983 	if (!guest_cpuid_is_intel_compatible(vcpu))
8984 		return false;
8985 
8986 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
8987 }
8988 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)8989 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8990 					   int emulation_type, int *r)
8991 {
8992 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8993 
8994 	/*
8995 	 * Do not check for code breakpoints if hardware has already done the
8996 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
8997 	 * the instruction has passed all exception checks, and all intercepted
8998 	 * exceptions that trigger emulation have lower priority than code
8999 	 * breakpoints, i.e. the fact that the intercepted exception occurred
9000 	 * means any code breakpoints have already been serviced.
9001 	 *
9002 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9003 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
9004 	 * the instruction being emulated.  The intent of forced emulation is
9005 	 * to behave as if KVM intercepted the instruction without an exception
9006 	 * and without a prefix.
9007 	 */
9008 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9009 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9010 		return false;
9011 
9012 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9013 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9014 		struct kvm_run *kvm_run = vcpu->run;
9015 		unsigned long eip = kvm_get_linear_rip(vcpu);
9016 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9017 					   vcpu->arch.guest_debug_dr7,
9018 					   vcpu->arch.eff_db);
9019 
9020 		if (dr6 != 0) {
9021 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9022 			kvm_run->debug.arch.pc = eip;
9023 			kvm_run->debug.arch.exception = DB_VECTOR;
9024 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
9025 			*r = 0;
9026 			return true;
9027 		}
9028 	}
9029 
9030 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9031 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
9032 		unsigned long eip = kvm_get_linear_rip(vcpu);
9033 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9034 					   vcpu->arch.dr7,
9035 					   vcpu->arch.db);
9036 
9037 		if (dr6 != 0) {
9038 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9039 			*r = 1;
9040 			return true;
9041 		}
9042 	}
9043 
9044 	return false;
9045 }
9046 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9047 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9048 {
9049 	switch (ctxt->opcode_len) {
9050 	case 1:
9051 		switch (ctxt->b) {
9052 		case 0xe4:	/* IN */
9053 		case 0xe5:
9054 		case 0xec:
9055 		case 0xed:
9056 		case 0xe6:	/* OUT */
9057 		case 0xe7:
9058 		case 0xee:
9059 		case 0xef:
9060 		case 0x6c:	/* INS */
9061 		case 0x6d:
9062 		case 0x6e:	/* OUTS */
9063 		case 0x6f:
9064 			return true;
9065 		}
9066 		break;
9067 	case 2:
9068 		switch (ctxt->b) {
9069 		case 0x33:	/* RDPMC */
9070 			return true;
9071 		}
9072 		break;
9073 	}
9074 
9075 	return false;
9076 }
9077 
9078 /*
9079  * Decode an instruction for emulation.  The caller is responsible for handling
9080  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
9081  * (and wrong) when emulating on an intercepted fault-like exception[*], as
9082  * code breakpoints have higher priority and thus have already been done by
9083  * hardware.
9084  *
9085  * [*] Except #MC, which is higher priority, but KVM should never emulate in
9086  *     response to a machine check.
9087  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9088 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9089 				    void *insn, int insn_len)
9090 {
9091 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9092 	int r;
9093 
9094 	init_emulate_ctxt(vcpu);
9095 
9096 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9097 
9098 	trace_kvm_emulate_insn_start(vcpu);
9099 	++vcpu->stat.insn_emulation;
9100 
9101 	return r;
9102 }
9103 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9104 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9105 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9106 			    int emulation_type, void *insn, int insn_len)
9107 {
9108 	int r;
9109 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9110 	bool writeback = true;
9111 
9112 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9113 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9114 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9115 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9116 
9117 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9118 	if (r != X86EMUL_CONTINUE) {
9119 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9120 			return 1;
9121 
9122 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9123 						       emulation_type))
9124 			return 1;
9125 
9126 		if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9127 			kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9128 			return 0;
9129 		}
9130 
9131 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9132 		return handle_emulation_failure(vcpu, emulation_type);
9133 	}
9134 
9135 	vcpu->arch.l1tf_flush_l1d = true;
9136 
9137 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9138 		kvm_clear_exception_queue(vcpu);
9139 
9140 		/*
9141 		 * Return immediately if RIP hits a code breakpoint, such #DBs
9142 		 * are fault-like and are higher priority than any faults on
9143 		 * the code fetch itself.
9144 		 */
9145 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9146 			return r;
9147 
9148 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
9149 						    insn, insn_len);
9150 		if (r != EMULATION_OK)  {
9151 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
9152 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9153 				kvm_queue_exception(vcpu, UD_VECTOR);
9154 				return 1;
9155 			}
9156 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9157 							       emulation_type))
9158 				return 1;
9159 
9160 			if (ctxt->have_exception &&
9161 			    !(emulation_type & EMULTYPE_SKIP)) {
9162 				/*
9163 				 * #UD should result in just EMULATION_FAILED, and trap-like
9164 				 * exception should not be encountered during decode.
9165 				 */
9166 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9167 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9168 				inject_emulated_exception(vcpu);
9169 				return 1;
9170 			}
9171 			return handle_emulation_failure(vcpu, emulation_type);
9172 		}
9173 	}
9174 
9175 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9176 	    !is_vmware_backdoor_opcode(ctxt)) {
9177 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9178 		return 1;
9179 	}
9180 
9181 	/*
9182 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9183 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9184 	 * The caller is responsible for updating interruptibility state and
9185 	 * injecting single-step #DBs.
9186 	 */
9187 	if (emulation_type & EMULTYPE_SKIP) {
9188 		if (ctxt->mode != X86EMUL_MODE_PROT64)
9189 			ctxt->eip = (u32)ctxt->_eip;
9190 		else
9191 			ctxt->eip = ctxt->_eip;
9192 
9193 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9194 			r = 1;
9195 			goto writeback;
9196 		}
9197 
9198 		kvm_rip_write(vcpu, ctxt->eip);
9199 		if (ctxt->eflags & X86_EFLAGS_RF)
9200 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9201 		return 1;
9202 	}
9203 
9204 	/*
9205 	 * If emulation was caused by a write-protection #PF on a non-page_table
9206 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9207 	 * and retry the instruction, as the vCPU is likely no longer using the
9208 	 * gfn as a page table.
9209 	 */
9210 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9211 	    !x86_page_table_writing_insn(ctxt) &&
9212 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9213 		return 1;
9214 
9215 	/* this is needed for vmware backdoor interface to work since it
9216 	   changes registers values  during IO operation */
9217 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9218 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9219 		emulator_invalidate_register_cache(ctxt);
9220 	}
9221 
9222 restart:
9223 	if (emulation_type & EMULTYPE_PF) {
9224 		/* Save the faulting GPA (cr2) in the address field */
9225 		ctxt->exception.address = cr2_or_gpa;
9226 
9227 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
9228 		if (vcpu->arch.mmu->root_role.direct) {
9229 			ctxt->gpa_available = true;
9230 			ctxt->gpa_val = cr2_or_gpa;
9231 		}
9232 	} else {
9233 		/* Sanitize the address out of an abundance of paranoia. */
9234 		ctxt->exception.address = 0;
9235 	}
9236 
9237 	r = x86_emulate_insn(ctxt);
9238 
9239 	if (r == EMULATION_INTERCEPTED)
9240 		return 1;
9241 
9242 	if (r == EMULATION_FAILED) {
9243 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9244 						       emulation_type))
9245 			return 1;
9246 
9247 		return handle_emulation_failure(vcpu, emulation_type);
9248 	}
9249 
9250 	if (ctxt->have_exception) {
9251 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9252 		vcpu->mmio_needed = false;
9253 		r = 1;
9254 		inject_emulated_exception(vcpu);
9255 	} else if (vcpu->arch.pio.count) {
9256 		if (!vcpu->arch.pio.in) {
9257 			/* FIXME: return into emulator if single-stepping.  */
9258 			vcpu->arch.pio.count = 0;
9259 		} else {
9260 			writeback = false;
9261 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
9262 		}
9263 		r = 0;
9264 	} else if (vcpu->mmio_needed) {
9265 		++vcpu->stat.mmio_exits;
9266 
9267 		if (!vcpu->mmio_is_write)
9268 			writeback = false;
9269 		r = 0;
9270 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9271 	} else if (vcpu->arch.complete_userspace_io) {
9272 		writeback = false;
9273 		r = 0;
9274 	} else if (r == EMULATION_RESTART)
9275 		goto restart;
9276 	else
9277 		r = 1;
9278 
9279 writeback:
9280 	if (writeback) {
9281 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9282 		toggle_interruptibility(vcpu, ctxt->interruptibility);
9283 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9284 
9285 		/*
9286 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9287 		 * only supports code breakpoints and general detect #DB, both
9288 		 * of which are fault-like.
9289 		 */
9290 		if (!ctxt->have_exception ||
9291 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9292 			kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9293 			if (ctxt->is_branch)
9294 				kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
9295 			kvm_rip_write(vcpu, ctxt->eip);
9296 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9297 				r = kvm_vcpu_do_singlestep(vcpu);
9298 			kvm_x86_call(update_emulated_instruction)(vcpu);
9299 			__kvm_set_rflags(vcpu, ctxt->eflags);
9300 		}
9301 
9302 		/*
9303 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9304 		 * do nothing, and it will be requested again as soon as
9305 		 * the shadow expires.  But we still need to check here,
9306 		 * because POPF has no interrupt shadow.
9307 		 */
9308 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9309 			kvm_make_request(KVM_REQ_EVENT, vcpu);
9310 	} else
9311 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9312 
9313 	return r;
9314 }
9315 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9316 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9317 {
9318 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9319 }
9320 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9321 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9322 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9323 					void *insn, int insn_len)
9324 {
9325 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9326 }
9327 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9328 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9329 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9330 {
9331 	vcpu->arch.pio.count = 0;
9332 	return 1;
9333 }
9334 
complete_fast_pio_out(struct kvm_vcpu * vcpu)9335 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9336 {
9337 	vcpu->arch.pio.count = 0;
9338 
9339 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
9340 		return 1;
9341 
9342 	return kvm_skip_emulated_instruction(vcpu);
9343 }
9344 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9345 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9346 			    unsigned short port)
9347 {
9348 	unsigned long val = kvm_rax_read(vcpu);
9349 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9350 
9351 	if (ret)
9352 		return ret;
9353 
9354 	/*
9355 	 * Workaround userspace that relies on old KVM behavior of %rip being
9356 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9357 	 */
9358 	if (port == 0x7e &&
9359 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9360 		vcpu->arch.complete_userspace_io =
9361 			complete_fast_pio_out_port_0x7e;
9362 		kvm_skip_emulated_instruction(vcpu);
9363 	} else {
9364 		vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9365 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9366 	}
9367 	return 0;
9368 }
9369 
complete_fast_pio_in(struct kvm_vcpu * vcpu)9370 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9371 {
9372 	unsigned long val;
9373 
9374 	/* We should only ever be called with arch.pio.count equal to 1 */
9375 	BUG_ON(vcpu->arch.pio.count != 1);
9376 
9377 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
9378 		vcpu->arch.pio.count = 0;
9379 		return 1;
9380 	}
9381 
9382 	/* For size less than 4 we merge, else we zero extend */
9383 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9384 
9385 	complete_emulator_pio_in(vcpu, &val);
9386 	kvm_rax_write(vcpu, val);
9387 
9388 	return kvm_skip_emulated_instruction(vcpu);
9389 }
9390 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9391 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9392 			   unsigned short port)
9393 {
9394 	unsigned long val;
9395 	int ret;
9396 
9397 	/* For size less than 4 we merge, else we zero extend */
9398 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9399 
9400 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
9401 	if (ret) {
9402 		kvm_rax_write(vcpu, val);
9403 		return ret;
9404 	}
9405 
9406 	vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9407 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9408 
9409 	return 0;
9410 }
9411 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9412 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9413 {
9414 	int ret;
9415 
9416 	if (in)
9417 		ret = kvm_fast_pio_in(vcpu, size, port);
9418 	else
9419 		ret = kvm_fast_pio_out(vcpu, size, port);
9420 	return ret && kvm_skip_emulated_instruction(vcpu);
9421 }
9422 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9423 
kvmclock_cpu_down_prep(unsigned int cpu)9424 static int kvmclock_cpu_down_prep(unsigned int cpu)
9425 {
9426 	__this_cpu_write(cpu_tsc_khz, 0);
9427 	return 0;
9428 }
9429 
tsc_khz_changed(void * data)9430 static void tsc_khz_changed(void *data)
9431 {
9432 	struct cpufreq_freqs *freq = data;
9433 	unsigned long khz;
9434 
9435 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9436 
9437 	if (data)
9438 		khz = freq->new;
9439 	else
9440 		khz = cpufreq_quick_get(raw_smp_processor_id());
9441 	if (!khz)
9442 		khz = tsc_khz;
9443 	__this_cpu_write(cpu_tsc_khz, khz);
9444 }
9445 
9446 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9447 static void kvm_hyperv_tsc_notifier(void)
9448 {
9449 	struct kvm *kvm;
9450 	int cpu;
9451 
9452 	mutex_lock(&kvm_lock);
9453 	list_for_each_entry(kvm, &vm_list, vm_list)
9454 		kvm_make_mclock_inprogress_request(kvm);
9455 
9456 	/* no guest entries from this point */
9457 	hyperv_stop_tsc_emulation();
9458 
9459 	/* TSC frequency always matches when on Hyper-V */
9460 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9461 		for_each_present_cpu(cpu)
9462 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9463 	}
9464 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9465 
9466 	list_for_each_entry(kvm, &vm_list, vm_list) {
9467 		__kvm_start_pvclock_update(kvm);
9468 		pvclock_update_vm_gtod_copy(kvm);
9469 		kvm_end_pvclock_update(kvm);
9470 	}
9471 
9472 	mutex_unlock(&kvm_lock);
9473 }
9474 #endif
9475 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9476 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9477 {
9478 	struct kvm *kvm;
9479 	struct kvm_vcpu *vcpu;
9480 	int send_ipi = 0;
9481 	unsigned long i;
9482 
9483 	/*
9484 	 * We allow guests to temporarily run on slowing clocks,
9485 	 * provided we notify them after, or to run on accelerating
9486 	 * clocks, provided we notify them before.  Thus time never
9487 	 * goes backwards.
9488 	 *
9489 	 * However, we have a problem.  We can't atomically update
9490 	 * the frequency of a given CPU from this function; it is
9491 	 * merely a notifier, which can be called from any CPU.
9492 	 * Changing the TSC frequency at arbitrary points in time
9493 	 * requires a recomputation of local variables related to
9494 	 * the TSC for each VCPU.  We must flag these local variables
9495 	 * to be updated and be sure the update takes place with the
9496 	 * new frequency before any guests proceed.
9497 	 *
9498 	 * Unfortunately, the combination of hotplug CPU and frequency
9499 	 * change creates an intractable locking scenario; the order
9500 	 * of when these callouts happen is undefined with respect to
9501 	 * CPU hotplug, and they can race with each other.  As such,
9502 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9503 	 * undefined; you can actually have a CPU frequency change take
9504 	 * place in between the computation of X and the setting of the
9505 	 * variable.  To protect against this problem, all updates of
9506 	 * the per_cpu tsc_khz variable are done in an interrupt
9507 	 * protected IPI, and all callers wishing to update the value
9508 	 * must wait for a synchronous IPI to complete (which is trivial
9509 	 * if the caller is on the CPU already).  This establishes the
9510 	 * necessary total order on variable updates.
9511 	 *
9512 	 * Note that because a guest time update may take place
9513 	 * anytime after the setting of the VCPU's request bit, the
9514 	 * correct TSC value must be set before the request.  However,
9515 	 * to ensure the update actually makes it to any guest which
9516 	 * starts running in hardware virtualization between the set
9517 	 * and the acquisition of the spinlock, we must also ping the
9518 	 * CPU after setting the request bit.
9519 	 *
9520 	 */
9521 
9522 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9523 
9524 	mutex_lock(&kvm_lock);
9525 	list_for_each_entry(kvm, &vm_list, vm_list) {
9526 		kvm_for_each_vcpu(i, vcpu, kvm) {
9527 			if (vcpu->cpu != cpu)
9528 				continue;
9529 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9530 			if (vcpu->cpu != raw_smp_processor_id())
9531 				send_ipi = 1;
9532 		}
9533 	}
9534 	mutex_unlock(&kvm_lock);
9535 
9536 	if (freq->old < freq->new && send_ipi) {
9537 		/*
9538 		 * We upscale the frequency.  Must make the guest
9539 		 * doesn't see old kvmclock values while running with
9540 		 * the new frequency, otherwise we risk the guest sees
9541 		 * time go backwards.
9542 		 *
9543 		 * In case we update the frequency for another cpu
9544 		 * (which might be in guest context) send an interrupt
9545 		 * to kick the cpu out of guest context.  Next time
9546 		 * guest context is entered kvmclock will be updated,
9547 		 * so the guest will not see stale values.
9548 		 */
9549 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9550 	}
9551 }
9552 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9553 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9554 				     void *data)
9555 {
9556 	struct cpufreq_freqs *freq = data;
9557 	int cpu;
9558 
9559 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9560 		return 0;
9561 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9562 		return 0;
9563 
9564 	for_each_cpu(cpu, freq->policy->cpus)
9565 		__kvmclock_cpufreq_notifier(freq, cpu);
9566 
9567 	return 0;
9568 }
9569 
9570 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9571 	.notifier_call  = kvmclock_cpufreq_notifier
9572 };
9573 
kvmclock_cpu_online(unsigned int cpu)9574 static int kvmclock_cpu_online(unsigned int cpu)
9575 {
9576 	tsc_khz_changed(NULL);
9577 	return 0;
9578 }
9579 
kvm_timer_init(void)9580 static void kvm_timer_init(void)
9581 {
9582 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9583 		max_tsc_khz = tsc_khz;
9584 
9585 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9586 			struct cpufreq_policy *policy;
9587 			int cpu;
9588 
9589 			cpu = get_cpu();
9590 			policy = cpufreq_cpu_get(cpu);
9591 			if (policy) {
9592 				if (policy->cpuinfo.max_freq)
9593 					max_tsc_khz = policy->cpuinfo.max_freq;
9594 				cpufreq_cpu_put(policy);
9595 			}
9596 			put_cpu();
9597 		}
9598 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9599 					  CPUFREQ_TRANSITION_NOTIFIER);
9600 
9601 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9602 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9603 	}
9604 }
9605 
9606 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9607 static void pvclock_gtod_update_fn(struct work_struct *work)
9608 {
9609 	struct kvm *kvm;
9610 	struct kvm_vcpu *vcpu;
9611 	unsigned long i;
9612 
9613 	mutex_lock(&kvm_lock);
9614 	list_for_each_entry(kvm, &vm_list, vm_list)
9615 		kvm_for_each_vcpu(i, vcpu, kvm)
9616 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9617 	atomic_set(&kvm_guest_has_master_clock, 0);
9618 	mutex_unlock(&kvm_lock);
9619 }
9620 
9621 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9622 
9623 /*
9624  * Indirection to move queue_work() out of the tk_core.seq write held
9625  * region to prevent possible deadlocks against time accessors which
9626  * are invoked with work related locks held.
9627  */
pvclock_irq_work_fn(struct irq_work * w)9628 static void pvclock_irq_work_fn(struct irq_work *w)
9629 {
9630 	queue_work(system_long_wq, &pvclock_gtod_work);
9631 }
9632 
9633 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9634 
9635 /*
9636  * Notification about pvclock gtod data update.
9637  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9638 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9639 			       void *priv)
9640 {
9641 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9642 	struct timekeeper *tk = priv;
9643 
9644 	update_pvclock_gtod(tk);
9645 
9646 	/*
9647 	 * Disable master clock if host does not trust, or does not use,
9648 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9649 	 * this is invoked with tk_core.seq write held.
9650 	 */
9651 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9652 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9653 		irq_work_queue(&pvclock_irq_work);
9654 	return 0;
9655 }
9656 
9657 static struct notifier_block pvclock_gtod_notifier = {
9658 	.notifier_call = pvclock_gtod_notify,
9659 };
9660 #endif
9661 
kvm_ops_update(struct kvm_x86_init_ops * ops)9662 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9663 {
9664 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9665 
9666 #define __KVM_X86_OP(func) \
9667 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9668 #define KVM_X86_OP(func) \
9669 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9670 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9671 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9672 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9673 					   (void *)__static_call_return0);
9674 #include <asm/kvm-x86-ops.h>
9675 #undef __KVM_X86_OP
9676 
9677 	kvm_pmu_ops_update(ops->pmu_ops);
9678 }
9679 
kvm_x86_check_processor_compatibility(void)9680 static int kvm_x86_check_processor_compatibility(void)
9681 {
9682 	int cpu = smp_processor_id();
9683 	struct cpuinfo_x86 *c = &cpu_data(cpu);
9684 
9685 	/*
9686 	 * Compatibility checks are done when loading KVM and when enabling
9687 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9688 	 * compatible, i.e. KVM should never perform a compatibility check on
9689 	 * an offline CPU.
9690 	 */
9691 	WARN_ON(!cpu_online(cpu));
9692 
9693 	if (__cr4_reserved_bits(cpu_has, c) !=
9694 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9695 		return -EIO;
9696 
9697 	return kvm_x86_call(check_processor_compatibility)();
9698 }
9699 
kvm_x86_check_cpu_compat(void * ret)9700 static void kvm_x86_check_cpu_compat(void *ret)
9701 {
9702 	*(int *)ret = kvm_x86_check_processor_compatibility();
9703 }
9704 
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9705 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9706 {
9707 	u64 host_pat;
9708 	int r, cpu;
9709 
9710 	guard(mutex)(&vendor_module_lock);
9711 
9712 	if (kvm_x86_ops.enable_virtualization_cpu) {
9713 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9714 		return -EEXIST;
9715 	}
9716 
9717 	/*
9718 	 * KVM explicitly assumes that the guest has an FPU and
9719 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9720 	 * vCPU's FPU state as a fxregs_state struct.
9721 	 */
9722 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9723 		pr_err("inadequate fpu\n");
9724 		return -EOPNOTSUPP;
9725 	}
9726 
9727 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9728 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9729 		return -EOPNOTSUPP;
9730 	}
9731 
9732 	/*
9733 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9734 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
9735 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
9736 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
9737 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9738 	 */
9739 	if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9740 	    (host_pat & GENMASK(2, 0)) != 6) {
9741 		pr_err("host PAT[0] is not WB\n");
9742 		return -EIO;
9743 	}
9744 
9745 	memset(&kvm_caps, 0, sizeof(kvm_caps));
9746 
9747 	x86_emulator_cache = kvm_alloc_emulator_cache();
9748 	if (!x86_emulator_cache) {
9749 		pr_err("failed to allocate cache for x86 emulator\n");
9750 		return -ENOMEM;
9751 	}
9752 
9753 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9754 	if (!user_return_msrs) {
9755 		pr_err("failed to allocate percpu kvm_user_return_msrs\n");
9756 		r = -ENOMEM;
9757 		goto out_free_x86_emulator_cache;
9758 	}
9759 	kvm_nr_uret_msrs = 0;
9760 
9761 	r = kvm_mmu_vendor_module_init();
9762 	if (r)
9763 		goto out_free_percpu;
9764 
9765 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
9766 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
9767 
9768 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9769 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9770 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
9771 	}
9772 
9773 	rdmsrl_safe(MSR_EFER, &kvm_host.efer);
9774 
9775 	if (boot_cpu_has(X86_FEATURE_XSAVES))
9776 		rdmsrl(MSR_IA32_XSS, kvm_host.xss);
9777 
9778 	kvm_init_pmu_capability(ops->pmu_ops);
9779 
9780 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
9781 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
9782 
9783 	r = ops->hardware_setup();
9784 	if (r != 0)
9785 		goto out_mmu_exit;
9786 
9787 	kvm_ops_update(ops);
9788 
9789 	for_each_online_cpu(cpu) {
9790 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
9791 		if (r < 0)
9792 			goto out_unwind_ops;
9793 	}
9794 
9795 	/*
9796 	 * Point of no return!  DO NOT add error paths below this point unless
9797 	 * absolutely necessary, as most operations from this point forward
9798 	 * require unwinding.
9799 	 */
9800 	kvm_timer_init();
9801 
9802 	if (pi_inject_timer == -1)
9803 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9804 #ifdef CONFIG_X86_64
9805 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9806 
9807 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9808 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9809 #endif
9810 
9811 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9812 
9813 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9814 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9815 
9816 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9817 		kvm_caps.supported_xss = 0;
9818 
9819 	if (kvm_caps.has_tsc_control) {
9820 		/*
9821 		 * Make sure the user can only configure tsc_khz values that
9822 		 * fit into a signed integer.
9823 		 * A min value is not calculated because it will always
9824 		 * be 1 on all machines.
9825 		 */
9826 		u64 max = min(0x7fffffffULL,
9827 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9828 		kvm_caps.max_guest_tsc_khz = max;
9829 	}
9830 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9831 	kvm_init_msr_lists();
9832 	return 0;
9833 
9834 out_unwind_ops:
9835 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9836 	kvm_x86_call(hardware_unsetup)();
9837 out_mmu_exit:
9838 	kvm_mmu_vendor_module_exit();
9839 out_free_percpu:
9840 	free_percpu(user_return_msrs);
9841 out_free_x86_emulator_cache:
9842 	kmem_cache_destroy(x86_emulator_cache);
9843 	return r;
9844 }
9845 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9846 
kvm_x86_vendor_exit(void)9847 void kvm_x86_vendor_exit(void)
9848 {
9849 	kvm_unregister_perf_callbacks();
9850 
9851 #ifdef CONFIG_X86_64
9852 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9853 		clear_hv_tscchange_cb();
9854 #endif
9855 	kvm_lapic_exit();
9856 
9857 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9858 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9859 					    CPUFREQ_TRANSITION_NOTIFIER);
9860 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9861 	}
9862 #ifdef CONFIG_X86_64
9863 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9864 	irq_work_sync(&pvclock_irq_work);
9865 	cancel_work_sync(&pvclock_gtod_work);
9866 #endif
9867 	kvm_x86_call(hardware_unsetup)();
9868 	kvm_mmu_vendor_module_exit();
9869 	free_percpu(user_return_msrs);
9870 	kmem_cache_destroy(x86_emulator_cache);
9871 #ifdef CONFIG_KVM_XEN
9872 	static_key_deferred_flush(&kvm_xen_enabled);
9873 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9874 #endif
9875 	mutex_lock(&vendor_module_lock);
9876 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9877 	mutex_unlock(&vendor_module_lock);
9878 }
9879 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9880 
9881 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)9882 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9883 			        unsigned long clock_type)
9884 {
9885 	struct kvm_clock_pairing clock_pairing;
9886 	struct timespec64 ts;
9887 	u64 cycle;
9888 	int ret;
9889 
9890 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9891 		return -KVM_EOPNOTSUPP;
9892 
9893 	/*
9894 	 * When tsc is in permanent catchup mode guests won't be able to use
9895 	 * pvclock_read_retry loop to get consistent view of pvclock
9896 	 */
9897 	if (vcpu->arch.tsc_always_catchup)
9898 		return -KVM_EOPNOTSUPP;
9899 
9900 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9901 		return -KVM_EOPNOTSUPP;
9902 
9903 	clock_pairing.sec = ts.tv_sec;
9904 	clock_pairing.nsec = ts.tv_nsec;
9905 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9906 	clock_pairing.flags = 0;
9907 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9908 
9909 	ret = 0;
9910 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9911 			    sizeof(struct kvm_clock_pairing)))
9912 		ret = -KVM_EFAULT;
9913 
9914 	return ret;
9915 }
9916 #endif
9917 
9918 /*
9919  * kvm_pv_kick_cpu_op:  Kick a vcpu.
9920  *
9921  * @apicid - apicid of vcpu to be kicked.
9922  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)9923 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9924 {
9925 	/*
9926 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9927 	 * common code, e.g. for tracing. Defer initialization to the compiler.
9928 	 */
9929 	struct kvm_lapic_irq lapic_irq = {
9930 		.delivery_mode = APIC_DM_REMRD,
9931 		.dest_mode = APIC_DEST_PHYSICAL,
9932 		.shorthand = APIC_DEST_NOSHORT,
9933 		.dest_id = apicid,
9934 	};
9935 
9936 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9937 }
9938 
kvm_apicv_activated(struct kvm * kvm)9939 bool kvm_apicv_activated(struct kvm *kvm)
9940 {
9941 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9942 }
9943 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9944 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)9945 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9946 {
9947 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9948 	ulong vcpu_reasons =
9949 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
9950 
9951 	return (vm_reasons | vcpu_reasons) == 0;
9952 }
9953 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9954 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)9955 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9956 				       enum kvm_apicv_inhibit reason, bool set)
9957 {
9958 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
9959 
9960 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
9961 
9962 	if (set)
9963 		__set_bit(reason, inhibits);
9964 	else
9965 		__clear_bit(reason, inhibits);
9966 
9967 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9968 }
9969 
kvm_apicv_init(struct kvm * kvm)9970 static void kvm_apicv_init(struct kvm *kvm)
9971 {
9972 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
9973 						       APICV_INHIBIT_REASON_DISABLED;
9974 
9975 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
9976 
9977 	init_rwsem(&kvm->arch.apicv_update_lock);
9978 }
9979 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)9980 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9981 {
9982 	struct kvm_vcpu *target = NULL;
9983 	struct kvm_apic_map *map;
9984 
9985 	vcpu->stat.directed_yield_attempted++;
9986 
9987 	if (single_task_running())
9988 		goto no_yield;
9989 
9990 	rcu_read_lock();
9991 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
9992 
9993 	if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9994 		target = map->phys_map[dest_id]->vcpu;
9995 
9996 	rcu_read_unlock();
9997 
9998 	if (!target || !READ_ONCE(target->ready))
9999 		goto no_yield;
10000 
10001 	/* Ignore requests to yield to self */
10002 	if (vcpu == target)
10003 		goto no_yield;
10004 
10005 	if (kvm_vcpu_yield_to(target) <= 0)
10006 		goto no_yield;
10007 
10008 	vcpu->stat.directed_yield_successful++;
10009 
10010 no_yield:
10011 	return;
10012 }
10013 
complete_hypercall_exit(struct kvm_vcpu * vcpu)10014 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10015 {
10016 	u64 ret = vcpu->run->hypercall.ret;
10017 
10018 	if (!is_64_bit_hypercall(vcpu))
10019 		ret = (u32)ret;
10020 	kvm_rax_write(vcpu, ret);
10021 	return kvm_skip_emulated_instruction(vcpu);
10022 }
10023 
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,unsigned long nr,unsigned long a0,unsigned long a1,unsigned long a2,unsigned long a3,int op_64_bit,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10024 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, unsigned long nr,
10025 			      unsigned long a0, unsigned long a1,
10026 			      unsigned long a2, unsigned long a3,
10027 			      int op_64_bit, int cpl,
10028 			      int (*complete_hypercall)(struct kvm_vcpu *))
10029 {
10030 	unsigned long ret;
10031 
10032 	++vcpu->stat.hypercalls;
10033 
10034 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
10035 
10036 	if (!op_64_bit) {
10037 		nr &= 0xFFFFFFFF;
10038 		a0 &= 0xFFFFFFFF;
10039 		a1 &= 0xFFFFFFFF;
10040 		a2 &= 0xFFFFFFFF;
10041 		a3 &= 0xFFFFFFFF;
10042 	}
10043 
10044 	if (cpl) {
10045 		ret = -KVM_EPERM;
10046 		goto out;
10047 	}
10048 
10049 	ret = -KVM_ENOSYS;
10050 
10051 	switch (nr) {
10052 	case KVM_HC_VAPIC_POLL_IRQ:
10053 		ret = 0;
10054 		break;
10055 	case KVM_HC_KICK_CPU:
10056 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10057 			break;
10058 
10059 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10060 		kvm_sched_yield(vcpu, a1);
10061 		ret = 0;
10062 		break;
10063 #ifdef CONFIG_X86_64
10064 	case KVM_HC_CLOCK_PAIRING:
10065 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10066 		break;
10067 #endif
10068 	case KVM_HC_SEND_IPI:
10069 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10070 			break;
10071 
10072 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10073 		break;
10074 	case KVM_HC_SCHED_YIELD:
10075 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10076 			break;
10077 
10078 		kvm_sched_yield(vcpu, a0);
10079 		ret = 0;
10080 		break;
10081 	case KVM_HC_MAP_GPA_RANGE: {
10082 		u64 gpa = a0, npages = a1, attrs = a2;
10083 
10084 		ret = -KVM_ENOSYS;
10085 		if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10086 			break;
10087 
10088 		if (!PAGE_ALIGNED(gpa) || !npages ||
10089 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10090 			ret = -KVM_EINVAL;
10091 			break;
10092 		}
10093 
10094 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
10095 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
10096 		/*
10097 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10098 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10099 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
10100 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10101 		 */
10102 		vcpu->run->hypercall.ret = 0;
10103 		vcpu->run->hypercall.args[0]  = gpa;
10104 		vcpu->run->hypercall.args[1]  = npages;
10105 		vcpu->run->hypercall.args[2]  = attrs;
10106 		vcpu->run->hypercall.flags    = 0;
10107 		if (op_64_bit)
10108 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10109 
10110 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10111 		vcpu->arch.complete_userspace_io = complete_hypercall;
10112 		return 0;
10113 	}
10114 	default:
10115 		ret = -KVM_ENOSYS;
10116 		break;
10117 	}
10118 
10119 out:
10120 	vcpu->run->hypercall.ret = ret;
10121 	return 1;
10122 }
10123 EXPORT_SYMBOL_GPL(____kvm_emulate_hypercall);
10124 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10125 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10126 {
10127 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
10128 		return kvm_xen_hypercall(vcpu);
10129 
10130 	if (kvm_hv_hypercall_enabled(vcpu))
10131 		return kvm_hv_hypercall(vcpu);
10132 
10133 	return __kvm_emulate_hypercall(vcpu, rax, rbx, rcx, rdx, rsi,
10134 				       is_64_bit_hypercall(vcpu),
10135 				       kvm_x86_call(get_cpl)(vcpu),
10136 				       complete_hypercall_exit);
10137 }
10138 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10139 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10140 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10141 {
10142 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10143 	char instruction[3];
10144 	unsigned long rip = kvm_rip_read(vcpu);
10145 
10146 	/*
10147 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10148 	 * the pieces.
10149 	 */
10150 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10151 		ctxt->exception.error_code_valid = false;
10152 		ctxt->exception.vector = UD_VECTOR;
10153 		ctxt->have_exception = true;
10154 		return X86EMUL_PROPAGATE_FAULT;
10155 	}
10156 
10157 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
10158 
10159 	return emulator_write_emulated(ctxt, rip, instruction, 3,
10160 		&ctxt->exception);
10161 }
10162 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10163 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10164 {
10165 	return vcpu->run->request_interrupt_window &&
10166 		likely(!pic_in_kernel(vcpu->kvm));
10167 }
10168 
10169 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)10170 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10171 {
10172 	struct kvm_run *kvm_run = vcpu->run;
10173 
10174 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10175 	kvm_run->cr8 = kvm_get_cr8(vcpu);
10176 	kvm_run->apic_base = vcpu->arch.apic_base;
10177 
10178 	kvm_run->ready_for_interrupt_injection =
10179 		pic_in_kernel(vcpu->kvm) ||
10180 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
10181 
10182 	if (is_smm(vcpu))
10183 		kvm_run->flags |= KVM_RUN_X86_SMM;
10184 	if (is_guest_mode(vcpu))
10185 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10186 }
10187 
update_cr8_intercept(struct kvm_vcpu * vcpu)10188 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10189 {
10190 	int max_irr, tpr;
10191 
10192 	if (!kvm_x86_ops.update_cr8_intercept)
10193 		return;
10194 
10195 	if (!lapic_in_kernel(vcpu))
10196 		return;
10197 
10198 	if (vcpu->arch.apic->apicv_active)
10199 		return;
10200 
10201 	if (!vcpu->arch.apic->vapic_addr)
10202 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10203 	else
10204 		max_irr = -1;
10205 
10206 	if (max_irr != -1)
10207 		max_irr >>= 4;
10208 
10209 	tpr = kvm_lapic_get_cr8(vcpu);
10210 
10211 	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10212 }
10213 
10214 
kvm_check_nested_events(struct kvm_vcpu * vcpu)10215 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10216 {
10217 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10218 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
10219 		return 1;
10220 	}
10221 
10222 	return kvm_x86_ops.nested_ops->check_events(vcpu);
10223 }
10224 
kvm_inject_exception(struct kvm_vcpu * vcpu)10225 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10226 {
10227 	/*
10228 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10229 	 * exceptions don't report error codes.  The presence of an error code
10230 	 * is carried with the exception and only stripped when the exception
10231 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10232 	 * report an error code despite the CPU being in Real Mode.
10233 	 */
10234 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10235 
10236 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
10237 				vcpu->arch.exception.has_error_code,
10238 				vcpu->arch.exception.error_code,
10239 				vcpu->arch.exception.injected);
10240 
10241 	kvm_x86_call(inject_exception)(vcpu);
10242 }
10243 
10244 /*
10245  * Check for any event (interrupt or exception) that is ready to be injected,
10246  * and if there is at least one event, inject the event with the highest
10247  * priority.  This handles both "pending" events, i.e. events that have never
10248  * been injected into the guest, and "injected" events, i.e. events that were
10249  * injected as part of a previous VM-Enter, but weren't successfully delivered
10250  * and need to be re-injected.
10251  *
10252  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10253  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
10254  * be able to inject exceptions in the "middle" of an instruction, and so must
10255  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10256  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10257  * boundaries is necessary and correct.
10258  *
10259  * For simplicity, KVM uses a single path to inject all events (except events
10260  * that are injected directly from L1 to L2) and doesn't explicitly track
10261  * instruction boundaries for asynchronous events.  However, because VM-Exits
10262  * that can occur during instruction execution typically result in KVM skipping
10263  * the instruction or injecting an exception, e.g. instruction and exception
10264  * intercepts, and because pending exceptions have higher priority than pending
10265  * interrupts, KVM still honors instruction boundaries in most scenarios.
10266  *
10267  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10268  * the instruction or inject an exception, then KVM can incorrecty inject a new
10269  * asynchronous event if the event became pending after the CPU fetched the
10270  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
10271  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10272  * injected on the restarted instruction instead of being deferred until the
10273  * instruction completes.
10274  *
10275  * In practice, this virtualization hole is unlikely to be observed by the
10276  * guest, and even less likely to cause functional problems.  To detect the
10277  * hole, the guest would have to trigger an event on a side effect of an early
10278  * phase of instruction execution, e.g. on the instruction fetch from memory.
10279  * And for it to be a functional problem, the guest would need to depend on the
10280  * ordering between that side effect, the instruction completing, _and_ the
10281  * delivery of the asynchronous event.
10282  */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10283 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10284 				       bool *req_immediate_exit)
10285 {
10286 	bool can_inject;
10287 	int r;
10288 
10289 	/*
10290 	 * Process nested events first, as nested VM-Exit supersedes event
10291 	 * re-injection.  If there's an event queued for re-injection, it will
10292 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10293 	 */
10294 	if (is_guest_mode(vcpu))
10295 		r = kvm_check_nested_events(vcpu);
10296 	else
10297 		r = 0;
10298 
10299 	/*
10300 	 * Re-inject exceptions and events *especially* if immediate entry+exit
10301 	 * to/from L2 is needed, as any event that has already been injected
10302 	 * into L2 needs to complete its lifecycle before injecting a new event.
10303 	 *
10304 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
10305 	 * This collision arises if an exception occurred while vectoring the
10306 	 * injected event, KVM intercepted said exception, and KVM ultimately
10307 	 * determined the fault belongs to the guest and queues the exception
10308 	 * for injection back into the guest.
10309 	 *
10310 	 * "Injected" interrupts can also collide with pending exceptions if
10311 	 * userspace ignores the "ready for injection" flag and blindly queues
10312 	 * an interrupt.  In that case, prioritizing the exception is correct,
10313 	 * as the exception "occurred" before the exit to userspace.  Trap-like
10314 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10315 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10316 	 * priority, they're only generated (pended) during instruction
10317 	 * execution, and interrupts are recognized at instruction boundaries.
10318 	 * Thus a pending fault-like exception means the fault occurred on the
10319 	 * *previous* instruction and must be serviced prior to recognizing any
10320 	 * new events in order to fully complete the previous instruction.
10321 	 */
10322 	if (vcpu->arch.exception.injected)
10323 		kvm_inject_exception(vcpu);
10324 	else if (kvm_is_exception_pending(vcpu))
10325 		; /* see above */
10326 	else if (vcpu->arch.nmi_injected)
10327 		kvm_x86_call(inject_nmi)(vcpu);
10328 	else if (vcpu->arch.interrupt.injected)
10329 		kvm_x86_call(inject_irq)(vcpu, true);
10330 
10331 	/*
10332 	 * Exceptions that morph to VM-Exits are handled above, and pending
10333 	 * exceptions on top of injected exceptions that do not VM-Exit should
10334 	 * either morph to #DF or, sadly, override the injected exception.
10335 	 */
10336 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
10337 		     vcpu->arch.exception.pending);
10338 
10339 	/*
10340 	 * Bail if immediate entry+exit to/from the guest is needed to complete
10341 	 * nested VM-Enter or event re-injection so that a different pending
10342 	 * event can be serviced (or if KVM needs to exit to userspace).
10343 	 *
10344 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
10345 	 * VM-Exit will have cleared exceptions that were meant for L2, but
10346 	 * there may now be events that can be injected into L1.
10347 	 */
10348 	if (r < 0)
10349 		goto out;
10350 
10351 	/*
10352 	 * A pending exception VM-Exit should either result in nested VM-Exit
10353 	 * or force an immediate re-entry and exit to/from L2, and exception
10354 	 * VM-Exits cannot be injected (flag should _never_ be set).
10355 	 */
10356 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10357 		     vcpu->arch.exception_vmexit.pending);
10358 
10359 	/*
10360 	 * New events, other than exceptions, cannot be injected if KVM needs
10361 	 * to re-inject a previous event.  See above comments on re-injecting
10362 	 * for why pending exceptions get priority.
10363 	 */
10364 	can_inject = !kvm_event_needs_reinjection(vcpu);
10365 
10366 	if (vcpu->arch.exception.pending) {
10367 		/*
10368 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10369 		 * value pushed on the stack.  Trap-like exception and all #DBs
10370 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
10371 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10372 		 *
10373 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10374 		 * describe the behavior of General Detect #DBs, which are
10375 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
10376 		 */
10377 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10378 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10379 					     X86_EFLAGS_RF);
10380 
10381 		if (vcpu->arch.exception.vector == DB_VECTOR) {
10382 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10383 			if (vcpu->arch.dr7 & DR7_GD) {
10384 				vcpu->arch.dr7 &= ~DR7_GD;
10385 				kvm_update_dr7(vcpu);
10386 			}
10387 		}
10388 
10389 		kvm_inject_exception(vcpu);
10390 
10391 		vcpu->arch.exception.pending = false;
10392 		vcpu->arch.exception.injected = true;
10393 
10394 		can_inject = false;
10395 	}
10396 
10397 	/* Don't inject interrupts if the user asked to avoid doing so */
10398 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10399 		return 0;
10400 
10401 	/*
10402 	 * Finally, inject interrupt events.  If an event cannot be injected
10403 	 * due to architectural conditions (e.g. IF=0) a window-open exit
10404 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
10405 	 * and can architecturally be injected, but we cannot do it right now:
10406 	 * an interrupt could have arrived just now and we have to inject it
10407 	 * as a vmexit, or there could already an event in the queue, which is
10408 	 * indicated by can_inject.  In that case we request an immediate exit
10409 	 * in order to make progress and get back here for another iteration.
10410 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10411 	 */
10412 #ifdef CONFIG_KVM_SMM
10413 	if (vcpu->arch.smi_pending) {
10414 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10415 				 -EBUSY;
10416 		if (r < 0)
10417 			goto out;
10418 		if (r) {
10419 			vcpu->arch.smi_pending = false;
10420 			++vcpu->arch.smi_count;
10421 			enter_smm(vcpu);
10422 			can_inject = false;
10423 		} else
10424 			kvm_x86_call(enable_smi_window)(vcpu);
10425 	}
10426 #endif
10427 
10428 	if (vcpu->arch.nmi_pending) {
10429 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10430 				 -EBUSY;
10431 		if (r < 0)
10432 			goto out;
10433 		if (r) {
10434 			--vcpu->arch.nmi_pending;
10435 			vcpu->arch.nmi_injected = true;
10436 			kvm_x86_call(inject_nmi)(vcpu);
10437 			can_inject = false;
10438 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10439 		}
10440 		if (vcpu->arch.nmi_pending)
10441 			kvm_x86_call(enable_nmi_window)(vcpu);
10442 	}
10443 
10444 	if (kvm_cpu_has_injectable_intr(vcpu)) {
10445 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10446 				 -EBUSY;
10447 		if (r < 0)
10448 			goto out;
10449 		if (r) {
10450 			int irq = kvm_cpu_get_interrupt(vcpu);
10451 
10452 			if (!WARN_ON_ONCE(irq == -1)) {
10453 				kvm_queue_interrupt(vcpu, irq, false);
10454 				kvm_x86_call(inject_irq)(vcpu, false);
10455 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10456 			}
10457 		}
10458 		if (kvm_cpu_has_injectable_intr(vcpu))
10459 			kvm_x86_call(enable_irq_window)(vcpu);
10460 	}
10461 
10462 	if (is_guest_mode(vcpu) &&
10463 	    kvm_x86_ops.nested_ops->has_events &&
10464 	    kvm_x86_ops.nested_ops->has_events(vcpu, true))
10465 		*req_immediate_exit = true;
10466 
10467 	/*
10468 	 * KVM must never queue a new exception while injecting an event; KVM
10469 	 * is done emulating and should only propagate the to-be-injected event
10470 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
10471 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
10472 	 * exception and start the cycle all over.
10473 	 *
10474 	 * Exempt triple faults as they have special handling and won't put the
10475 	 * vCPU into an infinite loop.  Triple fault can be queued when running
10476 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
10477 	 * Mode events (see kvm_inject_realmode_interrupt()).
10478 	 */
10479 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
10480 		     vcpu->arch.exception_vmexit.pending);
10481 	return 0;
10482 
10483 out:
10484 	if (r == -EBUSY) {
10485 		*req_immediate_exit = true;
10486 		r = 0;
10487 	}
10488 	return r;
10489 }
10490 
process_nmi(struct kvm_vcpu * vcpu)10491 static void process_nmi(struct kvm_vcpu *vcpu)
10492 {
10493 	unsigned int limit;
10494 
10495 	/*
10496 	 * x86 is limited to one NMI pending, but because KVM can't react to
10497 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10498 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
10499 	 * up at the same time.  To handle this scenario, allow two NMIs to be
10500 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10501 	 * waiting for a previous NMI injection to complete (which effectively
10502 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
10503 	 * will request an NMI window to handle the second NMI.
10504 	 */
10505 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10506 		limit = 1;
10507 	else
10508 		limit = 2;
10509 
10510 	/*
10511 	 * Adjust the limit to account for pending virtual NMIs, which aren't
10512 	 * tracked in vcpu->arch.nmi_pending.
10513 	 */
10514 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
10515 		limit--;
10516 
10517 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10518 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10519 
10520 	if (vcpu->arch.nmi_pending &&
10521 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
10522 		vcpu->arch.nmi_pending--;
10523 
10524 	if (vcpu->arch.nmi_pending)
10525 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10526 }
10527 
10528 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10529 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10530 {
10531 	return vcpu->arch.nmi_pending +
10532 	       kvm_x86_call(is_vnmi_pending)(vcpu);
10533 }
10534 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10535 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10536 				       unsigned long *vcpu_bitmap)
10537 {
10538 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10539 }
10540 
kvm_make_scan_ioapic_request(struct kvm * kvm)10541 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10542 {
10543 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10544 }
10545 
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10546 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10547 {
10548 	struct kvm_lapic *apic = vcpu->arch.apic;
10549 	bool activate;
10550 
10551 	if (!lapic_in_kernel(vcpu))
10552 		return;
10553 
10554 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10555 	preempt_disable();
10556 
10557 	/* Do not activate APICV when APIC is disabled */
10558 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10559 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10560 
10561 	if (apic->apicv_active == activate)
10562 		goto out;
10563 
10564 	apic->apicv_active = activate;
10565 	kvm_apic_update_apicv(vcpu);
10566 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10567 
10568 	/*
10569 	 * When APICv gets disabled, we may still have injected interrupts
10570 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10571 	 * still active when the interrupt got accepted. Make sure
10572 	 * kvm_check_and_inject_events() is called to check for that.
10573 	 */
10574 	if (!apic->apicv_active)
10575 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10576 
10577 out:
10578 	preempt_enable();
10579 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10580 }
10581 EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10582 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10583 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10584 {
10585 	if (!lapic_in_kernel(vcpu))
10586 		return;
10587 
10588 	/*
10589 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10590 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10591 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
10592 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
10593 	 * this case so that KVM can use the AVIC doorbell to inject interrupts
10594 	 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10595 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10596 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
10597 	 * access page is sticky.
10598 	 */
10599 	if (apic_x2apic_mode(vcpu->arch.apic) &&
10600 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10601 		kvm_inhibit_apic_access_page(vcpu);
10602 
10603 	__kvm_vcpu_update_apicv(vcpu);
10604 }
10605 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10606 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10607 				      enum kvm_apicv_inhibit reason, bool set)
10608 {
10609 	unsigned long old, new;
10610 
10611 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10612 
10613 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10614 		return;
10615 
10616 	old = new = kvm->arch.apicv_inhibit_reasons;
10617 
10618 	set_or_clear_apicv_inhibit(&new, reason, set);
10619 
10620 	if (!!old != !!new) {
10621 		/*
10622 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10623 		 * false positives in the sanity check WARN in vcpu_enter_guest().
10624 		 * This task will wait for all vCPUs to ack the kick IRQ before
10625 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10626 		 * block on acquiring apicv_update_lock so that vCPUs can't
10627 		 * redo vcpu_enter_guest() without seeing the new inhibit state.
10628 		 *
10629 		 * Note, holding apicv_update_lock and taking it in the read
10630 		 * side (handling the request) also prevents other vCPUs from
10631 		 * servicing the request with a stale apicv_inhibit_reasons.
10632 		 */
10633 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10634 		kvm->arch.apicv_inhibit_reasons = new;
10635 		if (new) {
10636 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10637 			int idx = srcu_read_lock(&kvm->srcu);
10638 
10639 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10640 			srcu_read_unlock(&kvm->srcu, idx);
10641 		}
10642 	} else {
10643 		kvm->arch.apicv_inhibit_reasons = new;
10644 	}
10645 }
10646 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10647 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10648 				    enum kvm_apicv_inhibit reason, bool set)
10649 {
10650 	if (!enable_apicv)
10651 		return;
10652 
10653 	down_write(&kvm->arch.apicv_update_lock);
10654 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10655 	up_write(&kvm->arch.apicv_update_lock);
10656 }
10657 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10658 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10659 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10660 {
10661 	if (!kvm_apic_present(vcpu))
10662 		return;
10663 
10664 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10665 
10666 	kvm_x86_call(sync_pir_to_irr)(vcpu);
10667 
10668 	if (irqchip_split(vcpu->kvm))
10669 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10670 	else if (ioapic_in_kernel(vcpu->kvm))
10671 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10672 
10673 	if (is_guest_mode(vcpu))
10674 		vcpu->arch.load_eoi_exitmap_pending = true;
10675 	else
10676 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10677 }
10678 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10679 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10680 {
10681 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10682 		return;
10683 
10684 #ifdef CONFIG_KVM_HYPERV
10685 	if (to_hv_vcpu(vcpu)) {
10686 		u64 eoi_exit_bitmap[4];
10687 
10688 		bitmap_or((ulong *)eoi_exit_bitmap,
10689 			  vcpu->arch.ioapic_handled_vectors,
10690 			  to_hv_synic(vcpu)->vec_bitmap, 256);
10691 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10692 		return;
10693 	}
10694 #endif
10695 	kvm_x86_call(load_eoi_exitmap)(
10696 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10697 }
10698 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)10699 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10700 {
10701 	kvm_x86_call(guest_memory_reclaimed)(kvm);
10702 }
10703 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)10704 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10705 {
10706 	if (!lapic_in_kernel(vcpu))
10707 		return;
10708 
10709 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
10710 }
10711 
10712 /*
10713  * Called within kvm->srcu read side.
10714  * Returns 1 to let vcpu_run() continue the guest execution loop without
10715  * exiting to the userspace.  Otherwise, the value will be returned to the
10716  * userspace.
10717  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)10718 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10719 {
10720 	int r;
10721 	bool req_int_win =
10722 		dm_request_for_irq_injection(vcpu) &&
10723 		kvm_cpu_accept_dm_intr(vcpu);
10724 	fastpath_t exit_fastpath;
10725 
10726 	bool req_immediate_exit = false;
10727 
10728 	if (kvm_request_pending(vcpu)) {
10729 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10730 			r = -EIO;
10731 			goto out;
10732 		}
10733 
10734 		if (kvm_dirty_ring_check_request(vcpu)) {
10735 			r = 0;
10736 			goto out;
10737 		}
10738 
10739 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10740 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10741 				r = 0;
10742 				goto out;
10743 			}
10744 		}
10745 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10746 			kvm_mmu_free_obsolete_roots(vcpu);
10747 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10748 			__kvm_migrate_timers(vcpu);
10749 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10750 			kvm_update_masterclock(vcpu->kvm);
10751 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10752 			kvm_gen_kvmclock_update(vcpu);
10753 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10754 			r = kvm_guest_time_update(vcpu);
10755 			if (unlikely(r))
10756 				goto out;
10757 		}
10758 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10759 			kvm_mmu_sync_roots(vcpu);
10760 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10761 			kvm_mmu_load_pgd(vcpu);
10762 
10763 		/*
10764 		 * Note, the order matters here, as flushing "all" TLB entries
10765 		 * also flushes the "current" TLB entries, i.e. servicing the
10766 		 * flush "all" will clear any request to flush "current".
10767 		 */
10768 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
10769 			kvm_vcpu_flush_tlb_all(vcpu);
10770 
10771 		kvm_service_local_tlb_flush_requests(vcpu);
10772 
10773 		/*
10774 		 * Fall back to a "full" guest flush if Hyper-V's precise
10775 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
10776 		 * the flushes are considered "remote" and not "local" because
10777 		 * the requests can be initiated from other vCPUs.
10778 		 */
10779 #ifdef CONFIG_KVM_HYPERV
10780 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10781 		    kvm_hv_vcpu_flush_tlb(vcpu))
10782 			kvm_vcpu_flush_tlb_guest(vcpu);
10783 #endif
10784 
10785 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10786 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10787 			r = 0;
10788 			goto out;
10789 		}
10790 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10791 			if (is_guest_mode(vcpu))
10792 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
10793 
10794 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10795 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10796 				vcpu->mmio_needed = 0;
10797 				r = 0;
10798 				goto out;
10799 			}
10800 		}
10801 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10802 			/* Page is swapped out. Do synthetic halt */
10803 			vcpu->arch.apf.halted = true;
10804 			r = 1;
10805 			goto out;
10806 		}
10807 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10808 			record_steal_time(vcpu);
10809 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
10810 			kvm_pmu_handle_event(vcpu);
10811 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
10812 			kvm_pmu_deliver_pmi(vcpu);
10813 #ifdef CONFIG_KVM_SMM
10814 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
10815 			process_smi(vcpu);
10816 #endif
10817 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
10818 			process_nmi(vcpu);
10819 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10820 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10821 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
10822 				     vcpu->arch.ioapic_handled_vectors)) {
10823 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10824 				vcpu->run->eoi.vector =
10825 						vcpu->arch.pending_ioapic_eoi;
10826 				r = 0;
10827 				goto out;
10828 			}
10829 		}
10830 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10831 			vcpu_scan_ioapic(vcpu);
10832 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10833 			vcpu_load_eoi_exitmap(vcpu);
10834 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10835 			kvm_vcpu_reload_apic_access_page(vcpu);
10836 #ifdef CONFIG_KVM_HYPERV
10837 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10838 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10839 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10840 			vcpu->run->system_event.ndata = 0;
10841 			r = 0;
10842 			goto out;
10843 		}
10844 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10845 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10846 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10847 			vcpu->run->system_event.ndata = 0;
10848 			r = 0;
10849 			goto out;
10850 		}
10851 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10852 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10853 
10854 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10855 			vcpu->run->hyperv = hv_vcpu->exit;
10856 			r = 0;
10857 			goto out;
10858 		}
10859 
10860 		/*
10861 		 * KVM_REQ_HV_STIMER has to be processed after
10862 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10863 		 * depend on the guest clock being up-to-date
10864 		 */
10865 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10866 			kvm_hv_process_stimers(vcpu);
10867 #endif
10868 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10869 			kvm_vcpu_update_apicv(vcpu);
10870 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10871 			kvm_check_async_pf_completion(vcpu);
10872 		if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10873 			kvm_x86_call(msr_filter_changed)(vcpu);
10874 
10875 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10876 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
10877 
10878 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
10879 			kvm_vcpu_reset(vcpu, true);
10880 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
10881 				r = 1;
10882 				goto out;
10883 			}
10884 		}
10885 	}
10886 
10887 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10888 	    kvm_xen_has_interrupt(vcpu)) {
10889 		++vcpu->stat.req_event;
10890 		r = kvm_apic_accept_events(vcpu);
10891 		if (r < 0) {
10892 			r = 0;
10893 			goto out;
10894 		}
10895 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10896 			r = 1;
10897 			goto out;
10898 		}
10899 
10900 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10901 		if (r < 0) {
10902 			r = 0;
10903 			goto out;
10904 		}
10905 		if (req_int_win)
10906 			kvm_x86_call(enable_irq_window)(vcpu);
10907 
10908 		if (kvm_lapic_enabled(vcpu)) {
10909 			update_cr8_intercept(vcpu);
10910 			kvm_lapic_sync_to_vapic(vcpu);
10911 		}
10912 	}
10913 
10914 	r = kvm_mmu_reload(vcpu);
10915 	if (unlikely(r)) {
10916 		goto cancel_injection;
10917 	}
10918 
10919 	preempt_disable();
10920 
10921 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
10922 
10923 	/*
10924 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
10925 	 * IPI are then delayed after guest entry, which ensures that they
10926 	 * result in virtual interrupt delivery.
10927 	 */
10928 	local_irq_disable();
10929 
10930 	/* Store vcpu->apicv_active before vcpu->mode.  */
10931 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10932 
10933 	kvm_vcpu_srcu_read_unlock(vcpu);
10934 
10935 	/*
10936 	 * 1) We should set ->mode before checking ->requests.  Please see
10937 	 * the comment in kvm_vcpu_exiting_guest_mode().
10938 	 *
10939 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
10940 	 * pairs with the memory barrier implicit in pi_test_and_set_on
10941 	 * (see vmx_deliver_posted_interrupt).
10942 	 *
10943 	 * 3) This also orders the write to mode from any reads to the page
10944 	 * tables done while the VCPU is running.  Please see the comment
10945 	 * in kvm_flush_remote_tlbs.
10946 	 */
10947 	smp_mb__after_srcu_read_unlock();
10948 
10949 	/*
10950 	 * Process pending posted interrupts to handle the case where the
10951 	 * notification IRQ arrived in the host, or was never sent (because the
10952 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
10953 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
10954 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
10955 	 */
10956 	if (kvm_lapic_enabled(vcpu))
10957 		kvm_x86_call(sync_pir_to_irr)(vcpu);
10958 
10959 	if (kvm_vcpu_exit_request(vcpu)) {
10960 		vcpu->mode = OUTSIDE_GUEST_MODE;
10961 		smp_wmb();
10962 		local_irq_enable();
10963 		preempt_enable();
10964 		kvm_vcpu_srcu_read_lock(vcpu);
10965 		r = 1;
10966 		goto cancel_injection;
10967 	}
10968 
10969 	if (req_immediate_exit)
10970 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10971 
10972 	fpregs_assert_state_consistent();
10973 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
10974 		switch_fpu_return();
10975 
10976 	if (vcpu->arch.guest_fpu.xfd_err)
10977 		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10978 
10979 	if (unlikely(vcpu->arch.switch_db_regs)) {
10980 		set_debugreg(0, 7);
10981 		set_debugreg(vcpu->arch.eff_db[0], 0);
10982 		set_debugreg(vcpu->arch.eff_db[1], 1);
10983 		set_debugreg(vcpu->arch.eff_db[2], 2);
10984 		set_debugreg(vcpu->arch.eff_db[3], 3);
10985 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
10986 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
10987 			kvm_x86_call(set_dr6)(vcpu, vcpu->arch.dr6);
10988 	} else if (unlikely(hw_breakpoint_active())) {
10989 		set_debugreg(0, 7);
10990 	}
10991 
10992 	vcpu->arch.host_debugctl = get_debugctlmsr();
10993 
10994 	guest_timing_enter_irqoff();
10995 
10996 	for (;;) {
10997 		/*
10998 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
10999 		 * update must kick and wait for all vCPUs before toggling the
11000 		 * per-VM state, and responding vCPUs must wait for the update
11001 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
11002 		 */
11003 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11004 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11005 
11006 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu,
11007 						       req_immediate_exit);
11008 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11009 			break;
11010 
11011 		if (kvm_lapic_enabled(vcpu))
11012 			kvm_x86_call(sync_pir_to_irr)(vcpu);
11013 
11014 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11015 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11016 			break;
11017 		}
11018 
11019 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
11020 		++vcpu->stat.exits;
11021 	}
11022 
11023 	/*
11024 	 * Do this here before restoring debug registers on the host.  And
11025 	 * since we do this before handling the vmexit, a DR access vmexit
11026 	 * can (a) read the correct value of the debug registers, (b) set
11027 	 * KVM_DEBUGREG_WONT_EXIT again.
11028 	 */
11029 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11030 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11031 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11032 		kvm_update_dr0123(vcpu);
11033 		kvm_update_dr7(vcpu);
11034 	}
11035 
11036 	/*
11037 	 * If the guest has used debug registers, at least dr7
11038 	 * will be disabled while returning to the host.
11039 	 * If we don't have active breakpoints in the host, we don't
11040 	 * care about the messed up debug address registers. But if
11041 	 * we have some of them active, restore the old state.
11042 	 */
11043 	if (hw_breakpoint_active())
11044 		hw_breakpoint_restore();
11045 
11046 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11047 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11048 
11049 	vcpu->mode = OUTSIDE_GUEST_MODE;
11050 	smp_wmb();
11051 
11052 	/*
11053 	 * Sync xfd before calling handle_exit_irqoff() which may
11054 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11055 	 * in #NM irqoff handler).
11056 	 */
11057 	if (vcpu->arch.xfd_no_write_intercept)
11058 		fpu_sync_guest_vmexit_xfd_state();
11059 
11060 	kvm_x86_call(handle_exit_irqoff)(vcpu);
11061 
11062 	if (vcpu->arch.guest_fpu.xfd_err)
11063 		wrmsrl(MSR_IA32_XFD_ERR, 0);
11064 
11065 	/*
11066 	 * Consume any pending interrupts, including the possible source of
11067 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11068 	 * An instruction is required after local_irq_enable() to fully unblock
11069 	 * interrupts on processors that implement an interrupt shadow, the
11070 	 * stat.exits increment will do nicely.
11071 	 */
11072 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11073 	local_irq_enable();
11074 	++vcpu->stat.exits;
11075 	local_irq_disable();
11076 	kvm_after_interrupt(vcpu);
11077 
11078 	/*
11079 	 * Wait until after servicing IRQs to account guest time so that any
11080 	 * ticks that occurred while running the guest are properly accounted
11081 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
11082 	 * of accounting via context tracking, but the loss of accuracy is
11083 	 * acceptable for all known use cases.
11084 	 */
11085 	guest_timing_exit_irqoff();
11086 
11087 	local_irq_enable();
11088 	preempt_enable();
11089 
11090 	kvm_vcpu_srcu_read_lock(vcpu);
11091 
11092 	/*
11093 	 * Call this to ensure WC buffers in guest are evicted after each VM
11094 	 * Exit, so that the evicted WC writes can be snooped across all cpus
11095 	 */
11096 	smp_mb__after_srcu_read_lock();
11097 
11098 	/*
11099 	 * Profile KVM exit RIPs:
11100 	 */
11101 	if (unlikely(prof_on == KVM_PROFILING)) {
11102 		unsigned long rip = kvm_rip_read(vcpu);
11103 		profile_hit(KVM_PROFILING, (void *)rip);
11104 	}
11105 
11106 	if (unlikely(vcpu->arch.tsc_always_catchup))
11107 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11108 
11109 	if (vcpu->arch.apic_attention)
11110 		kvm_lapic_sync_from_vapic(vcpu);
11111 
11112 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11113 		return 0;
11114 
11115 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11116 	return r;
11117 
11118 cancel_injection:
11119 	if (req_immediate_exit)
11120 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11121 	kvm_x86_call(cancel_injection)(vcpu);
11122 	if (unlikely(vcpu->arch.apic_attention))
11123 		kvm_lapic_sync_from_vapic(vcpu);
11124 out:
11125 	return r;
11126 }
11127 
kvm_vcpu_running(struct kvm_vcpu * vcpu)11128 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11129 {
11130 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11131 		!vcpu->arch.apf.halted);
11132 }
11133 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11134 static bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11135 {
11136 	if (!list_empty_careful(&vcpu->async_pf.done))
11137 		return true;
11138 
11139 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11140 	    kvm_apic_init_sipi_allowed(vcpu))
11141 		return true;
11142 
11143 	if (vcpu->arch.pv.pv_unhalted)
11144 		return true;
11145 
11146 	if (kvm_is_exception_pending(vcpu))
11147 		return true;
11148 
11149 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11150 	    (vcpu->arch.nmi_pending &&
11151 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
11152 		return true;
11153 
11154 #ifdef CONFIG_KVM_SMM
11155 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11156 	    (vcpu->arch.smi_pending &&
11157 	     kvm_x86_call(smi_allowed)(vcpu, false)))
11158 		return true;
11159 #endif
11160 
11161 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
11162 		return true;
11163 
11164 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11165 		return true;
11166 
11167 	if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11168 		return true;
11169 
11170 	if (kvm_hv_has_stimer_pending(vcpu))
11171 		return true;
11172 
11173 	if (is_guest_mode(vcpu) &&
11174 	    kvm_x86_ops.nested_ops->has_events &&
11175 	    kvm_x86_ops.nested_ops->has_events(vcpu, false))
11176 		return true;
11177 
11178 	if (kvm_xen_has_pending_events(vcpu))
11179 		return true;
11180 
11181 	return false;
11182 }
11183 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11184 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11185 {
11186 	return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
11187 }
11188 
11189 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)11190 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11191 {
11192 	bool hv_timer;
11193 
11194 	if (!kvm_arch_vcpu_runnable(vcpu)) {
11195 		/*
11196 		 * Switch to the software timer before halt-polling/blocking as
11197 		 * the guest's timer may be a break event for the vCPU, and the
11198 		 * hypervisor timer runs only when the CPU is in guest mode.
11199 		 * Switch before halt-polling so that KVM recognizes an expired
11200 		 * timer before blocking.
11201 		 */
11202 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11203 		if (hv_timer)
11204 			kvm_lapic_switch_to_sw_timer(vcpu);
11205 
11206 		kvm_vcpu_srcu_read_unlock(vcpu);
11207 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11208 			kvm_vcpu_halt(vcpu);
11209 		else
11210 			kvm_vcpu_block(vcpu);
11211 		kvm_vcpu_srcu_read_lock(vcpu);
11212 
11213 		if (hv_timer)
11214 			kvm_lapic_switch_to_hv_timer(vcpu);
11215 
11216 		/*
11217 		 * If the vCPU is not runnable, a signal or another host event
11218 		 * of some kind is pending; service it without changing the
11219 		 * vCPU's activity state.
11220 		 */
11221 		if (!kvm_arch_vcpu_runnable(vcpu))
11222 			return 1;
11223 	}
11224 
11225 	/*
11226 	 * Evaluate nested events before exiting the halted state.  This allows
11227 	 * the halt state to be recorded properly in the VMCS12's activity
11228 	 * state field (AMD does not have a similar field and a VM-Exit always
11229 	 * causes a spurious wakeup from HLT).
11230 	 */
11231 	if (is_guest_mode(vcpu)) {
11232 		int r = kvm_check_nested_events(vcpu);
11233 
11234 		WARN_ON_ONCE(r == -EBUSY);
11235 		if (r < 0)
11236 			return 0;
11237 	}
11238 
11239 	if (kvm_apic_accept_events(vcpu) < 0)
11240 		return 0;
11241 	switch(vcpu->arch.mp_state) {
11242 	case KVM_MP_STATE_HALTED:
11243 	case KVM_MP_STATE_AP_RESET_HOLD:
11244 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11245 		fallthrough;
11246 	case KVM_MP_STATE_RUNNABLE:
11247 		vcpu->arch.apf.halted = false;
11248 		break;
11249 	case KVM_MP_STATE_INIT_RECEIVED:
11250 		break;
11251 	default:
11252 		WARN_ON_ONCE(1);
11253 		break;
11254 	}
11255 	return 1;
11256 }
11257 
11258 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)11259 static int vcpu_run(struct kvm_vcpu *vcpu)
11260 {
11261 	int r;
11262 
11263 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11264 
11265 	for (;;) {
11266 		/*
11267 		 * If another guest vCPU requests a PV TLB flush in the middle
11268 		 * of instruction emulation, the rest of the emulation could
11269 		 * use a stale page translation. Assume that any code after
11270 		 * this point can start executing an instruction.
11271 		 */
11272 		vcpu->arch.at_instruction_boundary = false;
11273 		if (kvm_vcpu_running(vcpu)) {
11274 			r = vcpu_enter_guest(vcpu);
11275 		} else {
11276 			r = vcpu_block(vcpu);
11277 		}
11278 
11279 		if (r <= 0)
11280 			break;
11281 
11282 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11283 		if (kvm_xen_has_pending_events(vcpu))
11284 			kvm_xen_inject_pending_events(vcpu);
11285 
11286 		if (kvm_cpu_has_pending_timer(vcpu))
11287 			kvm_inject_pending_timer_irqs(vcpu);
11288 
11289 		if (dm_request_for_irq_injection(vcpu) &&
11290 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11291 			r = 0;
11292 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11293 			++vcpu->stat.request_irq_exits;
11294 			break;
11295 		}
11296 
11297 		if (__xfer_to_guest_mode_work_pending()) {
11298 			kvm_vcpu_srcu_read_unlock(vcpu);
11299 			r = xfer_to_guest_mode_handle_work(vcpu);
11300 			kvm_vcpu_srcu_read_lock(vcpu);
11301 			if (r)
11302 				return r;
11303 		}
11304 	}
11305 
11306 	return r;
11307 }
11308 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11309 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11310 {
11311 	/*
11312 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
11313 	 * local APIC is in-kernel, the run loop will detect the non-runnable
11314 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
11315 	 * managed by userspace, in which case userspace is responsible for
11316 	 * handling wake events.
11317 	 */
11318 	++vcpu->stat.halt_exits;
11319 	if (lapic_in_kernel(vcpu)) {
11320 		if (kvm_vcpu_has_events(vcpu))
11321 			state = KVM_MP_STATE_RUNNABLE;
11322 		kvm_set_mp_state(vcpu, state);
11323 		return 1;
11324 	} else {
11325 		vcpu->run->exit_reason = reason;
11326 		return 0;
11327 	}
11328 }
11329 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11330 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11331 {
11332 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11333 }
11334 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
11335 
kvm_emulate_halt(struct kvm_vcpu * vcpu)11336 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11337 {
11338 	int ret = kvm_skip_emulated_instruction(vcpu);
11339 	/*
11340 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11341 	 * KVM_EXIT_DEBUG here.
11342 	 */
11343 	return kvm_emulate_halt_noskip(vcpu) && ret;
11344 }
11345 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
11346 
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11347 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11348 {
11349 	int ret;
11350 
11351 	kvm_vcpu_srcu_read_lock(vcpu);
11352 	ret = kvm_emulate_halt(vcpu);
11353 	kvm_vcpu_srcu_read_unlock(vcpu);
11354 
11355 	if (!ret)
11356 		return EXIT_FASTPATH_EXIT_USERSPACE;
11357 
11358 	if (kvm_vcpu_running(vcpu))
11359 		return EXIT_FASTPATH_REENTER_GUEST;
11360 
11361 	return EXIT_FASTPATH_EXIT_HANDLED;
11362 }
11363 EXPORT_SYMBOL_GPL(handle_fastpath_hlt);
11364 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11365 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11366 {
11367 	int ret = kvm_skip_emulated_instruction(vcpu);
11368 
11369 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11370 					KVM_EXIT_AP_RESET_HOLD) && ret;
11371 }
11372 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
11373 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11374 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11375 {
11376 	return kvm_vcpu_apicv_active(vcpu) &&
11377 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11378 }
11379 
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11380 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11381 {
11382 	return vcpu->arch.preempted_in_kernel;
11383 }
11384 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11385 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11386 {
11387 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11388 		return true;
11389 
11390 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11391 #ifdef CONFIG_KVM_SMM
11392 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
11393 #endif
11394 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
11395 		return true;
11396 
11397 	return kvm_arch_dy_has_pending_interrupt(vcpu);
11398 }
11399 
complete_emulated_io(struct kvm_vcpu * vcpu)11400 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11401 {
11402 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11403 }
11404 
complete_emulated_pio(struct kvm_vcpu * vcpu)11405 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11406 {
11407 	BUG_ON(!vcpu->arch.pio.count);
11408 
11409 	return complete_emulated_io(vcpu);
11410 }
11411 
11412 /*
11413  * Implements the following, as a state machine:
11414  *
11415  * read:
11416  *   for each fragment
11417  *     for each mmio piece in the fragment
11418  *       write gpa, len
11419  *       exit
11420  *       copy data
11421  *   execute insn
11422  *
11423  * write:
11424  *   for each fragment
11425  *     for each mmio piece in the fragment
11426  *       write gpa, len
11427  *       copy data
11428  *       exit
11429  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11430 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11431 {
11432 	struct kvm_run *run = vcpu->run;
11433 	struct kvm_mmio_fragment *frag;
11434 	unsigned len;
11435 
11436 	BUG_ON(!vcpu->mmio_needed);
11437 
11438 	/* Complete previous fragment */
11439 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11440 	len = min(8u, frag->len);
11441 	if (!vcpu->mmio_is_write)
11442 		memcpy(frag->data, run->mmio.data, len);
11443 
11444 	if (frag->len <= 8) {
11445 		/* Switch to the next fragment. */
11446 		frag++;
11447 		vcpu->mmio_cur_fragment++;
11448 	} else {
11449 		/* Go forward to the next mmio piece. */
11450 		frag->data += len;
11451 		frag->gpa += len;
11452 		frag->len -= len;
11453 	}
11454 
11455 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11456 		vcpu->mmio_needed = 0;
11457 
11458 		/* FIXME: return into emulator if single-stepping.  */
11459 		if (vcpu->mmio_is_write)
11460 			return 1;
11461 		vcpu->mmio_read_completed = 1;
11462 		return complete_emulated_io(vcpu);
11463 	}
11464 
11465 	run->exit_reason = KVM_EXIT_MMIO;
11466 	run->mmio.phys_addr = frag->gpa;
11467 	if (vcpu->mmio_is_write)
11468 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11469 	run->mmio.len = min(8u, frag->len);
11470 	run->mmio.is_write = vcpu->mmio_is_write;
11471 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11472 	return 0;
11473 }
11474 
11475 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11476 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11477 {
11478 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11479 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11480 	trace_kvm_fpu(1);
11481 }
11482 
11483 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11484 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11485 {
11486 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11487 	++vcpu->stat.fpu_reload;
11488 	trace_kvm_fpu(0);
11489 }
11490 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11491 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11492 {
11493 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
11494 	struct kvm_run *kvm_run = vcpu->run;
11495 	u32 sync_valid_fields;
11496 	int r;
11497 
11498 	r = kvm_mmu_post_init_vm(vcpu->kvm);
11499 	if (r)
11500 		return r;
11501 
11502 	vcpu_load(vcpu);
11503 	kvm_sigset_activate(vcpu);
11504 	kvm_run->flags = 0;
11505 	kvm_load_guest_fpu(vcpu);
11506 
11507 	kvm_vcpu_srcu_read_lock(vcpu);
11508 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11509 		if (!vcpu->wants_to_run) {
11510 			r = -EINTR;
11511 			goto out;
11512 		}
11513 
11514 		/*
11515 		 * Don't bother switching APIC timer emulation from the
11516 		 * hypervisor timer to the software timer, the only way for the
11517 		 * APIC timer to be active is if userspace stuffed vCPU state,
11518 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
11519 		 * will transition the vCPU out of UNINITIALIZED (without more
11520 		 * state stuffing from userspace), which will reset the local
11521 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
11522 		 * already expired).
11523 		 */
11524 		kvm_vcpu_srcu_read_unlock(vcpu);
11525 		kvm_vcpu_block(vcpu);
11526 		kvm_vcpu_srcu_read_lock(vcpu);
11527 
11528 		if (kvm_apic_accept_events(vcpu) < 0) {
11529 			r = 0;
11530 			goto out;
11531 		}
11532 		r = -EAGAIN;
11533 		if (signal_pending(current)) {
11534 			r = -EINTR;
11535 			kvm_run->exit_reason = KVM_EXIT_INTR;
11536 			++vcpu->stat.signal_exits;
11537 		}
11538 		goto out;
11539 	}
11540 
11541 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11542 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11543 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11544 		r = -EINVAL;
11545 		goto out;
11546 	}
11547 
11548 	if (kvm_run->kvm_dirty_regs) {
11549 		r = sync_regs(vcpu);
11550 		if (r != 0)
11551 			goto out;
11552 	}
11553 
11554 	/* re-sync apic's tpr */
11555 	if (!lapic_in_kernel(vcpu)) {
11556 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11557 			r = -EINVAL;
11558 			goto out;
11559 		}
11560 	}
11561 
11562 	/*
11563 	 * If userspace set a pending exception and L2 is active, convert it to
11564 	 * a pending VM-Exit if L1 wants to intercept the exception.
11565 	 */
11566 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11567 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11568 							ex->error_code)) {
11569 		kvm_queue_exception_vmexit(vcpu, ex->vector,
11570 					   ex->has_error_code, ex->error_code,
11571 					   ex->has_payload, ex->payload);
11572 		ex->injected = false;
11573 		ex->pending = false;
11574 	}
11575 	vcpu->arch.exception_from_userspace = false;
11576 
11577 	if (unlikely(vcpu->arch.complete_userspace_io)) {
11578 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11579 		vcpu->arch.complete_userspace_io = NULL;
11580 		r = cui(vcpu);
11581 		if (r <= 0)
11582 			goto out;
11583 	} else {
11584 		WARN_ON_ONCE(vcpu->arch.pio.count);
11585 		WARN_ON_ONCE(vcpu->mmio_needed);
11586 	}
11587 
11588 	if (!vcpu->wants_to_run) {
11589 		r = -EINTR;
11590 		goto out;
11591 	}
11592 
11593 	r = kvm_x86_call(vcpu_pre_run)(vcpu);
11594 	if (r <= 0)
11595 		goto out;
11596 
11597 	r = vcpu_run(vcpu);
11598 
11599 out:
11600 	kvm_put_guest_fpu(vcpu);
11601 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11602 		store_regs(vcpu);
11603 	post_kvm_run_save(vcpu);
11604 	kvm_vcpu_srcu_read_unlock(vcpu);
11605 
11606 	kvm_sigset_deactivate(vcpu);
11607 	vcpu_put(vcpu);
11608 	return r;
11609 }
11610 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11611 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11612 {
11613 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11614 		/*
11615 		 * We are here if userspace calls get_regs() in the middle of
11616 		 * instruction emulation. Registers state needs to be copied
11617 		 * back from emulation context to vcpu. Userspace shouldn't do
11618 		 * that usually, but some bad designed PV devices (vmware
11619 		 * backdoor interface) need this to work
11620 		 */
11621 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11622 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11623 	}
11624 	regs->rax = kvm_rax_read(vcpu);
11625 	regs->rbx = kvm_rbx_read(vcpu);
11626 	regs->rcx = kvm_rcx_read(vcpu);
11627 	regs->rdx = kvm_rdx_read(vcpu);
11628 	regs->rsi = kvm_rsi_read(vcpu);
11629 	regs->rdi = kvm_rdi_read(vcpu);
11630 	regs->rsp = kvm_rsp_read(vcpu);
11631 	regs->rbp = kvm_rbp_read(vcpu);
11632 #ifdef CONFIG_X86_64
11633 	regs->r8 = kvm_r8_read(vcpu);
11634 	regs->r9 = kvm_r9_read(vcpu);
11635 	regs->r10 = kvm_r10_read(vcpu);
11636 	regs->r11 = kvm_r11_read(vcpu);
11637 	regs->r12 = kvm_r12_read(vcpu);
11638 	regs->r13 = kvm_r13_read(vcpu);
11639 	regs->r14 = kvm_r14_read(vcpu);
11640 	regs->r15 = kvm_r15_read(vcpu);
11641 #endif
11642 
11643 	regs->rip = kvm_rip_read(vcpu);
11644 	regs->rflags = kvm_get_rflags(vcpu);
11645 }
11646 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11647 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11648 {
11649 	if (vcpu->kvm->arch.has_protected_state &&
11650 	    vcpu->arch.guest_state_protected)
11651 		return -EINVAL;
11652 
11653 	vcpu_load(vcpu);
11654 	__get_regs(vcpu, regs);
11655 	vcpu_put(vcpu);
11656 	return 0;
11657 }
11658 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11659 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11660 {
11661 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11662 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11663 
11664 	kvm_rax_write(vcpu, regs->rax);
11665 	kvm_rbx_write(vcpu, regs->rbx);
11666 	kvm_rcx_write(vcpu, regs->rcx);
11667 	kvm_rdx_write(vcpu, regs->rdx);
11668 	kvm_rsi_write(vcpu, regs->rsi);
11669 	kvm_rdi_write(vcpu, regs->rdi);
11670 	kvm_rsp_write(vcpu, regs->rsp);
11671 	kvm_rbp_write(vcpu, regs->rbp);
11672 #ifdef CONFIG_X86_64
11673 	kvm_r8_write(vcpu, regs->r8);
11674 	kvm_r9_write(vcpu, regs->r9);
11675 	kvm_r10_write(vcpu, regs->r10);
11676 	kvm_r11_write(vcpu, regs->r11);
11677 	kvm_r12_write(vcpu, regs->r12);
11678 	kvm_r13_write(vcpu, regs->r13);
11679 	kvm_r14_write(vcpu, regs->r14);
11680 	kvm_r15_write(vcpu, regs->r15);
11681 #endif
11682 
11683 	kvm_rip_write(vcpu, regs->rip);
11684 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11685 
11686 	vcpu->arch.exception.pending = false;
11687 	vcpu->arch.exception_vmexit.pending = false;
11688 
11689 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11690 }
11691 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11692 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11693 {
11694 	if (vcpu->kvm->arch.has_protected_state &&
11695 	    vcpu->arch.guest_state_protected)
11696 		return -EINVAL;
11697 
11698 	vcpu_load(vcpu);
11699 	__set_regs(vcpu, regs);
11700 	vcpu_put(vcpu);
11701 	return 0;
11702 }
11703 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11704 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11705 {
11706 	struct desc_ptr dt;
11707 
11708 	if (vcpu->arch.guest_state_protected)
11709 		goto skip_protected_regs;
11710 
11711 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11712 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11713 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11714 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11715 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11716 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11717 
11718 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11719 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11720 
11721 	kvm_x86_call(get_idt)(vcpu, &dt);
11722 	sregs->idt.limit = dt.size;
11723 	sregs->idt.base = dt.address;
11724 	kvm_x86_call(get_gdt)(vcpu, &dt);
11725 	sregs->gdt.limit = dt.size;
11726 	sregs->gdt.base = dt.address;
11727 
11728 	sregs->cr2 = vcpu->arch.cr2;
11729 	sregs->cr3 = kvm_read_cr3(vcpu);
11730 
11731 skip_protected_regs:
11732 	sregs->cr0 = kvm_read_cr0(vcpu);
11733 	sregs->cr4 = kvm_read_cr4(vcpu);
11734 	sregs->cr8 = kvm_get_cr8(vcpu);
11735 	sregs->efer = vcpu->arch.efer;
11736 	sregs->apic_base = vcpu->arch.apic_base;
11737 }
11738 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11739 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11740 {
11741 	__get_sregs_common(vcpu, sregs);
11742 
11743 	if (vcpu->arch.guest_state_protected)
11744 		return;
11745 
11746 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11747 		set_bit(vcpu->arch.interrupt.nr,
11748 			(unsigned long *)sregs->interrupt_bitmap);
11749 }
11750 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)11751 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11752 {
11753 	int i;
11754 
11755 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11756 
11757 	if (vcpu->arch.guest_state_protected)
11758 		return;
11759 
11760 	if (is_pae_paging(vcpu)) {
11761 		for (i = 0 ; i < 4 ; i++)
11762 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11763 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11764 	}
11765 }
11766 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11767 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11768 				  struct kvm_sregs *sregs)
11769 {
11770 	if (vcpu->kvm->arch.has_protected_state &&
11771 	    vcpu->arch.guest_state_protected)
11772 		return -EINVAL;
11773 
11774 	vcpu_load(vcpu);
11775 	__get_sregs(vcpu, sregs);
11776 	vcpu_put(vcpu);
11777 	return 0;
11778 }
11779 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11780 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11781 				    struct kvm_mp_state *mp_state)
11782 {
11783 	int r;
11784 
11785 	vcpu_load(vcpu);
11786 	if (kvm_mpx_supported())
11787 		kvm_load_guest_fpu(vcpu);
11788 
11789 	r = kvm_apic_accept_events(vcpu);
11790 	if (r < 0)
11791 		goto out;
11792 	r = 0;
11793 
11794 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11795 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11796 	    vcpu->arch.pv.pv_unhalted)
11797 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11798 	else
11799 		mp_state->mp_state = vcpu->arch.mp_state;
11800 
11801 out:
11802 	if (kvm_mpx_supported())
11803 		kvm_put_guest_fpu(vcpu);
11804 	vcpu_put(vcpu);
11805 	return r;
11806 }
11807 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11808 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11809 				    struct kvm_mp_state *mp_state)
11810 {
11811 	int ret = -EINVAL;
11812 
11813 	vcpu_load(vcpu);
11814 
11815 	switch (mp_state->mp_state) {
11816 	case KVM_MP_STATE_UNINITIALIZED:
11817 	case KVM_MP_STATE_HALTED:
11818 	case KVM_MP_STATE_AP_RESET_HOLD:
11819 	case KVM_MP_STATE_INIT_RECEIVED:
11820 	case KVM_MP_STATE_SIPI_RECEIVED:
11821 		if (!lapic_in_kernel(vcpu))
11822 			goto out;
11823 		break;
11824 
11825 	case KVM_MP_STATE_RUNNABLE:
11826 		break;
11827 
11828 	default:
11829 		goto out;
11830 	}
11831 
11832 	/*
11833 	 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11834 	 * forcing the guest into INIT/SIPI if those events are supposed to be
11835 	 * blocked.  KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11836 	 * if an SMI is pending as well.
11837 	 */
11838 	if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11839 	    (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11840 	     mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11841 		goto out;
11842 
11843 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11844 		kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
11845 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11846 	} else
11847 		kvm_set_mp_state(vcpu, mp_state->mp_state);
11848 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11849 
11850 	ret = 0;
11851 out:
11852 	vcpu_put(vcpu);
11853 	return ret;
11854 }
11855 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)11856 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11857 		    int reason, bool has_error_code, u32 error_code)
11858 {
11859 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11860 	int ret;
11861 
11862 	init_emulate_ctxt(vcpu);
11863 
11864 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11865 				   has_error_code, error_code);
11866 
11867 	/*
11868 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
11869 	 * MMIO during a task switch (or any other complex operation).
11870 	 */
11871 	if (ret || vcpu->mmio_needed) {
11872 		vcpu->mmio_needed = false;
11873 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11874 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11875 		vcpu->run->internal.ndata = 0;
11876 		return 0;
11877 	}
11878 
11879 	kvm_rip_write(vcpu, ctxt->eip);
11880 	kvm_set_rflags(vcpu, ctxt->eflags);
11881 	return 1;
11882 }
11883 EXPORT_SYMBOL_GPL(kvm_task_switch);
11884 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11885 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11886 {
11887 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11888 		/*
11889 		 * When EFER.LME and CR0.PG are set, the processor is in
11890 		 * 64-bit mode (though maybe in a 32-bit code segment).
11891 		 * CR4.PAE and EFER.LMA must be set.
11892 		 */
11893 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11894 			return false;
11895 		if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
11896 			return false;
11897 	} else {
11898 		/*
11899 		 * Not in 64-bit mode: EFER.LMA is clear and the code
11900 		 * segment cannot be 64-bit.
11901 		 */
11902 		if (sregs->efer & EFER_LMA || sregs->cs.l)
11903 			return false;
11904 	}
11905 
11906 	return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11907 	       kvm_is_valid_cr0(vcpu, sregs->cr0);
11908 }
11909 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)11910 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11911 		int *mmu_reset_needed, bool update_pdptrs)
11912 {
11913 	int idx;
11914 	struct desc_ptr dt;
11915 
11916 	if (!kvm_is_valid_sregs(vcpu, sregs))
11917 		return -EINVAL;
11918 
11919 	if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
11920 		return -EINVAL;
11921 
11922 	if (vcpu->arch.guest_state_protected)
11923 		return 0;
11924 
11925 	dt.size = sregs->idt.limit;
11926 	dt.address = sregs->idt.base;
11927 	kvm_x86_call(set_idt)(vcpu, &dt);
11928 	dt.size = sregs->gdt.limit;
11929 	dt.address = sregs->gdt.base;
11930 	kvm_x86_call(set_gdt)(vcpu, &dt);
11931 
11932 	vcpu->arch.cr2 = sregs->cr2;
11933 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11934 	vcpu->arch.cr3 = sregs->cr3;
11935 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11936 	kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
11937 
11938 	kvm_set_cr8(vcpu, sregs->cr8);
11939 
11940 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11941 	kvm_x86_call(set_efer)(vcpu, sregs->efer);
11942 
11943 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11944 	kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
11945 
11946 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11947 	kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
11948 
11949 	if (update_pdptrs) {
11950 		idx = srcu_read_lock(&vcpu->kvm->srcu);
11951 		if (is_pae_paging(vcpu)) {
11952 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11953 			*mmu_reset_needed = 1;
11954 		}
11955 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
11956 	}
11957 
11958 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11959 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11960 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11961 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11962 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11963 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11964 
11965 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11966 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11967 
11968 	update_cr8_intercept(vcpu);
11969 
11970 	/* Older userspace won't unhalt the vcpu on reset. */
11971 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11972 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11973 	    !is_protmode(vcpu))
11974 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11975 
11976 	return 0;
11977 }
11978 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11979 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11980 {
11981 	int pending_vec, max_bits;
11982 	int mmu_reset_needed = 0;
11983 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11984 
11985 	if (ret)
11986 		return ret;
11987 
11988 	if (mmu_reset_needed) {
11989 		kvm_mmu_reset_context(vcpu);
11990 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11991 	}
11992 
11993 	max_bits = KVM_NR_INTERRUPTS;
11994 	pending_vec = find_first_bit(
11995 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
11996 
11997 	if (pending_vec < max_bits) {
11998 		kvm_queue_interrupt(vcpu, pending_vec, false);
11999 		pr_debug("Set back pending irq %d\n", pending_vec);
12000 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12001 	}
12002 	return 0;
12003 }
12004 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12005 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12006 {
12007 	int mmu_reset_needed = 0;
12008 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12009 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12010 		!(sregs2->efer & EFER_LMA);
12011 	int i, ret;
12012 
12013 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12014 		return -EINVAL;
12015 
12016 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12017 		return -EINVAL;
12018 
12019 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12020 				 &mmu_reset_needed, !valid_pdptrs);
12021 	if (ret)
12022 		return ret;
12023 
12024 	if (valid_pdptrs) {
12025 		for (i = 0; i < 4 ; i++)
12026 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12027 
12028 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12029 		mmu_reset_needed = 1;
12030 		vcpu->arch.pdptrs_from_userspace = true;
12031 	}
12032 	if (mmu_reset_needed) {
12033 		kvm_mmu_reset_context(vcpu);
12034 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12035 	}
12036 	return 0;
12037 }
12038 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12039 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12040 				  struct kvm_sregs *sregs)
12041 {
12042 	int ret;
12043 
12044 	if (vcpu->kvm->arch.has_protected_state &&
12045 	    vcpu->arch.guest_state_protected)
12046 		return -EINVAL;
12047 
12048 	vcpu_load(vcpu);
12049 	ret = __set_sregs(vcpu, sregs);
12050 	vcpu_put(vcpu);
12051 	return ret;
12052 }
12053 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12054 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12055 {
12056 	bool set = false;
12057 	struct kvm_vcpu *vcpu;
12058 	unsigned long i;
12059 
12060 	if (!enable_apicv)
12061 		return;
12062 
12063 	down_write(&kvm->arch.apicv_update_lock);
12064 
12065 	kvm_for_each_vcpu(i, vcpu, kvm) {
12066 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12067 			set = true;
12068 			break;
12069 		}
12070 	}
12071 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12072 	up_write(&kvm->arch.apicv_update_lock);
12073 }
12074 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12075 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12076 					struct kvm_guest_debug *dbg)
12077 {
12078 	unsigned long rflags;
12079 	int i, r;
12080 
12081 	if (vcpu->arch.guest_state_protected)
12082 		return -EINVAL;
12083 
12084 	vcpu_load(vcpu);
12085 
12086 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12087 		r = -EBUSY;
12088 		if (kvm_is_exception_pending(vcpu))
12089 			goto out;
12090 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12091 			kvm_queue_exception(vcpu, DB_VECTOR);
12092 		else
12093 			kvm_queue_exception(vcpu, BP_VECTOR);
12094 	}
12095 
12096 	/*
12097 	 * Read rflags as long as potentially injected trace flags are still
12098 	 * filtered out.
12099 	 */
12100 	rflags = kvm_get_rflags(vcpu);
12101 
12102 	vcpu->guest_debug = dbg->control;
12103 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12104 		vcpu->guest_debug = 0;
12105 
12106 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12107 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
12108 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12109 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12110 	} else {
12111 		for (i = 0; i < KVM_NR_DB_REGS; i++)
12112 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12113 	}
12114 	kvm_update_dr7(vcpu);
12115 
12116 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12117 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12118 
12119 	/*
12120 	 * Trigger an rflags update that will inject or remove the trace
12121 	 * flags.
12122 	 */
12123 	kvm_set_rflags(vcpu, rflags);
12124 
12125 	kvm_x86_call(update_exception_bitmap)(vcpu);
12126 
12127 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12128 
12129 	r = 0;
12130 
12131 out:
12132 	vcpu_put(vcpu);
12133 	return r;
12134 }
12135 
12136 /*
12137  * Translate a guest virtual address to a guest physical address.
12138  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12139 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12140 				    struct kvm_translation *tr)
12141 {
12142 	unsigned long vaddr = tr->linear_address;
12143 	gpa_t gpa;
12144 	int idx;
12145 
12146 	vcpu_load(vcpu);
12147 
12148 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12149 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12150 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12151 	tr->physical_address = gpa;
12152 	tr->valid = gpa != INVALID_GPA;
12153 	tr->writeable = 1;
12154 	tr->usermode = 0;
12155 
12156 	vcpu_put(vcpu);
12157 	return 0;
12158 }
12159 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12160 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12161 {
12162 	struct fxregs_state *fxsave;
12163 
12164 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12165 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12166 
12167 	vcpu_load(vcpu);
12168 
12169 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12170 	memcpy(fpu->fpr, fxsave->st_space, 128);
12171 	fpu->fcw = fxsave->cwd;
12172 	fpu->fsw = fxsave->swd;
12173 	fpu->ftwx = fxsave->twd;
12174 	fpu->last_opcode = fxsave->fop;
12175 	fpu->last_ip = fxsave->rip;
12176 	fpu->last_dp = fxsave->rdp;
12177 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12178 
12179 	vcpu_put(vcpu);
12180 	return 0;
12181 }
12182 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12183 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12184 {
12185 	struct fxregs_state *fxsave;
12186 
12187 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12188 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12189 
12190 	vcpu_load(vcpu);
12191 
12192 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12193 
12194 	memcpy(fxsave->st_space, fpu->fpr, 128);
12195 	fxsave->cwd = fpu->fcw;
12196 	fxsave->swd = fpu->fsw;
12197 	fxsave->twd = fpu->ftwx;
12198 	fxsave->fop = fpu->last_opcode;
12199 	fxsave->rip = fpu->last_ip;
12200 	fxsave->rdp = fpu->last_dp;
12201 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12202 
12203 	vcpu_put(vcpu);
12204 	return 0;
12205 }
12206 
store_regs(struct kvm_vcpu * vcpu)12207 static void store_regs(struct kvm_vcpu *vcpu)
12208 {
12209 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12210 
12211 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12212 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
12213 
12214 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12215 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12216 
12217 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12218 		kvm_vcpu_ioctl_x86_get_vcpu_events(
12219 				vcpu, &vcpu->run->s.regs.events);
12220 }
12221 
sync_regs(struct kvm_vcpu * vcpu)12222 static int sync_regs(struct kvm_vcpu *vcpu)
12223 {
12224 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12225 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
12226 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12227 	}
12228 
12229 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12230 		struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12231 
12232 		if (__set_sregs(vcpu, &sregs))
12233 			return -EINVAL;
12234 
12235 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12236 	}
12237 
12238 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12239 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12240 
12241 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12242 			return -EINVAL;
12243 
12244 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12245 	}
12246 
12247 	return 0;
12248 }
12249 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12250 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12251 {
12252 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12253 		pr_warn_once("SMP vm created on host with unstable TSC; "
12254 			     "guest TSC will not be reliable\n");
12255 
12256 	if (!kvm->arch.max_vcpu_ids)
12257 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12258 
12259 	if (id >= kvm->arch.max_vcpu_ids)
12260 		return -EINVAL;
12261 
12262 	return kvm_x86_call(vcpu_precreate)(kvm);
12263 }
12264 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12265 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12266 {
12267 	struct page *page;
12268 	int r;
12269 
12270 	vcpu->arch.last_vmentry_cpu = -1;
12271 	vcpu->arch.regs_avail = ~0;
12272 	vcpu->arch.regs_dirty = ~0;
12273 
12274 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12275 
12276 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12277 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12278 	else
12279 		kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12280 
12281 	r = kvm_mmu_create(vcpu);
12282 	if (r < 0)
12283 		return r;
12284 
12285 	r = kvm_create_lapic(vcpu);
12286 	if (r < 0)
12287 		goto fail_mmu_destroy;
12288 
12289 	r = -ENOMEM;
12290 
12291 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12292 	if (!page)
12293 		goto fail_free_lapic;
12294 	vcpu->arch.pio_data = page_address(page);
12295 
12296 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12297 				       GFP_KERNEL_ACCOUNT);
12298 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12299 					    GFP_KERNEL_ACCOUNT);
12300 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12301 		goto fail_free_mce_banks;
12302 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12303 
12304 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12305 				GFP_KERNEL_ACCOUNT))
12306 		goto fail_free_mce_banks;
12307 
12308 	if (!alloc_emulate_ctxt(vcpu))
12309 		goto free_wbinvd_dirty_mask;
12310 
12311 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12312 		pr_err("failed to allocate vcpu's fpu\n");
12313 		goto free_emulate_ctxt;
12314 	}
12315 
12316 	kvm_async_pf_hash_reset(vcpu);
12317 
12318 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12319 		vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12320 		vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12321 		vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12322 	}
12323 	kvm_pmu_init(vcpu);
12324 
12325 	vcpu->arch.pending_external_vector = -1;
12326 	vcpu->arch.preempted_in_kernel = false;
12327 
12328 #if IS_ENABLED(CONFIG_HYPERV)
12329 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
12330 #endif
12331 
12332 	r = kvm_x86_call(vcpu_create)(vcpu);
12333 	if (r)
12334 		goto free_guest_fpu;
12335 
12336 	kvm_xen_init_vcpu(vcpu);
12337 	vcpu_load(vcpu);
12338 	kvm_vcpu_after_set_cpuid(vcpu);
12339 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12340 	kvm_vcpu_reset(vcpu, false);
12341 	kvm_init_mmu(vcpu);
12342 	vcpu_put(vcpu);
12343 	return 0;
12344 
12345 free_guest_fpu:
12346 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12347 free_emulate_ctxt:
12348 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12349 free_wbinvd_dirty_mask:
12350 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12351 fail_free_mce_banks:
12352 	kfree(vcpu->arch.mce_banks);
12353 	kfree(vcpu->arch.mci_ctl2_banks);
12354 	free_page((unsigned long)vcpu->arch.pio_data);
12355 fail_free_lapic:
12356 	kvm_free_lapic(vcpu);
12357 fail_mmu_destroy:
12358 	kvm_mmu_destroy(vcpu);
12359 	return r;
12360 }
12361 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12362 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12363 {
12364 	struct kvm *kvm = vcpu->kvm;
12365 
12366 	if (mutex_lock_killable(&vcpu->mutex))
12367 		return;
12368 	vcpu_load(vcpu);
12369 	kvm_synchronize_tsc(vcpu, NULL);
12370 	vcpu_put(vcpu);
12371 
12372 	/* poll control enabled by default */
12373 	vcpu->arch.msr_kvm_poll_control = 1;
12374 
12375 	mutex_unlock(&vcpu->mutex);
12376 
12377 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12378 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12379 						KVMCLOCK_SYNC_PERIOD);
12380 }
12381 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12382 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12383 {
12384 	int idx;
12385 
12386 	kvm_clear_async_pf_completion_queue(vcpu);
12387 	kvm_mmu_unload(vcpu);
12388 
12389 	kvmclock_reset(vcpu);
12390 
12391 	kvm_x86_call(vcpu_free)(vcpu);
12392 
12393 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12394 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12395 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12396 
12397 	kvm_xen_destroy_vcpu(vcpu);
12398 	kvm_hv_vcpu_uninit(vcpu);
12399 	kvm_pmu_destroy(vcpu);
12400 	kfree(vcpu->arch.mce_banks);
12401 	kfree(vcpu->arch.mci_ctl2_banks);
12402 	kvm_free_lapic(vcpu);
12403 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12404 	kvm_mmu_destroy(vcpu);
12405 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12406 	free_page((unsigned long)vcpu->arch.pio_data);
12407 	kvfree(vcpu->arch.cpuid_entries);
12408 }
12409 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12410 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12411 {
12412 	struct kvm_cpuid_entry2 *cpuid_0x1;
12413 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
12414 	unsigned long new_cr0;
12415 
12416 	/*
12417 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12418 	 * to handle side effects.  RESET emulation hits those flows and relies
12419 	 * on emulated/virtualized registers, including those that are loaded
12420 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
12421 	 * to detect improper or missing initialization.
12422 	 */
12423 	WARN_ON_ONCE(!init_event &&
12424 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12425 
12426 	/*
12427 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12428 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
12429 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12430 	 * bits), i.e. virtualization is disabled.
12431 	 */
12432 	if (is_guest_mode(vcpu))
12433 		kvm_leave_nested(vcpu);
12434 
12435 	kvm_lapic_reset(vcpu, init_event);
12436 
12437 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12438 	vcpu->arch.hflags = 0;
12439 
12440 	vcpu->arch.smi_pending = 0;
12441 	vcpu->arch.smi_count = 0;
12442 	atomic_set(&vcpu->arch.nmi_queued, 0);
12443 	vcpu->arch.nmi_pending = 0;
12444 	vcpu->arch.nmi_injected = false;
12445 	kvm_clear_interrupt_queue(vcpu);
12446 	kvm_clear_exception_queue(vcpu);
12447 
12448 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12449 	kvm_update_dr0123(vcpu);
12450 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12451 	vcpu->arch.dr7 = DR7_FIXED_1;
12452 	kvm_update_dr7(vcpu);
12453 
12454 	vcpu->arch.cr2 = 0;
12455 
12456 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12457 	vcpu->arch.apf.msr_en_val = 0;
12458 	vcpu->arch.apf.msr_int_val = 0;
12459 	vcpu->arch.st.msr_val = 0;
12460 
12461 	kvmclock_reset(vcpu);
12462 
12463 	kvm_clear_async_pf_completion_queue(vcpu);
12464 	kvm_async_pf_hash_reset(vcpu);
12465 	vcpu->arch.apf.halted = false;
12466 
12467 	if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12468 		struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12469 
12470 		/*
12471 		 * All paths that lead to INIT are required to load the guest's
12472 		 * FPU state (because most paths are buried in KVM_RUN).
12473 		 */
12474 		if (init_event)
12475 			kvm_put_guest_fpu(vcpu);
12476 
12477 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12478 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12479 
12480 		if (init_event)
12481 			kvm_load_guest_fpu(vcpu);
12482 	}
12483 
12484 	if (!init_event) {
12485 		vcpu->arch.smbase = 0x30000;
12486 
12487 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12488 
12489 		vcpu->arch.msr_misc_features_enables = 0;
12490 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12491 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12492 
12493 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12494 		__kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12495 	}
12496 
12497 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12498 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12499 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12500 
12501 	/*
12502 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12503 	 * if no CPUID match is found.  Note, it's impossible to get a match at
12504 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12505 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12506 	 * on RESET.  But, go through the motions in case that's ever remedied.
12507 	 */
12508 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12509 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12510 
12511 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
12512 
12513 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12514 	kvm_rip_write(vcpu, 0xfff0);
12515 
12516 	vcpu->arch.cr3 = 0;
12517 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12518 
12519 	/*
12520 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
12521 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12522 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
12523 	 */
12524 	new_cr0 = X86_CR0_ET;
12525 	if (init_event)
12526 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12527 	else
12528 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12529 
12530 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
12531 	kvm_x86_call(set_cr4)(vcpu, 0);
12532 	kvm_x86_call(set_efer)(vcpu, 0);
12533 	kvm_x86_call(update_exception_bitmap)(vcpu);
12534 
12535 	/*
12536 	 * On the standard CR0/CR4/EFER modification paths, there are several
12537 	 * complex conditions determining whether the MMU has to be reset and/or
12538 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
12539 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12540 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12541 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
12542 	 */
12543 	if (old_cr0 & X86_CR0_PG) {
12544 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12545 		kvm_mmu_reset_context(vcpu);
12546 	}
12547 
12548 	/*
12549 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
12550 	 * APM states the TLBs are untouched by INIT, but it also states that
12551 	 * the TLBs are flushed on "External initialization of the processor."
12552 	 * Flush the guest TLB regardless of vendor, there is no meaningful
12553 	 * benefit in relying on the guest to flush the TLB immediately after
12554 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
12555 	 * performance perspective.
12556 	 */
12557 	if (init_event)
12558 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12559 }
12560 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12561 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12562 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12563 {
12564 	struct kvm_segment cs;
12565 
12566 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12567 	cs.selector = vector << 8;
12568 	cs.base = vector << 12;
12569 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12570 	kvm_rip_write(vcpu, 0);
12571 }
12572 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12573 
kvm_arch_enable_virtualization(void)12574 void kvm_arch_enable_virtualization(void)
12575 {
12576 	cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12577 }
12578 
kvm_arch_disable_virtualization(void)12579 void kvm_arch_disable_virtualization(void)
12580 {
12581 	cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12582 }
12583 
kvm_arch_enable_virtualization_cpu(void)12584 int kvm_arch_enable_virtualization_cpu(void)
12585 {
12586 	struct kvm *kvm;
12587 	struct kvm_vcpu *vcpu;
12588 	unsigned long i;
12589 	int ret;
12590 	u64 local_tsc;
12591 	u64 max_tsc = 0;
12592 	bool stable, backwards_tsc = false;
12593 
12594 	kvm_user_return_msr_cpu_online();
12595 
12596 	ret = kvm_x86_check_processor_compatibility();
12597 	if (ret)
12598 		return ret;
12599 
12600 	ret = kvm_x86_call(enable_virtualization_cpu)();
12601 	if (ret != 0)
12602 		return ret;
12603 
12604 	local_tsc = rdtsc();
12605 	stable = !kvm_check_tsc_unstable();
12606 	list_for_each_entry(kvm, &vm_list, vm_list) {
12607 		kvm_for_each_vcpu(i, vcpu, kvm) {
12608 			if (!stable && vcpu->cpu == smp_processor_id())
12609 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12610 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12611 				backwards_tsc = true;
12612 				if (vcpu->arch.last_host_tsc > max_tsc)
12613 					max_tsc = vcpu->arch.last_host_tsc;
12614 			}
12615 		}
12616 	}
12617 
12618 	/*
12619 	 * Sometimes, even reliable TSCs go backwards.  This happens on
12620 	 * platforms that reset TSC during suspend or hibernate actions, but
12621 	 * maintain synchronization.  We must compensate.  Fortunately, we can
12622 	 * detect that condition here, which happens early in CPU bringup,
12623 	 * before any KVM threads can be running.  Unfortunately, we can't
12624 	 * bring the TSCs fully up to date with real time, as we aren't yet far
12625 	 * enough into CPU bringup that we know how much real time has actually
12626 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12627 	 * variables that haven't been updated yet.
12628 	 *
12629 	 * So we simply find the maximum observed TSC above, then record the
12630 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
12631 	 * the adjustment will be applied.  Note that we accumulate
12632 	 * adjustments, in case multiple suspend cycles happen before some VCPU
12633 	 * gets a chance to run again.  In the event that no KVM threads get a
12634 	 * chance to run, we will miss the entire elapsed period, as we'll have
12635 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12636 	 * loose cycle time.  This isn't too big a deal, since the loss will be
12637 	 * uniform across all VCPUs (not to mention the scenario is extremely
12638 	 * unlikely). It is possible that a second hibernate recovery happens
12639 	 * much faster than a first, causing the observed TSC here to be
12640 	 * smaller; this would require additional padding adjustment, which is
12641 	 * why we set last_host_tsc to the local tsc observed here.
12642 	 *
12643 	 * N.B. - this code below runs only on platforms with reliable TSC,
12644 	 * as that is the only way backwards_tsc is set above.  Also note
12645 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12646 	 * have the same delta_cyc adjustment applied if backwards_tsc
12647 	 * is detected.  Note further, this adjustment is only done once,
12648 	 * as we reset last_host_tsc on all VCPUs to stop this from being
12649 	 * called multiple times (one for each physical CPU bringup).
12650 	 *
12651 	 * Platforms with unreliable TSCs don't have to deal with this, they
12652 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
12653 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
12654 	 * guarantee that they stay in perfect synchronization.
12655 	 */
12656 	if (backwards_tsc) {
12657 		u64 delta_cyc = max_tsc - local_tsc;
12658 		list_for_each_entry(kvm, &vm_list, vm_list) {
12659 			kvm->arch.backwards_tsc_observed = true;
12660 			kvm_for_each_vcpu(i, vcpu, kvm) {
12661 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
12662 				vcpu->arch.last_host_tsc = local_tsc;
12663 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12664 			}
12665 
12666 			/*
12667 			 * We have to disable TSC offset matching.. if you were
12668 			 * booting a VM while issuing an S4 host suspend....
12669 			 * you may have some problem.  Solving this issue is
12670 			 * left as an exercise to the reader.
12671 			 */
12672 			kvm->arch.last_tsc_nsec = 0;
12673 			kvm->arch.last_tsc_write = 0;
12674 		}
12675 
12676 	}
12677 	return 0;
12678 }
12679 
kvm_arch_disable_virtualization_cpu(void)12680 void kvm_arch_disable_virtualization_cpu(void)
12681 {
12682 	kvm_x86_call(disable_virtualization_cpu)();
12683 	drop_user_return_notifiers();
12684 }
12685 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)12686 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12687 {
12688 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12689 }
12690 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)12691 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12692 {
12693 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12694 }
12695 
kvm_arch_free_vm(struct kvm * kvm)12696 void kvm_arch_free_vm(struct kvm *kvm)
12697 {
12698 #if IS_ENABLED(CONFIG_HYPERV)
12699 	kfree(kvm->arch.hv_pa_pg);
12700 #endif
12701 	__kvm_arch_free_vm(kvm);
12702 }
12703 
12704 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)12705 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12706 {
12707 	int ret;
12708 	unsigned long flags;
12709 
12710 	if (!kvm_is_vm_type_supported(type))
12711 		return -EINVAL;
12712 
12713 	kvm->arch.vm_type = type;
12714 	kvm->arch.has_private_mem =
12715 		(type == KVM_X86_SW_PROTECTED_VM);
12716 	/* Decided by the vendor code for other VM types.  */
12717 	kvm->arch.pre_fault_allowed =
12718 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
12719 
12720 	ret = kvm_page_track_init(kvm);
12721 	if (ret)
12722 		goto out;
12723 
12724 	kvm_mmu_init_vm(kvm);
12725 
12726 	ret = kvm_x86_call(vm_init)(kvm);
12727 	if (ret)
12728 		goto out_uninit_mmu;
12729 
12730 	INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12731 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12732 
12733 	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12734 	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12735 	/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12736 	set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12737 		&kvm->arch.irq_sources_bitmap);
12738 
12739 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12740 	mutex_init(&kvm->arch.apic_map_lock);
12741 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12742 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12743 
12744 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12745 	pvclock_update_vm_gtod_copy(kvm);
12746 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12747 
12748 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12749 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
12750 	kvm->arch.guest_can_read_msr_platform_info = true;
12751 	kvm->arch.enable_pmu = enable_pmu;
12752 
12753 #if IS_ENABLED(CONFIG_HYPERV)
12754 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12755 	kvm->arch.hv_root_tdp = INVALID_PAGE;
12756 #endif
12757 
12758 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12759 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12760 
12761 	kvm_apicv_init(kvm);
12762 	kvm_hv_init_vm(kvm);
12763 	kvm_xen_init_vm(kvm);
12764 
12765 	if (ignore_msrs && !report_ignored_msrs) {
12766 		pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
12767 			     "a supported configuration.  Lying to the guest about the existence of MSRs\n"
12768 			     "may cause the guest operating system to hang or produce errors.  If a guest\n"
12769 			     "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
12770 	}
12771 
12772 	once_init(&kvm->arch.nx_once);
12773 	return 0;
12774 
12775 out_uninit_mmu:
12776 	kvm_mmu_uninit_vm(kvm);
12777 	kvm_page_track_cleanup(kvm);
12778 out:
12779 	return ret;
12780 }
12781 
12782 /**
12783  * __x86_set_memory_region: Setup KVM internal memory slot
12784  *
12785  * @kvm: the kvm pointer to the VM.
12786  * @id: the slot ID to setup.
12787  * @gpa: the GPA to install the slot (unused when @size == 0).
12788  * @size: the size of the slot. Set to zero to uninstall a slot.
12789  *
12790  * This function helps to setup a KVM internal memory slot.  Specify
12791  * @size > 0 to install a new slot, while @size == 0 to uninstall a
12792  * slot.  The return code can be one of the following:
12793  *
12794  *   HVA:           on success (uninstall will return a bogus HVA)
12795  *   -errno:        on error
12796  *
12797  * The caller should always use IS_ERR() to check the return value
12798  * before use.  Note, the KVM internal memory slots are guaranteed to
12799  * remain valid and unchanged until the VM is destroyed, i.e., the
12800  * GPA->HVA translation will not change.  However, the HVA is a user
12801  * address, i.e. its accessibility is not guaranteed, and must be
12802  * accessed via __copy_{to,from}_user().
12803  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)12804 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12805 				      u32 size)
12806 {
12807 	int i, r;
12808 	unsigned long hva, old_npages;
12809 	struct kvm_memslots *slots = kvm_memslots(kvm);
12810 	struct kvm_memory_slot *slot;
12811 
12812 	lockdep_assert_held(&kvm->slots_lock);
12813 
12814 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12815 		return ERR_PTR_USR(-EINVAL);
12816 
12817 	slot = id_to_memslot(slots, id);
12818 	if (size) {
12819 		if (slot && slot->npages)
12820 			return ERR_PTR_USR(-EEXIST);
12821 
12822 		/*
12823 		 * MAP_SHARED to prevent internal slot pages from being moved
12824 		 * by fork()/COW.
12825 		 */
12826 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12827 			      MAP_SHARED | MAP_ANONYMOUS, 0);
12828 		if (IS_ERR_VALUE(hva))
12829 			return (void __user *)hva;
12830 	} else {
12831 		if (!slot || !slot->npages)
12832 			return NULL;
12833 
12834 		old_npages = slot->npages;
12835 		hva = slot->userspace_addr;
12836 	}
12837 
12838 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
12839 		struct kvm_userspace_memory_region2 m;
12840 
12841 		m.slot = id | (i << 16);
12842 		m.flags = 0;
12843 		m.guest_phys_addr = gpa;
12844 		m.userspace_addr = hva;
12845 		m.memory_size = size;
12846 		r = kvm_set_internal_memslot(kvm, &m);
12847 		if (r < 0)
12848 			return ERR_PTR_USR(r);
12849 	}
12850 
12851 	if (!size)
12852 		vm_munmap(hva, old_npages * PAGE_SIZE);
12853 
12854 	return (void __user *)hva;
12855 }
12856 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12857 
kvm_arch_pre_destroy_vm(struct kvm * kvm)12858 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12859 {
12860 	/*
12861 	 * Stop all background workers and kthreads before destroying vCPUs, as
12862 	 * iterating over vCPUs in a different task while vCPUs are being freed
12863 	 * is unsafe, i.e. will lead to use-after-free.  The PIT also needs to
12864 	 * be stopped before IRQ routing is freed.
12865 	 */
12866 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12867 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12868 
12869 	kvm_free_pit(kvm);
12870 
12871 	kvm_mmu_pre_destroy_vm(kvm);
12872 }
12873 
kvm_arch_destroy_vm(struct kvm * kvm)12874 void kvm_arch_destroy_vm(struct kvm *kvm)
12875 {
12876 	if (current->mm == kvm->mm) {
12877 		/*
12878 		 * Free memory regions allocated on behalf of userspace,
12879 		 * unless the memory map has changed due to process exit
12880 		 * or fd copying.
12881 		 */
12882 		mutex_lock(&kvm->slots_lock);
12883 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12884 					0, 0);
12885 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12886 					0, 0);
12887 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12888 		mutex_unlock(&kvm->slots_lock);
12889 	}
12890 	kvm_destroy_vcpus(kvm);
12891 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12892 	kvm_pic_destroy(kvm);
12893 	kvm_ioapic_destroy(kvm);
12894 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12895 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12896 	kvm_mmu_uninit_vm(kvm);
12897 	kvm_page_track_cleanup(kvm);
12898 	kvm_xen_destroy_vm(kvm);
12899 	kvm_hv_destroy_vm(kvm);
12900 	kvm_x86_call(vm_destroy)(kvm);
12901 }
12902 
memslot_rmap_free(struct kvm_memory_slot * slot)12903 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12904 {
12905 	int i;
12906 
12907 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12908 		vfree(slot->arch.rmap[i]);
12909 		slot->arch.rmap[i] = NULL;
12910 	}
12911 }
12912 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12913 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12914 {
12915 	int i;
12916 
12917 	memslot_rmap_free(slot);
12918 
12919 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12920 		vfree(slot->arch.lpage_info[i - 1]);
12921 		slot->arch.lpage_info[i - 1] = NULL;
12922 	}
12923 
12924 	kvm_page_track_free_memslot(slot);
12925 }
12926 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)12927 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12928 {
12929 	const int sz = sizeof(*slot->arch.rmap[0]);
12930 	int i;
12931 
12932 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12933 		int level = i + 1;
12934 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12935 
12936 		if (slot->arch.rmap[i])
12937 			continue;
12938 
12939 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12940 		if (!slot->arch.rmap[i]) {
12941 			memslot_rmap_free(slot);
12942 			return -ENOMEM;
12943 		}
12944 	}
12945 
12946 	return 0;
12947 }
12948 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)12949 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12950 				      struct kvm_memory_slot *slot)
12951 {
12952 	unsigned long npages = slot->npages;
12953 	int i, r;
12954 
12955 	/*
12956 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
12957 	 * old arrays will be freed by kvm_set_memory_region() if installing
12958 	 * the new memslot is successful.
12959 	 */
12960 	memset(&slot->arch, 0, sizeof(slot->arch));
12961 
12962 	if (kvm_memslots_have_rmaps(kvm)) {
12963 		r = memslot_rmap_alloc(slot, npages);
12964 		if (r)
12965 			return r;
12966 	}
12967 
12968 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12969 		struct kvm_lpage_info *linfo;
12970 		unsigned long ugfn;
12971 		int lpages;
12972 		int level = i + 1;
12973 
12974 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12975 
12976 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12977 		if (!linfo)
12978 			goto out_free;
12979 
12980 		slot->arch.lpage_info[i - 1] = linfo;
12981 
12982 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12983 			linfo[0].disallow_lpage = 1;
12984 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12985 			linfo[lpages - 1].disallow_lpage = 1;
12986 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
12987 		/*
12988 		 * If the gfn and userspace address are not aligned wrt each
12989 		 * other, disable large page support for this slot.
12990 		 */
12991 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12992 			unsigned long j;
12993 
12994 			for (j = 0; j < lpages; ++j)
12995 				linfo[j].disallow_lpage = 1;
12996 		}
12997 	}
12998 
12999 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13000 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13001 #endif
13002 
13003 	if (kvm_page_track_create_memslot(kvm, slot, npages))
13004 		goto out_free;
13005 
13006 	return 0;
13007 
13008 out_free:
13009 	memslot_rmap_free(slot);
13010 
13011 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13012 		vfree(slot->arch.lpage_info[i - 1]);
13013 		slot->arch.lpage_info[i - 1] = NULL;
13014 	}
13015 	return -ENOMEM;
13016 }
13017 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13018 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13019 {
13020 	struct kvm_vcpu *vcpu;
13021 	unsigned long i;
13022 
13023 	/*
13024 	 * memslots->generation has been incremented.
13025 	 * mmio generation may have reached its maximum value.
13026 	 */
13027 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13028 
13029 	/* Force re-initialization of steal_time cache */
13030 	kvm_for_each_vcpu(i, vcpu, kvm)
13031 		kvm_vcpu_kick(vcpu);
13032 }
13033 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13034 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13035 				   const struct kvm_memory_slot *old,
13036 				   struct kvm_memory_slot *new,
13037 				   enum kvm_mr_change change)
13038 {
13039 	/*
13040 	 * KVM doesn't support moving memslots when there are external page
13041 	 * trackers attached to the VM, i.e. if KVMGT is in use.
13042 	 */
13043 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13044 		return -EINVAL;
13045 
13046 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13047 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13048 			return -EINVAL;
13049 
13050 		if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13051 			return -EINVAL;
13052 
13053 		return kvm_alloc_memslot_metadata(kvm, new);
13054 	}
13055 
13056 	if (change == KVM_MR_FLAGS_ONLY)
13057 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
13058 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13059 		return -EIO;
13060 
13061 	return 0;
13062 }
13063 
13064 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13065 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13066 {
13067 	int nr_slots;
13068 
13069 	if (!kvm_x86_ops.cpu_dirty_log_size)
13070 		return;
13071 
13072 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13073 	if ((enable && nr_slots == 1) || !nr_slots)
13074 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13075 }
13076 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13077 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13078 				     struct kvm_memory_slot *old,
13079 				     const struct kvm_memory_slot *new,
13080 				     enum kvm_mr_change change)
13081 {
13082 	u32 old_flags = old ? old->flags : 0;
13083 	u32 new_flags = new ? new->flags : 0;
13084 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13085 
13086 	/*
13087 	 * Update CPU dirty logging if dirty logging is being toggled.  This
13088 	 * applies to all operations.
13089 	 */
13090 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13091 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13092 
13093 	/*
13094 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
13095 	 * made writable) or CREATE/MOVE/DELETE of a slot.
13096 	 *
13097 	 * For a memslot with dirty logging disabled:
13098 	 * CREATE:      No dirty mappings will already exist.
13099 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13100 	 *		kvm_arch_flush_shadow_memslot()
13101 	 *
13102 	 * For a memslot with dirty logging enabled:
13103 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
13104 	 *		and no dirty bits to clear.
13105 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13106 	 *		kvm_arch_flush_shadow_memslot().
13107 	 */
13108 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13109 		return;
13110 
13111 	/*
13112 	 * READONLY and non-flags changes were filtered out above, and the only
13113 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13114 	 * logging isn't being toggled on or off.
13115 	 */
13116 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13117 		return;
13118 
13119 	if (!log_dirty_pages) {
13120 		/*
13121 		 * Recover huge page mappings in the slot now that dirty logging
13122 		 * is disabled, i.e. now that KVM does not have to track guest
13123 		 * writes at 4KiB granularity.
13124 		 *
13125 		 * Dirty logging might be disabled by userspace if an ongoing VM
13126 		 * live migration is cancelled and the VM must continue running
13127 		 * on the source.
13128 		 */
13129 		kvm_mmu_recover_huge_pages(kvm, new);
13130 	} else {
13131 		/*
13132 		 * Initially-all-set does not require write protecting any page,
13133 		 * because they're all assumed to be dirty.
13134 		 */
13135 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13136 			return;
13137 
13138 		if (READ_ONCE(eager_page_split))
13139 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13140 
13141 		if (kvm_x86_ops.cpu_dirty_log_size) {
13142 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13143 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13144 		} else {
13145 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13146 		}
13147 
13148 		/*
13149 		 * Unconditionally flush the TLBs after enabling dirty logging.
13150 		 * A flush is almost always going to be necessary (see below),
13151 		 * and unconditionally flushing allows the helpers to omit
13152 		 * the subtly complex checks when removing write access.
13153 		 *
13154 		 * Do the flush outside of mmu_lock to reduce the amount of
13155 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
13156 		 * safe as KVM only needs to guarantee the slot is fully
13157 		 * write-protected before returning to userspace, i.e. before
13158 		 * userspace can consume the dirty status.
13159 		 *
13160 		 * Flushing outside of mmu_lock requires KVM to be careful when
13161 		 * making decisions based on writable status of an SPTE, e.g. a
13162 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13163 		 *
13164 		 * Specifically, KVM also write-protects guest page tables to
13165 		 * monitor changes when using shadow paging, and must guarantee
13166 		 * no CPUs can write to those page before mmu_lock is dropped.
13167 		 * Because CPUs may have stale TLB entries at this point, a
13168 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13169 		 *
13170 		 * KVM also allows making SPTES writable outside of mmu_lock,
13171 		 * e.g. to allow dirty logging without taking mmu_lock.
13172 		 *
13173 		 * To handle these scenarios, KVM uses a separate software-only
13174 		 * bit (MMU-writable) to track if a SPTE is !writable due to
13175 		 * a guest page table being write-protected (KVM clears the
13176 		 * MMU-writable flag when write-protecting for shadow paging).
13177 		 *
13178 		 * The use of MMU-writable is also the primary motivation for
13179 		 * the unconditional flush.  Because KVM must guarantee that a
13180 		 * CPU doesn't contain stale, writable TLB entries for a
13181 		 * !MMU-writable SPTE, KVM must flush if it encounters any
13182 		 * MMU-writable SPTE regardless of whether the actual hardware
13183 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
13184 		 * to flush, while unconditionally flushing allows the "remove
13185 		 * write access" helpers to ignore MMU-writable entirely.
13186 		 *
13187 		 * See is_writable_pte() for more details (the case involving
13188 		 * access-tracked SPTEs is particularly relevant).
13189 		 */
13190 		kvm_flush_remote_tlbs_memslot(kvm, new);
13191 	}
13192 }
13193 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13194 void kvm_arch_commit_memory_region(struct kvm *kvm,
13195 				struct kvm_memory_slot *old,
13196 				const struct kvm_memory_slot *new,
13197 				enum kvm_mr_change change)
13198 {
13199 	if (change == KVM_MR_DELETE)
13200 		kvm_page_track_delete_slot(kvm, old);
13201 
13202 	if (!kvm->arch.n_requested_mmu_pages &&
13203 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13204 		unsigned long nr_mmu_pages;
13205 
13206 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13207 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13208 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13209 	}
13210 
13211 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
13212 
13213 	/* Free the arrays associated with the old memslot. */
13214 	if (change == KVM_MR_MOVE)
13215 		kvm_arch_free_memslot(kvm, old);
13216 }
13217 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13218 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13219 {
13220 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13221 
13222 	if (vcpu->arch.guest_state_protected)
13223 		return true;
13224 
13225 	return kvm_x86_call(get_cpl)(vcpu) == 0;
13226 }
13227 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13228 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13229 {
13230 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13231 
13232 	if (vcpu->arch.guest_state_protected)
13233 		return 0;
13234 
13235 	return kvm_rip_read(vcpu);
13236 }
13237 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13238 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13239 {
13240 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13241 }
13242 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13243 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13244 {
13245 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
13246 }
13247 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13248 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13249 {
13250 	/* Can't read the RIP when guest state is protected, just return 0 */
13251 	if (vcpu->arch.guest_state_protected)
13252 		return 0;
13253 
13254 	if (is_64_bit_mode(vcpu))
13255 		return kvm_rip_read(vcpu);
13256 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13257 		     kvm_rip_read(vcpu));
13258 }
13259 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13260 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13261 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13262 {
13263 	return kvm_get_linear_rip(vcpu) == linear_rip;
13264 }
13265 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13266 
kvm_get_rflags(struct kvm_vcpu * vcpu)13267 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13268 {
13269 	unsigned long rflags;
13270 
13271 	rflags = kvm_x86_call(get_rflags)(vcpu);
13272 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13273 		rflags &= ~X86_EFLAGS_TF;
13274 	return rflags;
13275 }
13276 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13277 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13278 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13279 {
13280 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13281 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13282 		rflags |= X86_EFLAGS_TF;
13283 	kvm_x86_call(set_rflags)(vcpu, rflags);
13284 }
13285 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13286 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13287 {
13288 	__kvm_set_rflags(vcpu, rflags);
13289 	kvm_make_request(KVM_REQ_EVENT, vcpu);
13290 }
13291 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13292 
kvm_async_pf_hash_fn(gfn_t gfn)13293 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13294 {
13295 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13296 
13297 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13298 }
13299 
kvm_async_pf_next_probe(u32 key)13300 static inline u32 kvm_async_pf_next_probe(u32 key)
13301 {
13302 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13303 }
13304 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13305 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13306 {
13307 	u32 key = kvm_async_pf_hash_fn(gfn);
13308 
13309 	while (vcpu->arch.apf.gfns[key] != ~0)
13310 		key = kvm_async_pf_next_probe(key);
13311 
13312 	vcpu->arch.apf.gfns[key] = gfn;
13313 }
13314 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13315 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13316 {
13317 	int i;
13318 	u32 key = kvm_async_pf_hash_fn(gfn);
13319 
13320 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
13321 		     (vcpu->arch.apf.gfns[key] != gfn &&
13322 		      vcpu->arch.apf.gfns[key] != ~0); i++)
13323 		key = kvm_async_pf_next_probe(key);
13324 
13325 	return key;
13326 }
13327 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13328 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13329 {
13330 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13331 }
13332 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13333 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13334 {
13335 	u32 i, j, k;
13336 
13337 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13338 
13339 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13340 		return;
13341 
13342 	while (true) {
13343 		vcpu->arch.apf.gfns[i] = ~0;
13344 		do {
13345 			j = kvm_async_pf_next_probe(j);
13346 			if (vcpu->arch.apf.gfns[j] == ~0)
13347 				return;
13348 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13349 			/*
13350 			 * k lies cyclically in ]i,j]
13351 			 * |    i.k.j |
13352 			 * |....j i.k.| or  |.k..j i...|
13353 			 */
13354 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13355 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13356 		i = j;
13357 	}
13358 }
13359 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13360 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13361 {
13362 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13363 
13364 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13365 				      sizeof(reason));
13366 }
13367 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13368 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13369 {
13370 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13371 
13372 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13373 					     &token, offset, sizeof(token));
13374 }
13375 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13376 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13377 {
13378 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13379 	u32 val;
13380 
13381 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13382 					 &val, offset, sizeof(val)))
13383 		return false;
13384 
13385 	return !val;
13386 }
13387 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13388 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13389 {
13390 
13391 	if (!kvm_pv_async_pf_enabled(vcpu))
13392 		return false;
13393 
13394 	if (!vcpu->arch.apf.send_always &&
13395 	    (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13396 		return false;
13397 
13398 	if (is_guest_mode(vcpu)) {
13399 		/*
13400 		 * L1 needs to opt into the special #PF vmexits that are
13401 		 * used to deliver async page faults.
13402 		 */
13403 		return vcpu->arch.apf.delivery_as_pf_vmexit;
13404 	} else {
13405 		/*
13406 		 * Play it safe in case the guest temporarily disables paging.
13407 		 * The real mode IDT in particular is unlikely to have a #PF
13408 		 * exception setup.
13409 		 */
13410 		return is_paging(vcpu);
13411 	}
13412 }
13413 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13414 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13415 {
13416 	if (unlikely(!lapic_in_kernel(vcpu) ||
13417 		     kvm_event_needs_reinjection(vcpu) ||
13418 		     kvm_is_exception_pending(vcpu)))
13419 		return false;
13420 
13421 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13422 		return false;
13423 
13424 	/*
13425 	 * If interrupts are off we cannot even use an artificial
13426 	 * halt state.
13427 	 */
13428 	return kvm_arch_interrupt_allowed(vcpu);
13429 }
13430 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13431 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13432 				     struct kvm_async_pf *work)
13433 {
13434 	struct x86_exception fault;
13435 
13436 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13437 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13438 
13439 	if (kvm_can_deliver_async_pf(vcpu) &&
13440 	    !apf_put_user_notpresent(vcpu)) {
13441 		fault.vector = PF_VECTOR;
13442 		fault.error_code_valid = true;
13443 		fault.error_code = 0;
13444 		fault.nested_page_fault = false;
13445 		fault.address = work->arch.token;
13446 		fault.async_page_fault = true;
13447 		kvm_inject_page_fault(vcpu, &fault);
13448 		return true;
13449 	} else {
13450 		/*
13451 		 * It is not possible to deliver a paravirtualized asynchronous
13452 		 * page fault, but putting the guest in an artificial halt state
13453 		 * can be beneficial nevertheless: if an interrupt arrives, we
13454 		 * can deliver it timely and perhaps the guest will schedule
13455 		 * another process.  When the instruction that triggered a page
13456 		 * fault is retried, hopefully the page will be ready in the host.
13457 		 */
13458 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13459 		return false;
13460 	}
13461 }
13462 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13463 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13464 				 struct kvm_async_pf *work)
13465 {
13466 	struct kvm_lapic_irq irq = {
13467 		.delivery_mode = APIC_DM_FIXED,
13468 		.vector = vcpu->arch.apf.vec
13469 	};
13470 
13471 	if (work->wakeup_all)
13472 		work->arch.token = ~0; /* broadcast wakeup */
13473 	else
13474 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13475 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13476 
13477 	if ((work->wakeup_all || work->notpresent_injected) &&
13478 	    kvm_pv_async_pf_enabled(vcpu) &&
13479 	    !apf_put_user_ready(vcpu, work->arch.token)) {
13480 		vcpu->arch.apf.pageready_pending = true;
13481 		kvm_apic_set_irq(vcpu, &irq, NULL);
13482 	}
13483 
13484 	vcpu->arch.apf.halted = false;
13485 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13486 }
13487 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13488 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13489 {
13490 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
13491 	if (!vcpu->arch.apf.pageready_pending)
13492 		kvm_vcpu_kick(vcpu);
13493 }
13494 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13495 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13496 {
13497 	if (!kvm_pv_async_pf_enabled(vcpu))
13498 		return true;
13499 	else
13500 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13501 }
13502 
kvm_arch_start_assignment(struct kvm * kvm)13503 void kvm_arch_start_assignment(struct kvm *kvm)
13504 {
13505 	if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13506 		kvm_x86_call(pi_start_assignment)(kvm);
13507 }
13508 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13509 
kvm_arch_end_assignment(struct kvm * kvm)13510 void kvm_arch_end_assignment(struct kvm *kvm)
13511 {
13512 	atomic_dec(&kvm->arch.assigned_device_count);
13513 }
13514 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13515 
kvm_arch_has_assigned_device(struct kvm * kvm)13516 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13517 {
13518 	return raw_atomic_read(&kvm->arch.assigned_device_count);
13519 }
13520 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13521 
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13522 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13523 {
13524 	/*
13525 	 * Non-coherent DMA assignment and de-assignment may affect whether or
13526 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13527 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
13528 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
13529 	 * with the correct "ignore guest PAT" setting are created.
13530 	 */
13531 	if (kvm_mmu_may_ignore_guest_pat())
13532 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13533 }
13534 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13535 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13536 {
13537 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13538 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13539 }
13540 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13541 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13542 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13543 {
13544 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13545 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13546 }
13547 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13548 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13549 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13550 {
13551 	return atomic_read(&kvm->arch.noncoherent_dma_count);
13552 }
13553 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13554 
kvm_arch_has_irq_bypass(void)13555 bool kvm_arch_has_irq_bypass(void)
13556 {
13557 	return enable_apicv && irq_remapping_cap(IRQ_POSTING_CAP);
13558 }
13559 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13560 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13561 				      struct irq_bypass_producer *prod)
13562 {
13563 	struct kvm_kernel_irqfd *irqfd =
13564 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13565 	int ret;
13566 
13567 	irqfd->producer = prod;
13568 	kvm_arch_start_assignment(irqfd->kvm);
13569 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13570 					   prod->irq, irqfd->gsi, 1);
13571 	if (ret)
13572 		kvm_arch_end_assignment(irqfd->kvm);
13573 
13574 	return ret;
13575 }
13576 
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13577 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13578 				      struct irq_bypass_producer *prod)
13579 {
13580 	int ret;
13581 	struct kvm_kernel_irqfd *irqfd =
13582 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13583 
13584 	WARN_ON(irqfd->producer != prod);
13585 	irqfd->producer = NULL;
13586 
13587 	/*
13588 	 * When producer of consumer is unregistered, we change back to
13589 	 * remapped mode, so we can re-use the current implementation
13590 	 * when the irq is masked/disabled or the consumer side (KVM
13591 	 * int this case doesn't want to receive the interrupts.
13592 	*/
13593 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13594 					   prod->irq, irqfd->gsi, 0);
13595 	if (ret)
13596 		printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13597 		       " fails: %d\n", irqfd->consumer.token, ret);
13598 
13599 	kvm_arch_end_assignment(irqfd->kvm);
13600 }
13601 
kvm_arch_update_irqfd_routing(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)13602 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13603 				   uint32_t guest_irq, bool set)
13604 {
13605 	return kvm_x86_call(pi_update_irte)(kvm, host_irq, guest_irq, set);
13606 }
13607 
kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)13608 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13609 				  struct kvm_kernel_irq_routing_entry *new)
13610 {
13611 	if (new->type != KVM_IRQ_ROUTING_MSI)
13612 		return true;
13613 
13614 	return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13615 }
13616 
kvm_vector_hashing_enabled(void)13617 bool kvm_vector_hashing_enabled(void)
13618 {
13619 	return vector_hashing;
13620 }
13621 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13622 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13623 {
13624 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13625 }
13626 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13627 
13628 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13629 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13630 {
13631 	return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13632 }
13633 #endif
13634 
13635 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13636 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13637 {
13638 	kvm_x86_call(gmem_invalidate)(start, end);
13639 }
13640 #endif
13641 
kvm_spec_ctrl_test_value(u64 value)13642 int kvm_spec_ctrl_test_value(u64 value)
13643 {
13644 	/*
13645 	 * test that setting IA32_SPEC_CTRL to given value
13646 	 * is allowed by the host processor
13647 	 */
13648 
13649 	u64 saved_value;
13650 	unsigned long flags;
13651 	int ret = 0;
13652 
13653 	local_irq_save(flags);
13654 
13655 	if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13656 		ret = 1;
13657 	else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13658 		ret = 1;
13659 	else
13660 		wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13661 
13662 	local_irq_restore(flags);
13663 
13664 	return ret;
13665 }
13666 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13667 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)13668 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13669 {
13670 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13671 	struct x86_exception fault;
13672 	u64 access = error_code &
13673 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13674 
13675 	if (!(error_code & PFERR_PRESENT_MASK) ||
13676 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13677 		/*
13678 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13679 		 * tables probably do not match the TLB.  Just proceed
13680 		 * with the error code that the processor gave.
13681 		 */
13682 		fault.vector = PF_VECTOR;
13683 		fault.error_code_valid = true;
13684 		fault.error_code = error_code;
13685 		fault.nested_page_fault = false;
13686 		fault.address = gva;
13687 		fault.async_page_fault = false;
13688 	}
13689 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13690 }
13691 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13692 
13693 /*
13694  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13695  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13696  * indicates whether exit to userspace is needed.
13697  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)13698 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13699 			      struct x86_exception *e)
13700 {
13701 	if (r == X86EMUL_PROPAGATE_FAULT) {
13702 		if (KVM_BUG_ON(!e, vcpu->kvm))
13703 			return -EIO;
13704 
13705 		kvm_inject_emulated_page_fault(vcpu, e);
13706 		return 1;
13707 	}
13708 
13709 	/*
13710 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13711 	 * while handling a VMX instruction KVM could've handled the request
13712 	 * correctly by exiting to userspace and performing I/O but there
13713 	 * doesn't seem to be a real use-case behind such requests, just return
13714 	 * KVM_EXIT_INTERNAL_ERROR for now.
13715 	 */
13716 	kvm_prepare_emulation_failure_exit(vcpu);
13717 
13718 	return 0;
13719 }
13720 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13721 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)13722 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13723 {
13724 	bool pcid_enabled;
13725 	struct x86_exception e;
13726 	struct {
13727 		u64 pcid;
13728 		u64 gla;
13729 	} operand;
13730 	int r;
13731 
13732 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13733 	if (r != X86EMUL_CONTINUE)
13734 		return kvm_handle_memory_failure(vcpu, r, &e);
13735 
13736 	if (operand.pcid >> 12 != 0) {
13737 		kvm_inject_gp(vcpu, 0);
13738 		return 1;
13739 	}
13740 
13741 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
13742 
13743 	switch (type) {
13744 	case INVPCID_TYPE_INDIV_ADDR:
13745 		/*
13746 		 * LAM doesn't apply to addresses that are inputs to TLB
13747 		 * invalidation.
13748 		 */
13749 		if ((!pcid_enabled && (operand.pcid != 0)) ||
13750 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
13751 			kvm_inject_gp(vcpu, 0);
13752 			return 1;
13753 		}
13754 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13755 		return kvm_skip_emulated_instruction(vcpu);
13756 
13757 	case INVPCID_TYPE_SINGLE_CTXT:
13758 		if (!pcid_enabled && (operand.pcid != 0)) {
13759 			kvm_inject_gp(vcpu, 0);
13760 			return 1;
13761 		}
13762 
13763 		kvm_invalidate_pcid(vcpu, operand.pcid);
13764 		return kvm_skip_emulated_instruction(vcpu);
13765 
13766 	case INVPCID_TYPE_ALL_NON_GLOBAL:
13767 		/*
13768 		 * Currently, KVM doesn't mark global entries in the shadow
13769 		 * page tables, so a non-global flush just degenerates to a
13770 		 * global flush. If needed, we could optimize this later by
13771 		 * keeping track of global entries in shadow page tables.
13772 		 */
13773 
13774 		fallthrough;
13775 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
13776 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13777 		return kvm_skip_emulated_instruction(vcpu);
13778 
13779 	default:
13780 		kvm_inject_gp(vcpu, 0);
13781 		return 1;
13782 	}
13783 }
13784 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13785 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)13786 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13787 {
13788 	struct kvm_run *run = vcpu->run;
13789 	struct kvm_mmio_fragment *frag;
13790 	unsigned int len;
13791 
13792 	BUG_ON(!vcpu->mmio_needed);
13793 
13794 	/* Complete previous fragment */
13795 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13796 	len = min(8u, frag->len);
13797 	if (!vcpu->mmio_is_write)
13798 		memcpy(frag->data, run->mmio.data, len);
13799 
13800 	if (frag->len <= 8) {
13801 		/* Switch to the next fragment. */
13802 		frag++;
13803 		vcpu->mmio_cur_fragment++;
13804 	} else {
13805 		/* Go forward to the next mmio piece. */
13806 		frag->data += len;
13807 		frag->gpa += len;
13808 		frag->len -= len;
13809 	}
13810 
13811 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13812 		vcpu->mmio_needed = 0;
13813 
13814 		// VMG change, at this point, we're always done
13815 		// RIP has already been advanced
13816 		return 1;
13817 	}
13818 
13819 	// More MMIO is needed
13820 	run->mmio.phys_addr = frag->gpa;
13821 	run->mmio.len = min(8u, frag->len);
13822 	run->mmio.is_write = vcpu->mmio_is_write;
13823 	if (run->mmio.is_write)
13824 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13825 	run->exit_reason = KVM_EXIT_MMIO;
13826 
13827 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13828 
13829 	return 0;
13830 }
13831 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13832 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13833 			  void *data)
13834 {
13835 	int handled;
13836 	struct kvm_mmio_fragment *frag;
13837 
13838 	if (!data)
13839 		return -EINVAL;
13840 
13841 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13842 	if (handled == bytes)
13843 		return 1;
13844 
13845 	bytes -= handled;
13846 	gpa += handled;
13847 	data += handled;
13848 
13849 	/*TODO: Check if need to increment number of frags */
13850 	frag = vcpu->mmio_fragments;
13851 	vcpu->mmio_nr_fragments = 1;
13852 	frag->len = bytes;
13853 	frag->gpa = gpa;
13854 	frag->data = data;
13855 
13856 	vcpu->mmio_needed = 1;
13857 	vcpu->mmio_cur_fragment = 0;
13858 
13859 	vcpu->run->mmio.phys_addr = gpa;
13860 	vcpu->run->mmio.len = min(8u, frag->len);
13861 	vcpu->run->mmio.is_write = 1;
13862 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13863 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13864 
13865 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13866 
13867 	return 0;
13868 }
13869 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13870 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13871 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13872 			 void *data)
13873 {
13874 	int handled;
13875 	struct kvm_mmio_fragment *frag;
13876 
13877 	if (!data)
13878 		return -EINVAL;
13879 
13880 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13881 	if (handled == bytes)
13882 		return 1;
13883 
13884 	bytes -= handled;
13885 	gpa += handled;
13886 	data += handled;
13887 
13888 	/*TODO: Check if need to increment number of frags */
13889 	frag = vcpu->mmio_fragments;
13890 	vcpu->mmio_nr_fragments = 1;
13891 	frag->len = bytes;
13892 	frag->gpa = gpa;
13893 	frag->data = data;
13894 
13895 	vcpu->mmio_needed = 1;
13896 	vcpu->mmio_cur_fragment = 0;
13897 
13898 	vcpu->run->mmio.phys_addr = gpa;
13899 	vcpu->run->mmio.len = min(8u, frag->len);
13900 	vcpu->run->mmio.is_write = 0;
13901 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13902 
13903 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13904 
13905 	return 0;
13906 }
13907 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13908 
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)13909 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13910 {
13911 	vcpu->arch.sev_pio_count -= count;
13912 	vcpu->arch.sev_pio_data += count * size;
13913 }
13914 
13915 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13916 			   unsigned int port);
13917 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)13918 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13919 {
13920 	int size = vcpu->arch.pio.size;
13921 	int port = vcpu->arch.pio.port;
13922 
13923 	vcpu->arch.pio.count = 0;
13924 	if (vcpu->arch.sev_pio_count)
13925 		return kvm_sev_es_outs(vcpu, size, port);
13926 	return 1;
13927 }
13928 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13929 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13930 			   unsigned int port)
13931 {
13932 	for (;;) {
13933 		unsigned int count =
13934 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13935 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13936 
13937 		/* memcpy done already by emulator_pio_out.  */
13938 		advance_sev_es_emulated_pio(vcpu, count, size);
13939 		if (!ret)
13940 			break;
13941 
13942 		/* Emulation done by the kernel.  */
13943 		if (!vcpu->arch.sev_pio_count)
13944 			return 1;
13945 	}
13946 
13947 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13948 	return 0;
13949 }
13950 
13951 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13952 			  unsigned int port);
13953 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)13954 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13955 {
13956 	unsigned count = vcpu->arch.pio.count;
13957 	int size = vcpu->arch.pio.size;
13958 	int port = vcpu->arch.pio.port;
13959 
13960 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13961 	advance_sev_es_emulated_pio(vcpu, count, size);
13962 	if (vcpu->arch.sev_pio_count)
13963 		return kvm_sev_es_ins(vcpu, size, port);
13964 	return 1;
13965 }
13966 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13967 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13968 			  unsigned int port)
13969 {
13970 	for (;;) {
13971 		unsigned int count =
13972 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13973 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
13974 			break;
13975 
13976 		/* Emulation done by the kernel.  */
13977 		advance_sev_es_emulated_pio(vcpu, count, size);
13978 		if (!vcpu->arch.sev_pio_count)
13979 			return 1;
13980 	}
13981 
13982 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13983 	return 0;
13984 }
13985 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)13986 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13987 			 unsigned int port, void *data,  unsigned int count,
13988 			 int in)
13989 {
13990 	vcpu->arch.sev_pio_data = data;
13991 	vcpu->arch.sev_pio_count = count;
13992 	return in ? kvm_sev_es_ins(vcpu, size, port)
13993 		  : kvm_sev_es_outs(vcpu, size, port);
13994 }
13995 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13996 
13997 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
13998 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
13999 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14000 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14001 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14002 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14003 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14004 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14005 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14006 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14007 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14008 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14009 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14010 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14011 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14012 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14013 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14014 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14015 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
14016 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14017 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14018 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14019 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14020 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14021 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14022 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14023 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14024 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14025 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14026 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14027 
kvm_x86_init(void)14028 static int __init kvm_x86_init(void)
14029 {
14030 	kvm_init_xstate_sizes();
14031 
14032 	kvm_mmu_x86_module_init();
14033 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14034 	return 0;
14035 }
14036 module_init(kvm_x86_init);
14037 
kvm_x86_exit(void)14038 static void __exit kvm_x86_exit(void)
14039 {
14040 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14041 }
14042 module_exit(kvm_x86_exit);
14043