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 | ARCH_CAP_ITS_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 	if (!boot_cpu_has_bug(X86_BUG_ITS))
1622 		data |= ARCH_CAP_ITS_NO;
1623 
1624 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1625 		/*
1626 		 * If RTM=0 because the kernel has disabled TSX, the host might
1627 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1628 		 * and therefore knows that there cannot be TAA) but keep
1629 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1630 		 * and we want to allow migrating those guests to tsx=off hosts.
1631 		 */
1632 		data &= ~ARCH_CAP_TAA_NO;
1633 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1634 		data |= ARCH_CAP_TAA_NO;
1635 	} else {
1636 		/*
1637 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1638 		 * host so the guest can choose between disabling TSX or
1639 		 * using VERW to clear CPU buffers.
1640 		 */
1641 	}
1642 
1643 	if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1644 		data |= ARCH_CAP_GDS_NO;
1645 
1646 	return data;
1647 }
1648 
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1649 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1650 			       bool host_initiated)
1651 {
1652 	WARN_ON_ONCE(!host_initiated);
1653 
1654 	switch (index) {
1655 	case MSR_IA32_ARCH_CAPABILITIES:
1656 		*data = kvm_get_arch_capabilities();
1657 		break;
1658 	case MSR_IA32_PERF_CAPABILITIES:
1659 		*data = kvm_caps.supported_perf_cap;
1660 		break;
1661 	case MSR_PLATFORM_INFO:
1662 		*data = MSR_PLATFORM_INFO_CPUID_FAULT;
1663 		break;
1664 	case MSR_IA32_UCODE_REV:
1665 		rdmsrl_safe(index, data);
1666 		break;
1667 	default:
1668 		return kvm_x86_call(get_feature_msr)(index, data);
1669 	}
1670 	return 0;
1671 }
1672 
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1673 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1674 {
1675 	return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1676 				 kvm_get_feature_msr);
1677 }
1678 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1679 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1680 {
1681 	if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1682 		return false;
1683 
1684 	if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1685 		return false;
1686 
1687 	if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1688 		return false;
1689 
1690 	if (efer & (EFER_LME | EFER_LMA) &&
1691 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1692 		return false;
1693 
1694 	if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1695 		return false;
1696 
1697 	return true;
1698 
1699 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1700 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1701 {
1702 	if (efer & efer_reserved_bits)
1703 		return false;
1704 
1705 	return __kvm_valid_efer(vcpu, efer);
1706 }
1707 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1708 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1709 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1710 {
1711 	u64 old_efer = vcpu->arch.efer;
1712 	u64 efer = msr_info->data;
1713 	int r;
1714 
1715 	if (efer & efer_reserved_bits)
1716 		return 1;
1717 
1718 	if (!msr_info->host_initiated) {
1719 		if (!__kvm_valid_efer(vcpu, efer))
1720 			return 1;
1721 
1722 		if (is_paging(vcpu) &&
1723 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1724 			return 1;
1725 	}
1726 
1727 	efer &= ~EFER_LMA;
1728 	efer |= vcpu->arch.efer & EFER_LMA;
1729 
1730 	r = kvm_x86_call(set_efer)(vcpu, efer);
1731 	if (r) {
1732 		WARN_ON(r > 0);
1733 		return r;
1734 	}
1735 
1736 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1737 		kvm_mmu_reset_context(vcpu);
1738 
1739 	if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1740 	    (efer & EFER_SVME))
1741 		kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1742 
1743 	return 0;
1744 }
1745 
kvm_enable_efer_bits(u64 mask)1746 void kvm_enable_efer_bits(u64 mask)
1747 {
1748        efer_reserved_bits &= ~mask;
1749 }
1750 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1751 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1752 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1753 {
1754 	struct kvm_x86_msr_filter *msr_filter;
1755 	struct msr_bitmap_range *ranges;
1756 	struct kvm *kvm = vcpu->kvm;
1757 	bool allowed;
1758 	int idx;
1759 	u32 i;
1760 
1761 	/* x2APIC MSRs do not support filtering. */
1762 	if (index >= 0x800 && index <= 0x8ff)
1763 		return true;
1764 
1765 	idx = srcu_read_lock(&kvm->srcu);
1766 
1767 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1768 	if (!msr_filter) {
1769 		allowed = true;
1770 		goto out;
1771 	}
1772 
1773 	allowed = msr_filter->default_allow;
1774 	ranges = msr_filter->ranges;
1775 
1776 	for (i = 0; i < msr_filter->count; i++) {
1777 		u32 start = ranges[i].base;
1778 		u32 end = start + ranges[i].nmsrs;
1779 		u32 flags = ranges[i].flags;
1780 		unsigned long *bitmap = ranges[i].bitmap;
1781 
1782 		if ((index >= start) && (index < end) && (flags & type)) {
1783 			allowed = test_bit(index - start, bitmap);
1784 			break;
1785 		}
1786 	}
1787 
1788 out:
1789 	srcu_read_unlock(&kvm->srcu, idx);
1790 
1791 	return allowed;
1792 }
1793 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1794 
1795 /*
1796  * Write @data into the MSR specified by @index.  Select MSR specific fault
1797  * checks are bypassed if @host_initiated is %true.
1798  * Returns 0 on success, non-0 otherwise.
1799  * Assumes vcpu_load() was already called.
1800  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1801 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1802 			 bool host_initiated)
1803 {
1804 	struct msr_data msr;
1805 
1806 	switch (index) {
1807 	case MSR_FS_BASE:
1808 	case MSR_GS_BASE:
1809 	case MSR_KERNEL_GS_BASE:
1810 	case MSR_CSTAR:
1811 	case MSR_LSTAR:
1812 		if (is_noncanonical_msr_address(data, vcpu))
1813 			return 1;
1814 		break;
1815 	case MSR_IA32_SYSENTER_EIP:
1816 	case MSR_IA32_SYSENTER_ESP:
1817 		/*
1818 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1819 		 * non-canonical address is written on Intel but not on
1820 		 * AMD (which ignores the top 32-bits, because it does
1821 		 * not implement 64-bit SYSENTER).
1822 		 *
1823 		 * 64-bit code should hence be able to write a non-canonical
1824 		 * value on AMD.  Making the address canonical ensures that
1825 		 * vmentry does not fail on Intel after writing a non-canonical
1826 		 * value, and that something deterministic happens if the guest
1827 		 * invokes 64-bit SYSENTER.
1828 		 */
1829 		data = __canonical_address(data, max_host_virt_addr_bits());
1830 		break;
1831 	case MSR_TSC_AUX:
1832 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1833 			return 1;
1834 
1835 		if (!host_initiated &&
1836 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1837 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1838 			return 1;
1839 
1840 		/*
1841 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1842 		 * incomplete and conflicting architectural behavior.  Current
1843 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1844 		 * reserved and always read as zeros.  Enforce Intel's reserved
1845 		 * bits check if the guest CPU is Intel compatible, otherwise
1846 		 * clear the bits.  This ensures cross-vendor migration will
1847 		 * provide consistent behavior for the guest.
1848 		 */
1849 		if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1850 			return 1;
1851 
1852 		data = (u32)data;
1853 		break;
1854 	}
1855 
1856 	msr.data = data;
1857 	msr.index = index;
1858 	msr.host_initiated = host_initiated;
1859 
1860 	return kvm_x86_call(set_msr)(vcpu, &msr);
1861 }
1862 
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1863 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1864 			bool host_initiated)
1865 {
1866 	return __kvm_set_msr(vcpu, index, *data, host_initiated);
1867 }
1868 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1869 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1870 				     u32 index, u64 data, bool host_initiated)
1871 {
1872 	return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1873 				 _kvm_set_msr);
1874 }
1875 
1876 /*
1877  * Read the MSR specified by @index into @data.  Select MSR specific fault
1878  * checks are bypassed if @host_initiated is %true.
1879  * Returns 0 on success, non-0 otherwise.
1880  * Assumes vcpu_load() was already called.
1881  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1882 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1883 		  bool host_initiated)
1884 {
1885 	struct msr_data msr;
1886 	int ret;
1887 
1888 	switch (index) {
1889 	case MSR_TSC_AUX:
1890 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1891 			return 1;
1892 
1893 		if (!host_initiated &&
1894 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1895 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1896 			return 1;
1897 		break;
1898 	}
1899 
1900 	msr.index = index;
1901 	msr.host_initiated = host_initiated;
1902 
1903 	ret = kvm_x86_call(get_msr)(vcpu, &msr);
1904 	if (!ret)
1905 		*data = msr.data;
1906 	return ret;
1907 }
1908 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1909 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1910 				     u32 index, u64 *data, bool host_initiated)
1911 {
1912 	return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
1913 				 __kvm_get_msr);
1914 }
1915 
kvm_get_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 * data)1916 int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1917 {
1918 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1919 		return KVM_MSR_RET_FILTERED;
1920 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1921 }
1922 EXPORT_SYMBOL_GPL(kvm_get_msr_with_filter);
1923 
kvm_set_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 data)1924 int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1925 {
1926 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1927 		return KVM_MSR_RET_FILTERED;
1928 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1929 }
1930 EXPORT_SYMBOL_GPL(kvm_set_msr_with_filter);
1931 
kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data)1932 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1933 {
1934 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1935 }
1936 EXPORT_SYMBOL_GPL(kvm_get_msr);
1937 
kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data)1938 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1939 {
1940 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1941 }
1942 EXPORT_SYMBOL_GPL(kvm_set_msr);
1943 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)1944 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1945 {
1946 	if (!vcpu->run->msr.error) {
1947 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1948 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1949 	}
1950 }
1951 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)1952 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1953 {
1954 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1955 }
1956 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)1957 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1958 {
1959 	complete_userspace_rdmsr(vcpu);
1960 	return complete_emulated_msr_access(vcpu);
1961 }
1962 
complete_fast_msr_access(struct kvm_vcpu * vcpu)1963 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1964 {
1965 	return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1966 }
1967 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)1968 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1969 {
1970 	complete_userspace_rdmsr(vcpu);
1971 	return complete_fast_msr_access(vcpu);
1972 }
1973 
kvm_msr_reason(int r)1974 static u64 kvm_msr_reason(int r)
1975 {
1976 	switch (r) {
1977 	case KVM_MSR_RET_UNSUPPORTED:
1978 		return KVM_MSR_EXIT_REASON_UNKNOWN;
1979 	case KVM_MSR_RET_FILTERED:
1980 		return KVM_MSR_EXIT_REASON_FILTER;
1981 	default:
1982 		return KVM_MSR_EXIT_REASON_INVAL;
1983 	}
1984 }
1985 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)1986 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1987 			      u32 exit_reason, u64 data,
1988 			      int (*completion)(struct kvm_vcpu *vcpu),
1989 			      int r)
1990 {
1991 	u64 msr_reason = kvm_msr_reason(r);
1992 
1993 	/* Check if the user wanted to know about this MSR fault */
1994 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1995 		return 0;
1996 
1997 	vcpu->run->exit_reason = exit_reason;
1998 	vcpu->run->msr.error = 0;
1999 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2000 	vcpu->run->msr.reason = msr_reason;
2001 	vcpu->run->msr.index = index;
2002 	vcpu->run->msr.data = data;
2003 	vcpu->arch.complete_userspace_io = completion;
2004 
2005 	return 1;
2006 }
2007 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2008 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2009 {
2010 	u32 ecx = kvm_rcx_read(vcpu);
2011 	u64 data;
2012 	int r;
2013 
2014 	r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2015 
2016 	if (!r) {
2017 		trace_kvm_msr_read(ecx, data);
2018 
2019 		kvm_rax_write(vcpu, data & -1u);
2020 		kvm_rdx_write(vcpu, (data >> 32) & -1u);
2021 	} else {
2022 		/* MSR read failed? See if we should ask user space */
2023 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2024 				       complete_fast_rdmsr, r))
2025 			return 0;
2026 		trace_kvm_msr_read_ex(ecx);
2027 	}
2028 
2029 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2030 }
2031 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2032 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2033 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2034 {
2035 	u32 ecx = kvm_rcx_read(vcpu);
2036 	u64 data = kvm_read_edx_eax(vcpu);
2037 	int r;
2038 
2039 	r = kvm_set_msr_with_filter(vcpu, ecx, data);
2040 
2041 	if (!r) {
2042 		trace_kvm_msr_write(ecx, data);
2043 	} else {
2044 		/* MSR write failed? See if we should ask user space */
2045 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2046 				       complete_fast_msr_access, r))
2047 			return 0;
2048 		/* Signal all other negative errors to userspace */
2049 		if (r < 0)
2050 			return r;
2051 		trace_kvm_msr_write_ex(ecx, data);
2052 	}
2053 
2054 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2055 }
2056 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2057 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2058 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2059 {
2060 	return kvm_skip_emulated_instruction(vcpu);
2061 }
2062 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2063 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2064 {
2065 	/* Treat an INVD instruction as a NOP and just skip it. */
2066 	return kvm_emulate_as_nop(vcpu);
2067 }
2068 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2069 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2070 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2071 {
2072 	kvm_queue_exception(vcpu, UD_VECTOR);
2073 	return 1;
2074 }
2075 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2076 
2077 
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2078 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2079 {
2080 	bool enabled;
2081 
2082 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2083 		goto emulate_as_nop;
2084 
2085 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2086 		enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2087 	else
2088 		enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2089 
2090 	if (!enabled)
2091 		return kvm_handle_invalid_op(vcpu);
2092 
2093 emulate_as_nop:
2094 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
2095 	return kvm_emulate_as_nop(vcpu);
2096 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2097 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2098 {
2099 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2100 }
2101 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2102 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2103 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2104 {
2105 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2106 }
2107 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2108 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2109 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2110 {
2111 	xfer_to_guest_mode_prepare();
2112 
2113 	return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2114 	       kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2115 }
2116 
2117 /*
2118  * The fast path for frequent and performance sensitive wrmsr emulation,
2119  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2120  * the latency of virtual IPI by avoiding the expensive bits of transitioning
2121  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2122  * other cases which must be called after interrupts are enabled on the host.
2123  */
handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu * vcpu,u64 data)2124 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2125 {
2126 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2127 		return 1;
2128 
2129 	if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2130 	    ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2131 	    ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2132 	    ((u32)(data >> 32) != X2APIC_BROADCAST))
2133 		return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2134 
2135 	return 1;
2136 }
2137 
handle_fastpath_set_tscdeadline(struct kvm_vcpu * vcpu,u64 data)2138 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2139 {
2140 	if (!kvm_can_use_hv_timer(vcpu))
2141 		return 1;
2142 
2143 	kvm_set_lapic_tscdeadline_msr(vcpu, data);
2144 	return 0;
2145 }
2146 
handle_fastpath_set_msr_irqoff(struct kvm_vcpu * vcpu)2147 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2148 {
2149 	u32 msr = kvm_rcx_read(vcpu);
2150 	u64 data;
2151 	fastpath_t ret;
2152 	bool handled;
2153 
2154 	kvm_vcpu_srcu_read_lock(vcpu);
2155 
2156 	switch (msr) {
2157 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2158 		data = kvm_read_edx_eax(vcpu);
2159 		handled = !handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
2160 		break;
2161 	case MSR_IA32_TSC_DEADLINE:
2162 		data = kvm_read_edx_eax(vcpu);
2163 		handled = !handle_fastpath_set_tscdeadline(vcpu, data);
2164 		break;
2165 	default:
2166 		handled = false;
2167 		break;
2168 	}
2169 
2170 	if (handled) {
2171 		if (!kvm_skip_emulated_instruction(vcpu))
2172 			ret = EXIT_FASTPATH_EXIT_USERSPACE;
2173 		else
2174 			ret = EXIT_FASTPATH_REENTER_GUEST;
2175 		trace_kvm_msr_write(msr, data);
2176 	} else {
2177 		ret = EXIT_FASTPATH_NONE;
2178 	}
2179 
2180 	kvm_vcpu_srcu_read_unlock(vcpu);
2181 
2182 	return ret;
2183 }
2184 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2185 
2186 /*
2187  * Adapt set_msr() to msr_io()'s calling convention
2188  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2189 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2190 {
2191 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2192 }
2193 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2194 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2195 {
2196 	u64 val;
2197 
2198 	/*
2199 	 * Disallow writes to immutable feature MSRs after KVM_RUN.  KVM does
2200 	 * not support modifying the guest vCPU model on the fly, e.g. changing
2201 	 * the nVMX capabilities while L2 is running is nonsensical.  Allow
2202 	 * writes of the same value, e.g. to allow userspace to blindly stuff
2203 	 * all MSRs when emulating RESET.
2204 	 */
2205 	if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2206 	    (do_get_msr(vcpu, index, &val) || *data != val))
2207 		return -EINVAL;
2208 
2209 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2210 }
2211 
2212 #ifdef CONFIG_X86_64
2213 struct pvclock_clock {
2214 	int vclock_mode;
2215 	u64 cycle_last;
2216 	u64 mask;
2217 	u32 mult;
2218 	u32 shift;
2219 	u64 base_cycles;
2220 	u64 offset;
2221 };
2222 
2223 struct pvclock_gtod_data {
2224 	seqcount_t	seq;
2225 
2226 	struct pvclock_clock clock; /* extract of a clocksource struct */
2227 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2228 
2229 	ktime_t		offs_boot;
2230 	u64		wall_time_sec;
2231 };
2232 
2233 static struct pvclock_gtod_data pvclock_gtod_data;
2234 
update_pvclock_gtod(struct timekeeper * tk)2235 static void update_pvclock_gtod(struct timekeeper *tk)
2236 {
2237 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2238 
2239 	write_seqcount_begin(&vdata->seq);
2240 
2241 	/* copy pvclock gtod data */
2242 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2243 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2244 	vdata->clock.mask		= tk->tkr_mono.mask;
2245 	vdata->clock.mult		= tk->tkr_mono.mult;
2246 	vdata->clock.shift		= tk->tkr_mono.shift;
2247 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2248 	vdata->clock.offset		= tk->tkr_mono.base;
2249 
2250 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2251 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2252 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2253 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2254 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2255 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2256 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2257 
2258 	vdata->wall_time_sec            = tk->xtime_sec;
2259 
2260 	vdata->offs_boot		= tk->offs_boot;
2261 
2262 	write_seqcount_end(&vdata->seq);
2263 }
2264 
get_kvmclock_base_ns(void)2265 static s64 get_kvmclock_base_ns(void)
2266 {
2267 	/* Count up from boot time, but with the frequency of the raw clock.  */
2268 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2269 }
2270 #else
get_kvmclock_base_ns(void)2271 static s64 get_kvmclock_base_ns(void)
2272 {
2273 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2274 	return ktime_get_boottime_ns();
2275 }
2276 #endif
2277 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2278 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2279 {
2280 	int version;
2281 	int r;
2282 	struct pvclock_wall_clock wc;
2283 	u32 wc_sec_hi;
2284 	u64 wall_nsec;
2285 
2286 	if (!wall_clock)
2287 		return;
2288 
2289 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2290 	if (r)
2291 		return;
2292 
2293 	if (version & 1)
2294 		++version;  /* first time write, random junk */
2295 
2296 	++version;
2297 
2298 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2299 		return;
2300 
2301 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
2302 
2303 	wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2304 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2305 	wc.version = version;
2306 
2307 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2308 
2309 	if (sec_hi_ofs) {
2310 		wc_sec_hi = wall_nsec >> 32;
2311 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2312 				&wc_sec_hi, sizeof(wc_sec_hi));
2313 	}
2314 
2315 	version++;
2316 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2317 }
2318 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2319 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2320 				  bool old_msr, bool host_initiated)
2321 {
2322 	struct kvm_arch *ka = &vcpu->kvm->arch;
2323 
2324 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2325 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2326 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2327 
2328 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2329 	}
2330 
2331 	vcpu->arch.time = system_time;
2332 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2333 
2334 	/* we verify if the enable bit is set... */
2335 	if (system_time & 1)
2336 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2337 				 sizeof(struct pvclock_vcpu_time_info));
2338 	else
2339 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
2340 
2341 	return;
2342 }
2343 
div_frac(uint32_t dividend,uint32_t divisor)2344 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2345 {
2346 	do_shl32_div32(dividend, divisor);
2347 	return dividend;
2348 }
2349 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2350 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2351 			       s8 *pshift, u32 *pmultiplier)
2352 {
2353 	uint64_t scaled64;
2354 	int32_t  shift = 0;
2355 	uint64_t tps64;
2356 	uint32_t tps32;
2357 
2358 	tps64 = base_hz;
2359 	scaled64 = scaled_hz;
2360 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2361 		tps64 >>= 1;
2362 		shift--;
2363 	}
2364 
2365 	tps32 = (uint32_t)tps64;
2366 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2367 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2368 			scaled64 >>= 1;
2369 		else
2370 			tps32 <<= 1;
2371 		shift++;
2372 	}
2373 
2374 	*pshift = shift;
2375 	*pmultiplier = div_frac(scaled64, tps32);
2376 }
2377 
2378 #ifdef CONFIG_X86_64
2379 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2380 #endif
2381 
2382 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2383 static unsigned long max_tsc_khz;
2384 
adjust_tsc_khz(u32 khz,s32 ppm)2385 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2386 {
2387 	u64 v = (u64)khz * (1000000 + ppm);
2388 	do_div(v, 1000000);
2389 	return v;
2390 }
2391 
2392 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2393 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2394 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2395 {
2396 	u64 ratio;
2397 
2398 	/* Guest TSC same frequency as host TSC? */
2399 	if (!scale) {
2400 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2401 		return 0;
2402 	}
2403 
2404 	/* TSC scaling supported? */
2405 	if (!kvm_caps.has_tsc_control) {
2406 		if (user_tsc_khz > tsc_khz) {
2407 			vcpu->arch.tsc_catchup = 1;
2408 			vcpu->arch.tsc_always_catchup = 1;
2409 			return 0;
2410 		} else {
2411 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2412 			return -1;
2413 		}
2414 	}
2415 
2416 	/* TSC scaling required  - calculate ratio */
2417 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2418 				user_tsc_khz, tsc_khz);
2419 
2420 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2421 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2422 			            user_tsc_khz);
2423 		return -1;
2424 	}
2425 
2426 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2427 	return 0;
2428 }
2429 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2430 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2431 {
2432 	u32 thresh_lo, thresh_hi;
2433 	int use_scaling = 0;
2434 
2435 	/* tsc_khz can be zero if TSC calibration fails */
2436 	if (user_tsc_khz == 0) {
2437 		/* set tsc_scaling_ratio to a safe value */
2438 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2439 		return -1;
2440 	}
2441 
2442 	/* Compute a scale to convert nanoseconds in TSC cycles */
2443 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2444 			   &vcpu->arch.virtual_tsc_shift,
2445 			   &vcpu->arch.virtual_tsc_mult);
2446 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2447 
2448 	/*
2449 	 * Compute the variation in TSC rate which is acceptable
2450 	 * within the range of tolerance and decide if the
2451 	 * rate being applied is within that bounds of the hardware
2452 	 * rate.  If so, no scaling or compensation need be done.
2453 	 */
2454 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2455 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2456 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2457 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2458 			 user_tsc_khz, thresh_lo, thresh_hi);
2459 		use_scaling = 1;
2460 	}
2461 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2462 }
2463 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2464 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2465 {
2466 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2467 				      vcpu->arch.virtual_tsc_mult,
2468 				      vcpu->arch.virtual_tsc_shift);
2469 	tsc += vcpu->arch.this_tsc_write;
2470 	return tsc;
2471 }
2472 
2473 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2474 static inline bool gtod_is_based_on_tsc(int mode)
2475 {
2476 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2477 }
2478 #endif
2479 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2480 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2481 {
2482 #ifdef CONFIG_X86_64
2483 	struct kvm_arch *ka = &vcpu->kvm->arch;
2484 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2485 
2486 	/*
2487 	 * To use the masterclock, the host clocksource must be based on TSC
2488 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
2489 	 * vCPUs doesn't include the reference vCPU, hence "+1".
2490 	 */
2491 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2492 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
2493 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2494 
2495 	/*
2496 	 * Request a masterclock update if the masterclock needs to be toggled
2497 	 * on/off, or when starting a new generation and the masterclock is
2498 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2499 	 * taken _after_ the new generation is created).
2500 	 */
2501 	if ((ka->use_master_clock && new_generation) ||
2502 	    (ka->use_master_clock != use_master_clock))
2503 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2504 
2505 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2506 			    atomic_read(&vcpu->kvm->online_vcpus),
2507 		            ka->use_master_clock, gtod->clock.vclock_mode);
2508 #endif
2509 }
2510 
2511 /*
2512  * Multiply tsc by a fixed point number represented by ratio.
2513  *
2514  * The most significant 64-N bits (mult) of ratio represent the
2515  * integral part of the fixed point number; the remaining N bits
2516  * (frac) represent the fractional part, ie. ratio represents a fixed
2517  * point number (mult + frac * 2^(-N)).
2518  *
2519  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2520  */
__scale_tsc(u64 ratio,u64 tsc)2521 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2522 {
2523 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2524 }
2525 
kvm_scale_tsc(u64 tsc,u64 ratio)2526 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2527 {
2528 	u64 _tsc = tsc;
2529 
2530 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
2531 		_tsc = __scale_tsc(ratio, tsc);
2532 
2533 	return _tsc;
2534 }
2535 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2536 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2537 {
2538 	u64 tsc;
2539 
2540 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2541 
2542 	return target_tsc - tsc;
2543 }
2544 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2545 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2546 {
2547 	return vcpu->arch.l1_tsc_offset +
2548 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2549 }
2550 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2551 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2552 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2553 {
2554 	u64 nested_offset;
2555 
2556 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2557 		nested_offset = l1_offset;
2558 	else
2559 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2560 						kvm_caps.tsc_scaling_ratio_frac_bits);
2561 
2562 	nested_offset += l2_offset;
2563 	return nested_offset;
2564 }
2565 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2566 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2567 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2568 {
2569 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2570 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2571 				       kvm_caps.tsc_scaling_ratio_frac_bits);
2572 
2573 	return l1_multiplier;
2574 }
2575 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2576 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2577 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2578 {
2579 	if (vcpu->arch.guest_tsc_protected)
2580 		return;
2581 
2582 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2583 				   vcpu->arch.l1_tsc_offset,
2584 				   l1_offset);
2585 
2586 	vcpu->arch.l1_tsc_offset = l1_offset;
2587 
2588 	/*
2589 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2590 	 * according to the spec this should set L1's TSC (as opposed to
2591 	 * setting L1's offset for L2).
2592 	 */
2593 	if (is_guest_mode(vcpu))
2594 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2595 			l1_offset,
2596 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
2597 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2598 	else
2599 		vcpu->arch.tsc_offset = l1_offset;
2600 
2601 	kvm_x86_call(write_tsc_offset)(vcpu);
2602 }
2603 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2604 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2605 {
2606 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2607 
2608 	/* Userspace is changing the multiplier while L2 is active */
2609 	if (is_guest_mode(vcpu))
2610 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2611 			l1_multiplier,
2612 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2613 	else
2614 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2615 
2616 	if (kvm_caps.has_tsc_control)
2617 		kvm_x86_call(write_tsc_multiplier)(vcpu);
2618 }
2619 
kvm_check_tsc_unstable(void)2620 static inline bool kvm_check_tsc_unstable(void)
2621 {
2622 #ifdef CONFIG_X86_64
2623 	/*
2624 	 * TSC is marked unstable when we're running on Hyper-V,
2625 	 * 'TSC page' clocksource is good.
2626 	 */
2627 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2628 		return false;
2629 #endif
2630 	return check_tsc_unstable();
2631 }
2632 
2633 /*
2634  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2635  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2636  * participates in.
2637  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2638 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2639 				  u64 ns, bool matched, bool user_set_tsc)
2640 {
2641 	struct kvm *kvm = vcpu->kvm;
2642 
2643 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2644 
2645 	if (vcpu->arch.guest_tsc_protected)
2646 		return;
2647 
2648 	if (user_set_tsc)
2649 		vcpu->kvm->arch.user_set_tsc = true;
2650 
2651 	/*
2652 	 * We also track th most recent recorded KHZ, write and time to
2653 	 * allow the matching interval to be extended at each write.
2654 	 */
2655 	kvm->arch.last_tsc_nsec = ns;
2656 	kvm->arch.last_tsc_write = tsc;
2657 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2658 	kvm->arch.last_tsc_offset = offset;
2659 
2660 	vcpu->arch.last_guest_tsc = tsc;
2661 
2662 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2663 
2664 	if (!matched) {
2665 		/*
2666 		 * We split periods of matched TSC writes into generations.
2667 		 * For each generation, we track the original measured
2668 		 * nanosecond time, offset, and write, so if TSCs are in
2669 		 * sync, we can match exact offset, and if not, we can match
2670 		 * exact software computation in compute_guest_tsc()
2671 		 *
2672 		 * These values are tracked in kvm->arch.cur_xxx variables.
2673 		 */
2674 		kvm->arch.cur_tsc_generation++;
2675 		kvm->arch.cur_tsc_nsec = ns;
2676 		kvm->arch.cur_tsc_write = tsc;
2677 		kvm->arch.cur_tsc_offset = offset;
2678 		kvm->arch.nr_vcpus_matched_tsc = 0;
2679 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2680 		kvm->arch.nr_vcpus_matched_tsc++;
2681 	}
2682 
2683 	/* Keep track of which generation this VCPU has synchronized to */
2684 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2685 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2686 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2687 
2688 	kvm_track_tsc_matching(vcpu, !matched);
2689 }
2690 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2691 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2692 {
2693 	u64 data = user_value ? *user_value : 0;
2694 	struct kvm *kvm = vcpu->kvm;
2695 	u64 offset, ns, elapsed;
2696 	unsigned long flags;
2697 	bool matched = false;
2698 	bool synchronizing = false;
2699 
2700 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2701 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2702 	ns = get_kvmclock_base_ns();
2703 	elapsed = ns - kvm->arch.last_tsc_nsec;
2704 
2705 	if (vcpu->arch.virtual_tsc_khz) {
2706 		if (data == 0) {
2707 			/*
2708 			 * Force synchronization when creating a vCPU, or when
2709 			 * userspace explicitly writes a zero value.
2710 			 */
2711 			synchronizing = true;
2712 		} else if (kvm->arch.user_set_tsc) {
2713 			u64 tsc_exp = kvm->arch.last_tsc_write +
2714 						nsec_to_cycles(vcpu, elapsed);
2715 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2716 			/*
2717 			 * Here lies UAPI baggage: when a user-initiated TSC write has
2718 			 * a small delta (1 second) of virtual cycle time against the
2719 			 * previously set vCPU, we assume that they were intended to be
2720 			 * in sync and the delta was only due to the racy nature of the
2721 			 * legacy API.
2722 			 *
2723 			 * This trick falls down when restoring a guest which genuinely
2724 			 * has been running for less time than the 1 second of imprecision
2725 			 * which we allow for in the legacy API. In this case, the first
2726 			 * value written by userspace (on any vCPU) should not be subject
2727 			 * to this 'correction' to make it sync up with values that only
2728 			 * come from the kernel's default vCPU creation. Make the 1-second
2729 			 * slop hack only trigger if the user_set_tsc flag is already set.
2730 			 */
2731 			synchronizing = data < tsc_exp + tsc_hz &&
2732 					data + tsc_hz > tsc_exp;
2733 		}
2734 	}
2735 
2736 
2737 	/*
2738 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2739 	 * TSC, we add elapsed time in this computation.  We could let the
2740 	 * compensation code attempt to catch up if we fall behind, but
2741 	 * it's better to try to match offsets from the beginning.
2742          */
2743 	if (synchronizing &&
2744 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2745 		if (!kvm_check_tsc_unstable()) {
2746 			offset = kvm->arch.cur_tsc_offset;
2747 		} else {
2748 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2749 			data += delta;
2750 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2751 		}
2752 		matched = true;
2753 	}
2754 
2755 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2756 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2757 }
2758 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2759 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2760 					   s64 adjustment)
2761 {
2762 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2763 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2764 }
2765 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2766 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2767 {
2768 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2769 		WARN_ON(adjustment < 0);
2770 	adjustment = kvm_scale_tsc((u64) adjustment,
2771 				   vcpu->arch.l1_tsc_scaling_ratio);
2772 	adjust_tsc_offset_guest(vcpu, adjustment);
2773 }
2774 
2775 #ifdef CONFIG_X86_64
2776 
read_tsc(void)2777 static u64 read_tsc(void)
2778 {
2779 	u64 ret = (u64)rdtsc_ordered();
2780 	u64 last = pvclock_gtod_data.clock.cycle_last;
2781 
2782 	if (likely(ret >= last))
2783 		return ret;
2784 
2785 	/*
2786 	 * GCC likes to generate cmov here, but this branch is extremely
2787 	 * predictable (it's just a function of time and the likely is
2788 	 * very likely) and there's a data dependence, so force GCC
2789 	 * to generate a branch instead.  I don't barrier() because
2790 	 * we don't actually need a barrier, and if this function
2791 	 * ever gets inlined it will generate worse code.
2792 	 */
2793 	asm volatile ("");
2794 	return last;
2795 }
2796 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2797 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2798 			  int *mode)
2799 {
2800 	u64 tsc_pg_val;
2801 	long v;
2802 
2803 	switch (clock->vclock_mode) {
2804 	case VDSO_CLOCKMODE_HVCLOCK:
2805 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2806 					 tsc_timestamp, &tsc_pg_val)) {
2807 			/* TSC page valid */
2808 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2809 			v = (tsc_pg_val - clock->cycle_last) &
2810 				clock->mask;
2811 		} else {
2812 			/* TSC page invalid */
2813 			*mode = VDSO_CLOCKMODE_NONE;
2814 		}
2815 		break;
2816 	case VDSO_CLOCKMODE_TSC:
2817 		*mode = VDSO_CLOCKMODE_TSC;
2818 		*tsc_timestamp = read_tsc();
2819 		v = (*tsc_timestamp - clock->cycle_last) &
2820 			clock->mask;
2821 		break;
2822 	default:
2823 		*mode = VDSO_CLOCKMODE_NONE;
2824 	}
2825 
2826 	if (*mode == VDSO_CLOCKMODE_NONE)
2827 		*tsc_timestamp = v = 0;
2828 
2829 	return v * clock->mult;
2830 }
2831 
2832 /*
2833  * As with get_kvmclock_base_ns(), this counts from boot time, at the
2834  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2835  */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2836 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2837 {
2838 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2839 	unsigned long seq;
2840 	int mode;
2841 	u64 ns;
2842 
2843 	do {
2844 		seq = read_seqcount_begin(&gtod->seq);
2845 		ns = gtod->raw_clock.base_cycles;
2846 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2847 		ns >>= gtod->raw_clock.shift;
2848 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2849 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2850 	*t = ns;
2851 
2852 	return mode;
2853 }
2854 
2855 /*
2856  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2857  * no boot time offset.
2858  */
do_monotonic(s64 * t,u64 * tsc_timestamp)2859 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2860 {
2861 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2862 	unsigned long seq;
2863 	int mode;
2864 	u64 ns;
2865 
2866 	do {
2867 		seq = read_seqcount_begin(&gtod->seq);
2868 		ns = gtod->clock.base_cycles;
2869 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2870 		ns >>= gtod->clock.shift;
2871 		ns += ktime_to_ns(gtod->clock.offset);
2872 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2873 	*t = ns;
2874 
2875 	return mode;
2876 }
2877 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2878 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2879 {
2880 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2881 	unsigned long seq;
2882 	int mode;
2883 	u64 ns;
2884 
2885 	do {
2886 		seq = read_seqcount_begin(&gtod->seq);
2887 		ts->tv_sec = gtod->wall_time_sec;
2888 		ns = gtod->clock.base_cycles;
2889 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2890 		ns >>= gtod->clock.shift;
2891 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2892 
2893 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2894 	ts->tv_nsec = ns;
2895 
2896 	return mode;
2897 }
2898 
2899 /*
2900  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2901  * reports the TSC value from which it do so. Returns true if host is
2902  * using TSC based clocksource.
2903  */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2904 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2905 {
2906 	/* checked again under seqlock below */
2907 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2908 		return false;
2909 
2910 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2911 						     tsc_timestamp));
2912 }
2913 
2914 /*
2915  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2916  * so. Returns true if host is using TSC based clocksource.
2917  */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2918 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2919 {
2920 	/* checked again under seqlock below */
2921 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2922 		return false;
2923 
2924 	return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
2925 						 tsc_timestamp));
2926 }
2927 
2928 /*
2929  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2930  * so. Returns true if host is using TSC based clocksource.
2931  *
2932  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2933  * for that.
2934  */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)2935 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2936 					   u64 *tsc_timestamp)
2937 {
2938 	/* checked again under seqlock below */
2939 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2940 		return false;
2941 
2942 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2943 }
2944 #endif
2945 
2946 /*
2947  *
2948  * Assuming a stable TSC across physical CPUS, and a stable TSC
2949  * across virtual CPUs, the following condition is possible.
2950  * Each numbered line represents an event visible to both
2951  * CPUs at the next numbered event.
2952  *
2953  * "timespecX" represents host monotonic time. "tscX" represents
2954  * RDTSC value.
2955  *
2956  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
2957  *
2958  * 1.  read timespec0,tsc0
2959  * 2.					| timespec1 = timespec0 + N
2960  * 					| tsc1 = tsc0 + M
2961  * 3. transition to guest		| transition to guest
2962  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2963  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
2964  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2965  *
2966  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2967  *
2968  * 	- ret0 < ret1
2969  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2970  *		...
2971  *	- 0 < N - M => M < N
2972  *
2973  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2974  * always the case (the difference between two distinct xtime instances
2975  * might be smaller then the difference between corresponding TSC reads,
2976  * when updating guest vcpus pvclock areas).
2977  *
2978  * To avoid that problem, do not allow visibility of distinct
2979  * system_timestamp/tsc_timestamp values simultaneously: use a master
2980  * copy of host monotonic time values. Update that master copy
2981  * in lockstep.
2982  *
2983  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2984  *
2985  */
2986 
pvclock_update_vm_gtod_copy(struct kvm * kvm)2987 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2988 {
2989 #ifdef CONFIG_X86_64
2990 	struct kvm_arch *ka = &kvm->arch;
2991 	int vclock_mode;
2992 	bool host_tsc_clocksource, vcpus_matched;
2993 
2994 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2995 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2996 			atomic_read(&kvm->online_vcpus));
2997 
2998 	/*
2999 	 * If the host uses TSC clock, then passthrough TSC as stable
3000 	 * to the guest.
3001 	 */
3002 	host_tsc_clocksource = kvm_get_time_and_clockread(
3003 					&ka->master_kernel_ns,
3004 					&ka->master_cycle_now);
3005 
3006 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3007 				&& !ka->backwards_tsc_observed
3008 				&& !ka->boot_vcpu_runs_old_kvmclock;
3009 
3010 	if (ka->use_master_clock)
3011 		atomic_set(&kvm_guest_has_master_clock, 1);
3012 
3013 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3014 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3015 					vcpus_matched);
3016 #endif
3017 }
3018 
kvm_make_mclock_inprogress_request(struct kvm * kvm)3019 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3020 {
3021 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3022 }
3023 
__kvm_start_pvclock_update(struct kvm * kvm)3024 static void __kvm_start_pvclock_update(struct kvm *kvm)
3025 {
3026 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3027 	write_seqcount_begin(&kvm->arch.pvclock_sc);
3028 }
3029 
kvm_start_pvclock_update(struct kvm * kvm)3030 static void kvm_start_pvclock_update(struct kvm *kvm)
3031 {
3032 	kvm_make_mclock_inprogress_request(kvm);
3033 
3034 	/* no guest entries from this point */
3035 	__kvm_start_pvclock_update(kvm);
3036 }
3037 
kvm_end_pvclock_update(struct kvm * kvm)3038 static void kvm_end_pvclock_update(struct kvm *kvm)
3039 {
3040 	struct kvm_arch *ka = &kvm->arch;
3041 	struct kvm_vcpu *vcpu;
3042 	unsigned long i;
3043 
3044 	write_seqcount_end(&ka->pvclock_sc);
3045 	raw_spin_unlock_irq(&ka->tsc_write_lock);
3046 	kvm_for_each_vcpu(i, vcpu, kvm)
3047 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3048 
3049 	/* guest entries allowed */
3050 	kvm_for_each_vcpu(i, vcpu, kvm)
3051 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3052 }
3053 
kvm_update_masterclock(struct kvm * kvm)3054 static void kvm_update_masterclock(struct kvm *kvm)
3055 {
3056 	kvm_hv_request_tsc_page_update(kvm);
3057 	kvm_start_pvclock_update(kvm);
3058 	pvclock_update_vm_gtod_copy(kvm);
3059 	kvm_end_pvclock_update(kvm);
3060 }
3061 
3062 /*
3063  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3064  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
3065  * can change during boot even if the TSC is constant, as it's possible for KVM
3066  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
3067  * notification when calibration completes, but practically speaking calibration
3068  * will complete before userspace is alive enough to create VMs.
3069  */
get_cpu_tsc_khz(void)3070 static unsigned long get_cpu_tsc_khz(void)
3071 {
3072 	if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3073 		return tsc_khz;
3074 	else
3075 		return __this_cpu_read(cpu_tsc_khz);
3076 }
3077 
3078 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3079 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3080 {
3081 	struct kvm_arch *ka = &kvm->arch;
3082 	struct pvclock_vcpu_time_info hv_clock;
3083 
3084 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
3085 	get_cpu();
3086 
3087 	data->flags = 0;
3088 	if (ka->use_master_clock &&
3089 	    (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3090 #ifdef CONFIG_X86_64
3091 		struct timespec64 ts;
3092 
3093 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3094 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3095 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3096 		} else
3097 #endif
3098 		data->host_tsc = rdtsc();
3099 
3100 		data->flags |= KVM_CLOCK_TSC_STABLE;
3101 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3102 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3103 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3104 				   &hv_clock.tsc_shift,
3105 				   &hv_clock.tsc_to_system_mul);
3106 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3107 	} else {
3108 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3109 	}
3110 
3111 	put_cpu();
3112 }
3113 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3114 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3115 {
3116 	struct kvm_arch *ka = &kvm->arch;
3117 	unsigned seq;
3118 
3119 	do {
3120 		seq = read_seqcount_begin(&ka->pvclock_sc);
3121 		__get_kvmclock(kvm, data);
3122 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3123 }
3124 
get_kvmclock_ns(struct kvm * kvm)3125 u64 get_kvmclock_ns(struct kvm *kvm)
3126 {
3127 	struct kvm_clock_data data;
3128 
3129 	get_kvmclock(kvm, &data);
3130 	return data.clock;
3131 }
3132 
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)3133 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3134 				    struct kvm_vcpu *vcpu,
3135 				    struct gfn_to_pfn_cache *gpc,
3136 				    unsigned int offset)
3137 {
3138 	struct pvclock_vcpu_time_info *guest_hv_clock;
3139 	struct pvclock_vcpu_time_info hv_clock;
3140 	unsigned long flags;
3141 
3142 	memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3143 
3144 	read_lock_irqsave(&gpc->lock, flags);
3145 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3146 		read_unlock_irqrestore(&gpc->lock, flags);
3147 
3148 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3149 			return;
3150 
3151 		read_lock_irqsave(&gpc->lock, flags);
3152 	}
3153 
3154 	guest_hv_clock = (void *)(gpc->khva + offset);
3155 
3156 	/*
3157 	 * This VCPU is paused, but it's legal for a guest to read another
3158 	 * VCPU's kvmclock, so we really have to follow the specification where
3159 	 * it says that version is odd if data is being modified, and even after
3160 	 * it is consistent.
3161 	 */
3162 
3163 	guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3164 	smp_wmb();
3165 
3166 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3167 	hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3168 
3169 	memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3170 
3171 	smp_wmb();
3172 
3173 	guest_hv_clock->version = ++hv_clock.version;
3174 
3175 	kvm_gpc_mark_dirty_in_slot(gpc);
3176 	read_unlock_irqrestore(&gpc->lock, flags);
3177 
3178 	trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3179 }
3180 
kvm_guest_time_update(struct kvm_vcpu * v)3181 int kvm_guest_time_update(struct kvm_vcpu *v)
3182 {
3183 	struct pvclock_vcpu_time_info hv_clock = {};
3184 	unsigned long flags, tgt_tsc_khz;
3185 	unsigned seq;
3186 	struct kvm_vcpu_arch *vcpu = &v->arch;
3187 	struct kvm_arch *ka = &v->kvm->arch;
3188 	s64 kernel_ns;
3189 	u64 tsc_timestamp, host_tsc;
3190 	bool use_master_clock;
3191 
3192 	kernel_ns = 0;
3193 	host_tsc = 0;
3194 
3195 	/*
3196 	 * If the host uses TSC clock, then passthrough TSC as stable
3197 	 * to the guest.
3198 	 */
3199 	do {
3200 		seq = read_seqcount_begin(&ka->pvclock_sc);
3201 		use_master_clock = ka->use_master_clock;
3202 		if (use_master_clock) {
3203 			host_tsc = ka->master_cycle_now;
3204 			kernel_ns = ka->master_kernel_ns;
3205 		}
3206 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3207 
3208 	/* Keep irq disabled to prevent changes to the clock */
3209 	local_irq_save(flags);
3210 	tgt_tsc_khz = get_cpu_tsc_khz();
3211 	if (unlikely(tgt_tsc_khz == 0)) {
3212 		local_irq_restore(flags);
3213 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3214 		return 1;
3215 	}
3216 	if (!use_master_clock) {
3217 		host_tsc = rdtsc();
3218 		kernel_ns = get_kvmclock_base_ns();
3219 	}
3220 
3221 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3222 
3223 	/*
3224 	 * We may have to catch up the TSC to match elapsed wall clock
3225 	 * time for two reasons, even if kvmclock is used.
3226 	 *   1) CPU could have been running below the maximum TSC rate
3227 	 *   2) Broken TSC compensation resets the base at each VCPU
3228 	 *      entry to avoid unknown leaps of TSC even when running
3229 	 *      again on the same CPU.  This may cause apparent elapsed
3230 	 *      time to disappear, and the guest to stand still or run
3231 	 *	very slowly.
3232 	 */
3233 	if (vcpu->tsc_catchup) {
3234 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3235 		if (tsc > tsc_timestamp) {
3236 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3237 			tsc_timestamp = tsc;
3238 		}
3239 	}
3240 
3241 	local_irq_restore(flags);
3242 
3243 	/* With all the info we got, fill in the values */
3244 
3245 	if (kvm_caps.has_tsc_control)
3246 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3247 					    v->arch.l1_tsc_scaling_ratio);
3248 
3249 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3250 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3251 				   &vcpu->pvclock_tsc_shift,
3252 				   &vcpu->pvclock_tsc_mul);
3253 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3254 	}
3255 
3256 	hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3257 	hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3258 	hv_clock.tsc_timestamp = tsc_timestamp;
3259 	hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3260 	vcpu->last_guest_tsc = tsc_timestamp;
3261 
3262 	/* If the host uses TSC clocksource, then it is stable */
3263 	hv_clock.flags = 0;
3264 	if (use_master_clock)
3265 		hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3266 
3267 	if (vcpu->pv_time.active) {
3268 		/*
3269 		 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3270 		 * historic behavior is to only process the request if kvmclock
3271 		 * is active/enabled.
3272 		 */
3273 		if (vcpu->pvclock_set_guest_stopped_request) {
3274 			hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3275 			vcpu->pvclock_set_guest_stopped_request = false;
3276 		}
3277 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3278 
3279 		hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3280 	}
3281 
3282 	kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3283 
3284 #ifdef CONFIG_KVM_XEN
3285 	/*
3286 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3287 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3288 	 * This default behaviour led to bugs in some guest kernels which cause
3289 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3290 	 *
3291 	 * Note!  Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3292 	 */
3293 	if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3294 		hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3295 
3296 	if (vcpu->xen.vcpu_info_cache.active)
3297 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3298 					offsetof(struct compat_vcpu_info, time));
3299 	if (vcpu->xen.vcpu_time_info_cache.active)
3300 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3301 #endif
3302 	return 0;
3303 }
3304 
3305 /*
3306  * The pvclock_wall_clock ABI tells the guest the wall clock time at
3307  * which it started (i.e. its epoch, when its kvmclock was zero).
3308  *
3309  * In fact those clocks are subtly different; wall clock frequency is
3310  * adjusted by NTP and has leap seconds, while the kvmclock is a
3311  * simple function of the TSC without any such adjustment.
3312  *
3313  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3314  * that and kvmclock, but even that would be subject to change over
3315  * time.
3316  *
3317  * Attempt to calculate the epoch at a given moment using the *same*
3318  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3319  * wallclock and kvmclock times, and subtracting one from the other.
3320  *
3321  * Fall back to using their values at slightly different moments by
3322  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3323  */
kvm_get_wall_clock_epoch(struct kvm * kvm)3324 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3325 {
3326 #ifdef CONFIG_X86_64
3327 	struct pvclock_vcpu_time_info hv_clock;
3328 	struct kvm_arch *ka = &kvm->arch;
3329 	unsigned long seq, local_tsc_khz;
3330 	struct timespec64 ts;
3331 	uint64_t host_tsc;
3332 
3333 	do {
3334 		seq = read_seqcount_begin(&ka->pvclock_sc);
3335 
3336 		local_tsc_khz = 0;
3337 		if (!ka->use_master_clock)
3338 			break;
3339 
3340 		/*
3341 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
3342 		 * on the same CPU.
3343 		 */
3344 		get_cpu();
3345 
3346 		local_tsc_khz = get_cpu_tsc_khz();
3347 
3348 		if (local_tsc_khz &&
3349 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3350 			local_tsc_khz = 0; /* Fall back to old method */
3351 
3352 		put_cpu();
3353 
3354 		/*
3355 		 * These values must be snapshotted within the seqcount loop.
3356 		 * After that, it's just mathematics which can happen on any
3357 		 * CPU at any time.
3358 		 */
3359 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3360 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3361 
3362 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3363 
3364 	/*
3365 	 * If the conditions were right, and obtaining the wallclock+TSC was
3366 	 * successful, calculate the KVM clock at the corresponding time and
3367 	 * subtract one from the other to get the guest's epoch in nanoseconds
3368 	 * since 1970-01-01.
3369 	 */
3370 	if (local_tsc_khz) {
3371 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3372 				   &hv_clock.tsc_shift,
3373 				   &hv_clock.tsc_to_system_mul);
3374 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3375 			__pvclock_read_cycles(&hv_clock, host_tsc);
3376 	}
3377 #endif
3378 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3379 }
3380 
3381 /*
3382  * kvmclock updates which are isolated to a given vcpu, such as
3383  * vcpu->cpu migration, should not allow system_timestamp from
3384  * the rest of the vcpus to remain static. Otherwise ntp frequency
3385  * correction applies to one vcpu's system_timestamp but not
3386  * the others.
3387  *
3388  * So in those cases, request a kvmclock update for all vcpus.
3389  * We need to rate-limit these requests though, as they can
3390  * considerably slow guests that have a large number of vcpus.
3391  * The time for a remote vcpu to update its kvmclock is bound
3392  * by the delay we use to rate-limit the updates.
3393  */
3394 
3395 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3396 
kvmclock_update_fn(struct work_struct * work)3397 static void kvmclock_update_fn(struct work_struct *work)
3398 {
3399 	unsigned long i;
3400 	struct delayed_work *dwork = to_delayed_work(work);
3401 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3402 					   kvmclock_update_work);
3403 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3404 	struct kvm_vcpu *vcpu;
3405 
3406 	kvm_for_each_vcpu(i, vcpu, kvm) {
3407 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3408 		kvm_vcpu_kick(vcpu);
3409 	}
3410 }
3411 
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3412 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3413 {
3414 	struct kvm *kvm = v->kvm;
3415 
3416 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3417 	schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3418 					KVMCLOCK_UPDATE_DELAY);
3419 }
3420 
3421 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3422 
kvmclock_sync_fn(struct work_struct * work)3423 static void kvmclock_sync_fn(struct work_struct *work)
3424 {
3425 	struct delayed_work *dwork = to_delayed_work(work);
3426 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3427 					   kvmclock_sync_work);
3428 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3429 
3430 	schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3431 	schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3432 					KVMCLOCK_SYNC_PERIOD);
3433 }
3434 
3435 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3436 static bool is_mci_control_msr(u32 msr)
3437 {
3438 	return (msr & 3) == 0;
3439 }
is_mci_status_msr(u32 msr)3440 static bool is_mci_status_msr(u32 msr)
3441 {
3442 	return (msr & 3) == 1;
3443 }
3444 
3445 /*
3446  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3447  */
can_set_mci_status(struct kvm_vcpu * vcpu)3448 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3449 {
3450 	/* McStatusWrEn enabled? */
3451 	if (guest_cpuid_is_amd_compatible(vcpu))
3452 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3453 
3454 	return false;
3455 }
3456 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3457 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3458 {
3459 	u64 mcg_cap = vcpu->arch.mcg_cap;
3460 	unsigned bank_num = mcg_cap & 0xff;
3461 	u32 msr = msr_info->index;
3462 	u64 data = msr_info->data;
3463 	u32 offset, last_msr;
3464 
3465 	switch (msr) {
3466 	case MSR_IA32_MCG_STATUS:
3467 		vcpu->arch.mcg_status = data;
3468 		break;
3469 	case MSR_IA32_MCG_CTL:
3470 		if (!(mcg_cap & MCG_CTL_P) &&
3471 		    (data || !msr_info->host_initiated))
3472 			return 1;
3473 		if (data != 0 && data != ~(u64)0)
3474 			return 1;
3475 		vcpu->arch.mcg_ctl = data;
3476 		break;
3477 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3478 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3479 		if (msr > last_msr)
3480 			return 1;
3481 
3482 		if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3483 			return 1;
3484 		/* An attempt to write a 1 to a reserved bit raises #GP */
3485 		if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3486 			return 1;
3487 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3488 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
3489 		vcpu->arch.mci_ctl2_banks[offset] = data;
3490 		break;
3491 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3492 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3493 		if (msr > last_msr)
3494 			return 1;
3495 
3496 		/*
3497 		 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3498 		 * values are architecturally undefined.  But, some Linux
3499 		 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3500 		 * issue on AMD K8s, allow bit 10 to be clear when setting all
3501 		 * other bits in order to avoid an uncaught #GP in the guest.
3502 		 *
3503 		 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3504 		 * single-bit ECC data errors.
3505 		 */
3506 		if (is_mci_control_msr(msr) &&
3507 		    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3508 			return 1;
3509 
3510 		/*
3511 		 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3512 		 * AMD-based CPUs allow non-zero values, but if and only if
3513 		 * HWCR[McStatusWrEn] is set.
3514 		 */
3515 		if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3516 		    data != 0 && !can_set_mci_status(vcpu))
3517 			return 1;
3518 
3519 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3520 					    last_msr + 1 - MSR_IA32_MC0_CTL);
3521 		vcpu->arch.mce_banks[offset] = data;
3522 		break;
3523 	default:
3524 		return 1;
3525 	}
3526 	return 0;
3527 }
3528 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3529 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3530 {
3531 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3532 
3533 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
3534 }
3535 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3536 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3537 {
3538 	gpa_t gpa = data & ~0x3f;
3539 
3540 	/* Bits 4:5 are reserved, Should be zero */
3541 	if (data & 0x30)
3542 		return 1;
3543 
3544 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3545 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3546 		return 1;
3547 
3548 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3549 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3550 		return 1;
3551 
3552 	if (!lapic_in_kernel(vcpu))
3553 		return data ? 1 : 0;
3554 
3555 	vcpu->arch.apf.msr_en_val = data;
3556 
3557 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3558 		kvm_clear_async_pf_completion_queue(vcpu);
3559 		kvm_async_pf_hash_reset(vcpu);
3560 		return 0;
3561 	}
3562 
3563 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3564 					sizeof(u64)))
3565 		return 1;
3566 
3567 	vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3568 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3569 
3570 	kvm_async_pf_wakeup_all(vcpu);
3571 
3572 	return 0;
3573 }
3574 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3575 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3576 {
3577 	/* Bits 8-63 are reserved */
3578 	if (data >> 8)
3579 		return 1;
3580 
3581 	if (!lapic_in_kernel(vcpu))
3582 		return 1;
3583 
3584 	vcpu->arch.apf.msr_int_val = data;
3585 
3586 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3587 
3588 	return 0;
3589 }
3590 
kvmclock_reset(struct kvm_vcpu * vcpu)3591 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3592 {
3593 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
3594 	vcpu->arch.time = 0;
3595 }
3596 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3597 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3598 {
3599 	++vcpu->stat.tlb_flush;
3600 	kvm_x86_call(flush_tlb_all)(vcpu);
3601 
3602 	/* Flushing all ASIDs flushes the current ASID... */
3603 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3604 }
3605 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3606 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3607 {
3608 	++vcpu->stat.tlb_flush;
3609 
3610 	if (!tdp_enabled) {
3611 		/*
3612 		 * A TLB flush on behalf of the guest is equivalent to
3613 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3614 		 * a forced sync of the shadow page tables.  Ensure all the
3615 		 * roots are synced and the guest TLB in hardware is clean.
3616 		 */
3617 		kvm_mmu_sync_roots(vcpu);
3618 		kvm_mmu_sync_prev_roots(vcpu);
3619 	}
3620 
3621 	kvm_x86_call(flush_tlb_guest)(vcpu);
3622 
3623 	/*
3624 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3625 	 * grained flushing.
3626 	 */
3627 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
3628 }
3629 
3630 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3631 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3632 {
3633 	++vcpu->stat.tlb_flush;
3634 	kvm_x86_call(flush_tlb_current)(vcpu);
3635 }
3636 
3637 /*
3638  * Service "local" TLB flush requests, which are specific to the current MMU
3639  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3640  * TLB flushes that are targeted at an MMU context also need to be serviced
3641  * prior before nested VM-Enter/VM-Exit.
3642  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3643 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3644 {
3645 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3646 		kvm_vcpu_flush_tlb_current(vcpu);
3647 
3648 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3649 		kvm_vcpu_flush_tlb_guest(vcpu);
3650 }
3651 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3652 
record_steal_time(struct kvm_vcpu * vcpu)3653 static void record_steal_time(struct kvm_vcpu *vcpu)
3654 {
3655 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3656 	struct kvm_steal_time __user *st;
3657 	struct kvm_memslots *slots;
3658 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3659 	u64 steal;
3660 	u32 version;
3661 
3662 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3663 		kvm_xen_runstate_set_running(vcpu);
3664 		return;
3665 	}
3666 
3667 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3668 		return;
3669 
3670 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3671 		return;
3672 
3673 	slots = kvm_memslots(vcpu->kvm);
3674 
3675 	if (unlikely(slots->generation != ghc->generation ||
3676 		     gpa != ghc->gpa ||
3677 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3678 		/* We rely on the fact that it fits in a single page. */
3679 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3680 
3681 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3682 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3683 			return;
3684 	}
3685 
3686 	st = (struct kvm_steal_time __user *)ghc->hva;
3687 	/*
3688 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3689 	 * expensive IPIs.
3690 	 */
3691 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3692 		u8 st_preempted = 0;
3693 		int err = -EFAULT;
3694 
3695 		if (!user_access_begin(st, sizeof(*st)))
3696 			return;
3697 
3698 		asm volatile("1: xchgb %0, %2\n"
3699 			     "xor %1, %1\n"
3700 			     "2:\n"
3701 			     _ASM_EXTABLE_UA(1b, 2b)
3702 			     : "+q" (st_preempted),
3703 			       "+&r" (err),
3704 			       "+m" (st->preempted));
3705 		if (err)
3706 			goto out;
3707 
3708 		user_access_end();
3709 
3710 		vcpu->arch.st.preempted = 0;
3711 
3712 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3713 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3714 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3715 			kvm_vcpu_flush_tlb_guest(vcpu);
3716 
3717 		if (!user_access_begin(st, sizeof(*st)))
3718 			goto dirty;
3719 	} else {
3720 		if (!user_access_begin(st, sizeof(*st)))
3721 			return;
3722 
3723 		unsafe_put_user(0, &st->preempted, out);
3724 		vcpu->arch.st.preempted = 0;
3725 	}
3726 
3727 	unsafe_get_user(version, &st->version, out);
3728 	if (version & 1)
3729 		version += 1;  /* first time write, random junk */
3730 
3731 	version += 1;
3732 	unsafe_put_user(version, &st->version, out);
3733 
3734 	smp_wmb();
3735 
3736 	unsafe_get_user(steal, &st->steal, out);
3737 	steal += current->sched_info.run_delay -
3738 		vcpu->arch.st.last_steal;
3739 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3740 	unsafe_put_user(steal, &st->steal, out);
3741 
3742 	version += 1;
3743 	unsafe_put_user(version, &st->version, out);
3744 
3745  out:
3746 	user_access_end();
3747  dirty:
3748 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3749 }
3750 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3751 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3752 {
3753 	u32 msr = msr_info->index;
3754 	u64 data = msr_info->data;
3755 
3756 	/*
3757 	 * Do not allow host-initiated writes to trigger the Xen hypercall
3758 	 * page setup; it could incur locking paths which are not expected
3759 	 * if userspace sets the MSR in an unusual location.
3760 	 */
3761 	if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3762 	    !msr_info->host_initiated)
3763 		return kvm_xen_write_hypercall_page(vcpu, data);
3764 
3765 	switch (msr) {
3766 	case MSR_AMD64_NB_CFG:
3767 	case MSR_IA32_UCODE_WRITE:
3768 	case MSR_VM_HSAVE_PA:
3769 	case MSR_AMD64_PATCH_LOADER:
3770 	case MSR_AMD64_BU_CFG2:
3771 	case MSR_AMD64_DC_CFG:
3772 	case MSR_AMD64_TW_CFG:
3773 	case MSR_F15H_EX_CFG:
3774 		break;
3775 
3776 	case MSR_IA32_UCODE_REV:
3777 		if (msr_info->host_initiated)
3778 			vcpu->arch.microcode_version = data;
3779 		break;
3780 	case MSR_IA32_ARCH_CAPABILITIES:
3781 		if (!msr_info->host_initiated ||
3782 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3783 			return KVM_MSR_RET_UNSUPPORTED;
3784 		vcpu->arch.arch_capabilities = data;
3785 		break;
3786 	case MSR_IA32_PERF_CAPABILITIES:
3787 		if (!msr_info->host_initiated ||
3788 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3789 			return KVM_MSR_RET_UNSUPPORTED;
3790 
3791 		if (data & ~kvm_caps.supported_perf_cap)
3792 			return 1;
3793 
3794 		/*
3795 		 * Note, this is not just a performance optimization!  KVM
3796 		 * disallows changing feature MSRs after the vCPU has run; PMU
3797 		 * refresh will bug the VM if called after the vCPU has run.
3798 		 */
3799 		if (vcpu->arch.perf_capabilities == data)
3800 			break;
3801 
3802 		vcpu->arch.perf_capabilities = data;
3803 		kvm_pmu_refresh(vcpu);
3804 		break;
3805 	case MSR_IA32_PRED_CMD: {
3806 		u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3807 
3808 		if (!msr_info->host_initiated) {
3809 			if ((!guest_has_pred_cmd_msr(vcpu)))
3810 				return 1;
3811 
3812 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3813 			    !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3814 				reserved_bits |= PRED_CMD_IBPB;
3815 
3816 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3817 				reserved_bits |= PRED_CMD_SBPB;
3818 		}
3819 
3820 		if (!boot_cpu_has(X86_FEATURE_IBPB))
3821 			reserved_bits |= PRED_CMD_IBPB;
3822 
3823 		if (!boot_cpu_has(X86_FEATURE_SBPB))
3824 			reserved_bits |= PRED_CMD_SBPB;
3825 
3826 		if (data & reserved_bits)
3827 			return 1;
3828 
3829 		if (!data)
3830 			break;
3831 
3832 		wrmsrl(MSR_IA32_PRED_CMD, data);
3833 		break;
3834 	}
3835 	case MSR_IA32_FLUSH_CMD:
3836 		if (!msr_info->host_initiated &&
3837 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3838 			return 1;
3839 
3840 		if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3841 			return 1;
3842 		if (!data)
3843 			break;
3844 
3845 		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3846 		break;
3847 	case MSR_EFER:
3848 		return set_efer(vcpu, msr_info);
3849 	case MSR_K7_HWCR:
3850 		data &= ~(u64)0x40;	/* ignore flush filter disable */
3851 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
3852 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
3853 
3854 		/*
3855 		 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3856 		 * through at least v6.6 whine if TscFreqSel is clear,
3857 		 * depending on F/M/S.
3858 		 */
3859 		if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
3860 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3861 			return 1;
3862 		}
3863 		vcpu->arch.msr_hwcr = data;
3864 		break;
3865 	case MSR_FAM10H_MMIO_CONF_BASE:
3866 		if (data != 0) {
3867 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3868 			return 1;
3869 		}
3870 		break;
3871 	case MSR_IA32_CR_PAT:
3872 		if (!kvm_pat_valid(data))
3873 			return 1;
3874 
3875 		vcpu->arch.pat = data;
3876 		break;
3877 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3878 	case MSR_MTRRdefType:
3879 		return kvm_mtrr_set_msr(vcpu, msr, data);
3880 	case MSR_IA32_APICBASE:
3881 		return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
3882 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3883 		return kvm_x2apic_msr_write(vcpu, msr, data);
3884 	case MSR_IA32_TSC_DEADLINE:
3885 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
3886 		break;
3887 	case MSR_IA32_TSC_ADJUST:
3888 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3889 			if (!msr_info->host_initiated) {
3890 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3891 				adjust_tsc_offset_guest(vcpu, adj);
3892 				/* Before back to guest, tsc_timestamp must be adjusted
3893 				 * as well, otherwise guest's percpu pvclock time could jump.
3894 				 */
3895 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3896 			}
3897 			vcpu->arch.ia32_tsc_adjust_msr = data;
3898 		}
3899 		break;
3900 	case MSR_IA32_MISC_ENABLE: {
3901 		u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3902 
3903 		if (!msr_info->host_initiated) {
3904 			/* RO bits */
3905 			if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3906 				return 1;
3907 
3908 			/* R bits, i.e. writes are ignored, but don't fault. */
3909 			data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3910 			data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3911 		}
3912 
3913 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3914 		    ((old_val ^ data)  & MSR_IA32_MISC_ENABLE_MWAIT)) {
3915 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
3916 				return 1;
3917 			vcpu->arch.ia32_misc_enable_msr = data;
3918 			vcpu->arch.cpuid_dynamic_bits_dirty = true;
3919 		} else {
3920 			vcpu->arch.ia32_misc_enable_msr = data;
3921 		}
3922 		break;
3923 	}
3924 	case MSR_IA32_SMBASE:
3925 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
3926 			return 1;
3927 		vcpu->arch.smbase = data;
3928 		break;
3929 	case MSR_IA32_POWER_CTL:
3930 		vcpu->arch.msr_ia32_power_ctl = data;
3931 		break;
3932 	case MSR_IA32_TSC:
3933 		if (msr_info->host_initiated) {
3934 			kvm_synchronize_tsc(vcpu, &data);
3935 		} else if (!vcpu->arch.guest_tsc_protected) {
3936 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3937 			adjust_tsc_offset_guest(vcpu, adj);
3938 			vcpu->arch.ia32_tsc_adjust_msr += adj;
3939 		}
3940 		break;
3941 	case MSR_IA32_XSS:
3942 		if (!msr_info->host_initiated &&
3943 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3944 			return 1;
3945 		/*
3946 		 * KVM supports exposing PT to the guest, but does not support
3947 		 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3948 		 * XSAVES/XRSTORS to save/restore PT MSRs.
3949 		 */
3950 		if (data & ~kvm_caps.supported_xss)
3951 			return 1;
3952 		vcpu->arch.ia32_xss = data;
3953 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
3954 		break;
3955 	case MSR_SMI_COUNT:
3956 		if (!msr_info->host_initiated)
3957 			return 1;
3958 		vcpu->arch.smi_count = data;
3959 		break;
3960 	case MSR_KVM_WALL_CLOCK_NEW:
3961 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3962 			return 1;
3963 
3964 		vcpu->kvm->arch.wall_clock = data;
3965 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3966 		break;
3967 	case MSR_KVM_WALL_CLOCK:
3968 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3969 			return 1;
3970 
3971 		vcpu->kvm->arch.wall_clock = data;
3972 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3973 		break;
3974 	case MSR_KVM_SYSTEM_TIME_NEW:
3975 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3976 			return 1;
3977 
3978 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3979 		break;
3980 	case MSR_KVM_SYSTEM_TIME:
3981 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3982 			return 1;
3983 
3984 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
3985 		break;
3986 	case MSR_KVM_ASYNC_PF_EN:
3987 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3988 			return 1;
3989 
3990 		if (kvm_pv_enable_async_pf(vcpu, data))
3991 			return 1;
3992 		break;
3993 	case MSR_KVM_ASYNC_PF_INT:
3994 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3995 			return 1;
3996 
3997 		if (kvm_pv_enable_async_pf_int(vcpu, data))
3998 			return 1;
3999 		break;
4000 	case MSR_KVM_ASYNC_PF_ACK:
4001 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4002 			return 1;
4003 		if (data & 0x1) {
4004 			vcpu->arch.apf.pageready_pending = false;
4005 			kvm_check_async_pf_completion(vcpu);
4006 		}
4007 		break;
4008 	case MSR_KVM_STEAL_TIME:
4009 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4010 			return 1;
4011 
4012 		if (unlikely(!sched_info_on()))
4013 			return 1;
4014 
4015 		if (data & KVM_STEAL_RESERVED_MASK)
4016 			return 1;
4017 
4018 		vcpu->arch.st.msr_val = data;
4019 
4020 		if (!(data & KVM_MSR_ENABLED))
4021 			break;
4022 
4023 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4024 
4025 		break;
4026 	case MSR_KVM_PV_EOI_EN:
4027 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4028 			return 1;
4029 
4030 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4031 			return 1;
4032 		break;
4033 
4034 	case MSR_KVM_POLL_CONTROL:
4035 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4036 			return 1;
4037 
4038 		/* only enable bit supported */
4039 		if (data & (-1ULL << 1))
4040 			return 1;
4041 
4042 		vcpu->arch.msr_kvm_poll_control = data;
4043 		break;
4044 
4045 	case MSR_IA32_MCG_CTL:
4046 	case MSR_IA32_MCG_STATUS:
4047 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4048 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4049 		return set_msr_mce(vcpu, msr_info);
4050 
4051 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4052 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4053 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4054 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4055 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4056 			return kvm_pmu_set_msr(vcpu, msr_info);
4057 
4058 		if (data)
4059 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4060 		break;
4061 	case MSR_K7_CLK_CTL:
4062 		/*
4063 		 * Ignore all writes to this no longer documented MSR.
4064 		 * Writes are only relevant for old K7 processors,
4065 		 * all pre-dating SVM, but a recommended workaround from
4066 		 * AMD for these chips. It is possible to specify the
4067 		 * affected processor models on the command line, hence
4068 		 * the need to ignore the workaround.
4069 		 */
4070 		break;
4071 #ifdef CONFIG_KVM_HYPERV
4072 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4073 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4074 	case HV_X64_MSR_SYNDBG_OPTIONS:
4075 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4076 	case HV_X64_MSR_CRASH_CTL:
4077 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4078 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4079 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4080 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4081 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4082 		return kvm_hv_set_msr_common(vcpu, msr, data,
4083 					     msr_info->host_initiated);
4084 #endif
4085 	case MSR_IA32_BBL_CR_CTL3:
4086 		/* Drop writes to this legacy MSR -- see rdmsr
4087 		 * counterpart for further detail.
4088 		 */
4089 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4090 		break;
4091 	case MSR_AMD64_OSVW_ID_LENGTH:
4092 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4093 			return 1;
4094 		vcpu->arch.osvw.length = data;
4095 		break;
4096 	case MSR_AMD64_OSVW_STATUS:
4097 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4098 			return 1;
4099 		vcpu->arch.osvw.status = data;
4100 		break;
4101 	case MSR_PLATFORM_INFO:
4102 		if (!msr_info->host_initiated)
4103 			return 1;
4104 		vcpu->arch.msr_platform_info = data;
4105 		break;
4106 	case MSR_MISC_FEATURES_ENABLES:
4107 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4108 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4109 		     !supports_cpuid_fault(vcpu)))
4110 			return 1;
4111 		vcpu->arch.msr_misc_features_enables = data;
4112 		break;
4113 #ifdef CONFIG_X86_64
4114 	case MSR_IA32_XFD:
4115 		if (!msr_info->host_initiated &&
4116 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4117 			return 1;
4118 
4119 		if (data & ~kvm_guest_supported_xfd(vcpu))
4120 			return 1;
4121 
4122 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4123 		break;
4124 	case MSR_IA32_XFD_ERR:
4125 		if (!msr_info->host_initiated &&
4126 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4127 			return 1;
4128 
4129 		if (data & ~kvm_guest_supported_xfd(vcpu))
4130 			return 1;
4131 
4132 		vcpu->arch.guest_fpu.xfd_err = data;
4133 		break;
4134 #endif
4135 	default:
4136 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4137 			return kvm_pmu_set_msr(vcpu, msr_info);
4138 
4139 		return KVM_MSR_RET_UNSUPPORTED;
4140 	}
4141 	return 0;
4142 }
4143 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4144 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4145 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4146 {
4147 	u64 data;
4148 	u64 mcg_cap = vcpu->arch.mcg_cap;
4149 	unsigned bank_num = mcg_cap & 0xff;
4150 	u32 offset, last_msr;
4151 
4152 	switch (msr) {
4153 	case MSR_IA32_P5_MC_ADDR:
4154 	case MSR_IA32_P5_MC_TYPE:
4155 		data = 0;
4156 		break;
4157 	case MSR_IA32_MCG_CAP:
4158 		data = vcpu->arch.mcg_cap;
4159 		break;
4160 	case MSR_IA32_MCG_CTL:
4161 		if (!(mcg_cap & MCG_CTL_P) && !host)
4162 			return 1;
4163 		data = vcpu->arch.mcg_ctl;
4164 		break;
4165 	case MSR_IA32_MCG_STATUS:
4166 		data = vcpu->arch.mcg_status;
4167 		break;
4168 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4169 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4170 		if (msr > last_msr)
4171 			return 1;
4172 
4173 		if (!(mcg_cap & MCG_CMCI_P) && !host)
4174 			return 1;
4175 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4176 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
4177 		data = vcpu->arch.mci_ctl2_banks[offset];
4178 		break;
4179 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4180 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4181 		if (msr > last_msr)
4182 			return 1;
4183 
4184 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4185 					    last_msr + 1 - MSR_IA32_MC0_CTL);
4186 		data = vcpu->arch.mce_banks[offset];
4187 		break;
4188 	default:
4189 		return 1;
4190 	}
4191 	*pdata = data;
4192 	return 0;
4193 }
4194 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4195 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4196 {
4197 	switch (msr_info->index) {
4198 	case MSR_IA32_PLATFORM_ID:
4199 	case MSR_IA32_EBL_CR_POWERON:
4200 	case MSR_IA32_LASTBRANCHFROMIP:
4201 	case MSR_IA32_LASTBRANCHTOIP:
4202 	case MSR_IA32_LASTINTFROMIP:
4203 	case MSR_IA32_LASTINTTOIP:
4204 	case MSR_AMD64_SYSCFG:
4205 	case MSR_K8_TSEG_ADDR:
4206 	case MSR_K8_TSEG_MASK:
4207 	case MSR_VM_HSAVE_PA:
4208 	case MSR_K8_INT_PENDING_MSG:
4209 	case MSR_AMD64_NB_CFG:
4210 	case MSR_FAM10H_MMIO_CONF_BASE:
4211 	case MSR_AMD64_BU_CFG2:
4212 	case MSR_IA32_PERF_CTL:
4213 	case MSR_AMD64_DC_CFG:
4214 	case MSR_AMD64_TW_CFG:
4215 	case MSR_F15H_EX_CFG:
4216 	/*
4217 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4218 	 * limit) MSRs. Just return 0, as we do not want to expose the host
4219 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
4220 	 * so for existing CPU-specific MSRs.
4221 	 */
4222 	case MSR_RAPL_POWER_UNIT:
4223 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
4224 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
4225 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
4226 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
4227 		msr_info->data = 0;
4228 		break;
4229 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4230 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4231 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4232 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4233 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4234 			return kvm_pmu_get_msr(vcpu, msr_info);
4235 		msr_info->data = 0;
4236 		break;
4237 	case MSR_IA32_UCODE_REV:
4238 		msr_info->data = vcpu->arch.microcode_version;
4239 		break;
4240 	case MSR_IA32_ARCH_CAPABILITIES:
4241 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4242 			return KVM_MSR_RET_UNSUPPORTED;
4243 		msr_info->data = vcpu->arch.arch_capabilities;
4244 		break;
4245 	case MSR_IA32_PERF_CAPABILITIES:
4246 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4247 			return KVM_MSR_RET_UNSUPPORTED;
4248 		msr_info->data = vcpu->arch.perf_capabilities;
4249 		break;
4250 	case MSR_IA32_POWER_CTL:
4251 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4252 		break;
4253 	case MSR_IA32_TSC: {
4254 		/*
4255 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4256 		 * even when not intercepted. AMD manual doesn't explicitly
4257 		 * state this but appears to behave the same.
4258 		 *
4259 		 * On userspace reads and writes, however, we unconditionally
4260 		 * return L1's TSC value to ensure backwards-compatible
4261 		 * behavior for migration.
4262 		 */
4263 		u64 offset, ratio;
4264 
4265 		if (msr_info->host_initiated) {
4266 			offset = vcpu->arch.l1_tsc_offset;
4267 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
4268 		} else {
4269 			offset = vcpu->arch.tsc_offset;
4270 			ratio = vcpu->arch.tsc_scaling_ratio;
4271 		}
4272 
4273 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4274 		break;
4275 	}
4276 	case MSR_IA32_CR_PAT:
4277 		msr_info->data = vcpu->arch.pat;
4278 		break;
4279 	case MSR_MTRRcap:
4280 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4281 	case MSR_MTRRdefType:
4282 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4283 	case 0xcd: /* fsb frequency */
4284 		msr_info->data = 3;
4285 		break;
4286 		/*
4287 		 * MSR_EBC_FREQUENCY_ID
4288 		 * Conservative value valid for even the basic CPU models.
4289 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4290 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4291 		 * and 266MHz for model 3, or 4. Set Core Clock
4292 		 * Frequency to System Bus Frequency Ratio to 1 (bits
4293 		 * 31:24) even though these are only valid for CPU
4294 		 * models > 2, however guests may end up dividing or
4295 		 * multiplying by zero otherwise.
4296 		 */
4297 	case MSR_EBC_FREQUENCY_ID:
4298 		msr_info->data = 1 << 24;
4299 		break;
4300 	case MSR_IA32_APICBASE:
4301 		msr_info->data = vcpu->arch.apic_base;
4302 		break;
4303 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4304 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4305 	case MSR_IA32_TSC_DEADLINE:
4306 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4307 		break;
4308 	case MSR_IA32_TSC_ADJUST:
4309 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4310 		break;
4311 	case MSR_IA32_MISC_ENABLE:
4312 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4313 		break;
4314 	case MSR_IA32_SMBASE:
4315 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4316 			return 1;
4317 		msr_info->data = vcpu->arch.smbase;
4318 		break;
4319 	case MSR_SMI_COUNT:
4320 		msr_info->data = vcpu->arch.smi_count;
4321 		break;
4322 	case MSR_IA32_PERF_STATUS:
4323 		/* TSC increment by tick */
4324 		msr_info->data = 1000ULL;
4325 		/* CPU multiplier */
4326 		msr_info->data |= (((uint64_t)4ULL) << 40);
4327 		break;
4328 	case MSR_EFER:
4329 		msr_info->data = vcpu->arch.efer;
4330 		break;
4331 	case MSR_KVM_WALL_CLOCK:
4332 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4333 			return 1;
4334 
4335 		msr_info->data = vcpu->kvm->arch.wall_clock;
4336 		break;
4337 	case MSR_KVM_WALL_CLOCK_NEW:
4338 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4339 			return 1;
4340 
4341 		msr_info->data = vcpu->kvm->arch.wall_clock;
4342 		break;
4343 	case MSR_KVM_SYSTEM_TIME:
4344 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4345 			return 1;
4346 
4347 		msr_info->data = vcpu->arch.time;
4348 		break;
4349 	case MSR_KVM_SYSTEM_TIME_NEW:
4350 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4351 			return 1;
4352 
4353 		msr_info->data = vcpu->arch.time;
4354 		break;
4355 	case MSR_KVM_ASYNC_PF_EN:
4356 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4357 			return 1;
4358 
4359 		msr_info->data = vcpu->arch.apf.msr_en_val;
4360 		break;
4361 	case MSR_KVM_ASYNC_PF_INT:
4362 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4363 			return 1;
4364 
4365 		msr_info->data = vcpu->arch.apf.msr_int_val;
4366 		break;
4367 	case MSR_KVM_ASYNC_PF_ACK:
4368 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4369 			return 1;
4370 
4371 		msr_info->data = 0;
4372 		break;
4373 	case MSR_KVM_STEAL_TIME:
4374 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4375 			return 1;
4376 
4377 		msr_info->data = vcpu->arch.st.msr_val;
4378 		break;
4379 	case MSR_KVM_PV_EOI_EN:
4380 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4381 			return 1;
4382 
4383 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4384 		break;
4385 	case MSR_KVM_POLL_CONTROL:
4386 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4387 			return 1;
4388 
4389 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4390 		break;
4391 	case MSR_IA32_P5_MC_ADDR:
4392 	case MSR_IA32_P5_MC_TYPE:
4393 	case MSR_IA32_MCG_CAP:
4394 	case MSR_IA32_MCG_CTL:
4395 	case MSR_IA32_MCG_STATUS:
4396 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4397 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4398 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4399 				   msr_info->host_initiated);
4400 	case MSR_IA32_XSS:
4401 		if (!msr_info->host_initiated &&
4402 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4403 			return 1;
4404 		msr_info->data = vcpu->arch.ia32_xss;
4405 		break;
4406 	case MSR_K7_CLK_CTL:
4407 		/*
4408 		 * Provide expected ramp-up count for K7. All other
4409 		 * are set to zero, indicating minimum divisors for
4410 		 * every field.
4411 		 *
4412 		 * This prevents guest kernels on AMD host with CPU
4413 		 * type 6, model 8 and higher from exploding due to
4414 		 * the rdmsr failing.
4415 		 */
4416 		msr_info->data = 0x20000000;
4417 		break;
4418 #ifdef CONFIG_KVM_HYPERV
4419 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4420 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4421 	case HV_X64_MSR_SYNDBG_OPTIONS:
4422 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4423 	case HV_X64_MSR_CRASH_CTL:
4424 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4425 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4426 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4427 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4428 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4429 		return kvm_hv_get_msr_common(vcpu,
4430 					     msr_info->index, &msr_info->data,
4431 					     msr_info->host_initiated);
4432 #endif
4433 	case MSR_IA32_BBL_CR_CTL3:
4434 		/* This legacy MSR exists but isn't fully documented in current
4435 		 * silicon.  It is however accessed by winxp in very narrow
4436 		 * scenarios where it sets bit #19, itself documented as
4437 		 * a "reserved" bit.  Best effort attempt to source coherent
4438 		 * read data here should the balance of the register be
4439 		 * interpreted by the guest:
4440 		 *
4441 		 * L2 cache control register 3: 64GB range, 256KB size,
4442 		 * enabled, latency 0x1, configured
4443 		 */
4444 		msr_info->data = 0xbe702111;
4445 		break;
4446 	case MSR_AMD64_OSVW_ID_LENGTH:
4447 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4448 			return 1;
4449 		msr_info->data = vcpu->arch.osvw.length;
4450 		break;
4451 	case MSR_AMD64_OSVW_STATUS:
4452 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4453 			return 1;
4454 		msr_info->data = vcpu->arch.osvw.status;
4455 		break;
4456 	case MSR_PLATFORM_INFO:
4457 		if (!msr_info->host_initiated &&
4458 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4459 			return 1;
4460 		msr_info->data = vcpu->arch.msr_platform_info;
4461 		break;
4462 	case MSR_MISC_FEATURES_ENABLES:
4463 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4464 		break;
4465 	case MSR_K7_HWCR:
4466 		msr_info->data = vcpu->arch.msr_hwcr;
4467 		break;
4468 #ifdef CONFIG_X86_64
4469 	case MSR_IA32_XFD:
4470 		if (!msr_info->host_initiated &&
4471 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4472 			return 1;
4473 
4474 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4475 		break;
4476 	case MSR_IA32_XFD_ERR:
4477 		if (!msr_info->host_initiated &&
4478 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4479 			return 1;
4480 
4481 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4482 		break;
4483 #endif
4484 	default:
4485 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4486 			return kvm_pmu_get_msr(vcpu, msr_info);
4487 
4488 		return KVM_MSR_RET_UNSUPPORTED;
4489 	}
4490 	return 0;
4491 }
4492 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4493 
4494 /*
4495  * Read or write a bunch of msrs. All parameters are kernel addresses.
4496  *
4497  * @return number of msrs set successfully.
4498  */
__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))4499 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4500 		    struct kvm_msr_entry *entries,
4501 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4502 				  unsigned index, u64 *data))
4503 {
4504 	int i;
4505 
4506 	for (i = 0; i < msrs->nmsrs; ++i)
4507 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4508 			break;
4509 
4510 	return i;
4511 }
4512 
4513 /*
4514  * Read or write a bunch of msrs. Parameters are user addresses.
4515  *
4516  * @return number of msrs set successfully.
4517  */
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)4518 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4519 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4520 				unsigned index, u64 *data),
4521 		  int writeback)
4522 {
4523 	struct kvm_msrs msrs;
4524 	struct kvm_msr_entry *entries;
4525 	unsigned size;
4526 	int r;
4527 
4528 	r = -EFAULT;
4529 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4530 		goto out;
4531 
4532 	r = -E2BIG;
4533 	if (msrs.nmsrs >= MAX_IO_MSRS)
4534 		goto out;
4535 
4536 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4537 	entries = memdup_user(user_msrs->entries, size);
4538 	if (IS_ERR(entries)) {
4539 		r = PTR_ERR(entries);
4540 		goto out;
4541 	}
4542 
4543 	r = __msr_io(vcpu, &msrs, entries, do_msr);
4544 
4545 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4546 		r = -EFAULT;
4547 
4548 	kfree(entries);
4549 out:
4550 	return r;
4551 }
4552 
kvm_can_mwait_in_guest(void)4553 static inline bool kvm_can_mwait_in_guest(void)
4554 {
4555 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4556 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4557 		boot_cpu_has(X86_FEATURE_ARAT);
4558 }
4559 
kvm_get_allowed_disable_exits(void)4560 static u64 kvm_get_allowed_disable_exits(void)
4561 {
4562 	u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4563 
4564 	if (!mitigate_smt_rsb) {
4565 		r |= KVM_X86_DISABLE_EXITS_HLT |
4566 			KVM_X86_DISABLE_EXITS_CSTATE;
4567 
4568 		if (kvm_can_mwait_in_guest())
4569 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
4570 	}
4571 	return r;
4572 }
4573 
4574 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4575 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4576 					    struct kvm_cpuid2 __user *cpuid_arg)
4577 {
4578 	struct kvm_cpuid2 cpuid;
4579 	int r;
4580 
4581 	r = -EFAULT;
4582 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4583 		return r;
4584 
4585 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4586 	if (r)
4587 		return r;
4588 
4589 	r = -EFAULT;
4590 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4591 		return r;
4592 
4593 	return 0;
4594 }
4595 #endif
4596 
kvm_is_vm_type_supported(unsigned long type)4597 static bool kvm_is_vm_type_supported(unsigned long type)
4598 {
4599 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4600 }
4601 
kvm_sync_valid_fields(struct kvm * kvm)4602 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4603 {
4604 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4605 }
4606 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4607 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4608 {
4609 	int r = 0;
4610 
4611 	switch (ext) {
4612 	case KVM_CAP_IRQCHIP:
4613 	case KVM_CAP_HLT:
4614 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4615 	case KVM_CAP_SET_TSS_ADDR:
4616 	case KVM_CAP_EXT_CPUID:
4617 	case KVM_CAP_EXT_EMUL_CPUID:
4618 	case KVM_CAP_CLOCKSOURCE:
4619 	case KVM_CAP_PIT:
4620 	case KVM_CAP_NOP_IO_DELAY:
4621 	case KVM_CAP_MP_STATE:
4622 	case KVM_CAP_SYNC_MMU:
4623 	case KVM_CAP_USER_NMI:
4624 	case KVM_CAP_REINJECT_CONTROL:
4625 	case KVM_CAP_IRQ_INJECT_STATUS:
4626 	case KVM_CAP_IOEVENTFD:
4627 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4628 	case KVM_CAP_PIT2:
4629 	case KVM_CAP_PIT_STATE2:
4630 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4631 	case KVM_CAP_VCPU_EVENTS:
4632 #ifdef CONFIG_KVM_HYPERV
4633 	case KVM_CAP_HYPERV:
4634 	case KVM_CAP_HYPERV_VAPIC:
4635 	case KVM_CAP_HYPERV_SPIN:
4636 	case KVM_CAP_HYPERV_TIME:
4637 	case KVM_CAP_HYPERV_SYNIC:
4638 	case KVM_CAP_HYPERV_SYNIC2:
4639 	case KVM_CAP_HYPERV_VP_INDEX:
4640 	case KVM_CAP_HYPERV_EVENTFD:
4641 	case KVM_CAP_HYPERV_TLBFLUSH:
4642 	case KVM_CAP_HYPERV_SEND_IPI:
4643 	case KVM_CAP_HYPERV_CPUID:
4644 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4645 	case KVM_CAP_SYS_HYPERV_CPUID:
4646 #endif
4647 	case KVM_CAP_PCI_SEGMENT:
4648 	case KVM_CAP_DEBUGREGS:
4649 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4650 	case KVM_CAP_XSAVE:
4651 	case KVM_CAP_ASYNC_PF:
4652 	case KVM_CAP_ASYNC_PF_INT:
4653 	case KVM_CAP_GET_TSC_KHZ:
4654 	case KVM_CAP_KVMCLOCK_CTRL:
4655 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4656 	case KVM_CAP_TSC_DEADLINE_TIMER:
4657 	case KVM_CAP_DISABLE_QUIRKS:
4658 	case KVM_CAP_SET_BOOT_CPU_ID:
4659  	case KVM_CAP_SPLIT_IRQCHIP:
4660 	case KVM_CAP_IMMEDIATE_EXIT:
4661 	case KVM_CAP_PMU_EVENT_FILTER:
4662 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4663 	case KVM_CAP_GET_MSR_FEATURES:
4664 	case KVM_CAP_MSR_PLATFORM_INFO:
4665 	case KVM_CAP_EXCEPTION_PAYLOAD:
4666 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4667 	case KVM_CAP_SET_GUEST_DEBUG:
4668 	case KVM_CAP_LAST_CPU:
4669 	case KVM_CAP_X86_USER_SPACE_MSR:
4670 	case KVM_CAP_X86_MSR_FILTER:
4671 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4672 #ifdef CONFIG_X86_SGX_KVM
4673 	case KVM_CAP_SGX_ATTRIBUTE:
4674 #endif
4675 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4676 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4677 	case KVM_CAP_SREGS2:
4678 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4679 	case KVM_CAP_VCPU_ATTRIBUTES:
4680 	case KVM_CAP_SYS_ATTRIBUTES:
4681 	case KVM_CAP_VAPIC:
4682 	case KVM_CAP_ENABLE_CAP:
4683 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4684 	case KVM_CAP_IRQFD_RESAMPLE:
4685 	case KVM_CAP_MEMORY_FAULT_INFO:
4686 	case KVM_CAP_X86_GUEST_MODE:
4687 		r = 1;
4688 		break;
4689 	case KVM_CAP_PRE_FAULT_MEMORY:
4690 		r = tdp_enabled;
4691 		break;
4692 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4693 		r = APIC_BUS_CYCLE_NS_DEFAULT;
4694 		break;
4695 	case KVM_CAP_EXIT_HYPERCALL:
4696 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4697 		break;
4698 	case KVM_CAP_SET_GUEST_DEBUG2:
4699 		return KVM_GUESTDBG_VALID_MASK;
4700 #ifdef CONFIG_KVM_XEN
4701 	case KVM_CAP_XEN_HVM:
4702 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4703 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4704 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4705 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4706 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4707 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4708 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4709 		if (sched_info_on())
4710 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4711 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4712 		break;
4713 #endif
4714 	case KVM_CAP_SYNC_REGS:
4715 		r = kvm_sync_valid_fields(kvm);
4716 		break;
4717 	case KVM_CAP_ADJUST_CLOCK:
4718 		r = KVM_CLOCK_VALID_FLAGS;
4719 		break;
4720 	case KVM_CAP_X86_DISABLE_EXITS:
4721 		r = kvm_get_allowed_disable_exits();
4722 		break;
4723 	case KVM_CAP_X86_SMM:
4724 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4725 			break;
4726 
4727 		/* SMBASE is usually relocated above 1M on modern chipsets,
4728 		 * and SMM handlers might indeed rely on 4G segment limits,
4729 		 * so do not report SMM to be available if real mode is
4730 		 * emulated via vm86 mode.  Still, do not go to great lengths
4731 		 * to avoid userspace's usage of the feature, because it is a
4732 		 * fringe case that is not enabled except via specific settings
4733 		 * of the module parameters.
4734 		 */
4735 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4736 		break;
4737 	case KVM_CAP_NR_VCPUS:
4738 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4739 		break;
4740 	case KVM_CAP_MAX_VCPUS:
4741 		r = KVM_MAX_VCPUS;
4742 		break;
4743 	case KVM_CAP_MAX_VCPU_ID:
4744 		r = KVM_MAX_VCPU_IDS;
4745 		break;
4746 	case KVM_CAP_PV_MMU:	/* obsolete */
4747 		r = 0;
4748 		break;
4749 	case KVM_CAP_MCE:
4750 		r = KVM_MAX_MCE_BANKS;
4751 		break;
4752 	case KVM_CAP_XCRS:
4753 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4754 		break;
4755 	case KVM_CAP_TSC_CONTROL:
4756 	case KVM_CAP_VM_TSC_CONTROL:
4757 		r = kvm_caps.has_tsc_control;
4758 		break;
4759 	case KVM_CAP_X2APIC_API:
4760 		r = KVM_X2APIC_API_VALID_FLAGS;
4761 		break;
4762 	case KVM_CAP_NESTED_STATE:
4763 		r = kvm_x86_ops.nested_ops->get_state ?
4764 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4765 		break;
4766 #ifdef CONFIG_KVM_HYPERV
4767 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4768 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4769 		break;
4770 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4771 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4772 		break;
4773 #endif
4774 	case KVM_CAP_SMALLER_MAXPHYADDR:
4775 		r = (int) allow_smaller_maxphyaddr;
4776 		break;
4777 	case KVM_CAP_STEAL_TIME:
4778 		r = sched_info_on();
4779 		break;
4780 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4781 		if (kvm_caps.has_bus_lock_exit)
4782 			r = KVM_BUS_LOCK_DETECTION_OFF |
4783 			    KVM_BUS_LOCK_DETECTION_EXIT;
4784 		else
4785 			r = 0;
4786 		break;
4787 	case KVM_CAP_XSAVE2: {
4788 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4789 		if (r < sizeof(struct kvm_xsave))
4790 			r = sizeof(struct kvm_xsave);
4791 		break;
4792 	}
4793 	case KVM_CAP_PMU_CAPABILITY:
4794 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4795 		break;
4796 	case KVM_CAP_DISABLE_QUIRKS2:
4797 		r = KVM_X86_VALID_QUIRKS;
4798 		break;
4799 	case KVM_CAP_X86_NOTIFY_VMEXIT:
4800 		r = kvm_caps.has_notify_vmexit;
4801 		break;
4802 	case KVM_CAP_VM_TYPES:
4803 		r = kvm_caps.supported_vm_types;
4804 		break;
4805 	case KVM_CAP_READONLY_MEM:
4806 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4807 		break;
4808 	default:
4809 		break;
4810 	}
4811 	return r;
4812 }
4813 
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4814 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4815 {
4816 	if (attr->group) {
4817 		if (kvm_x86_ops.dev_get_attr)
4818 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4819 		return -ENXIO;
4820 	}
4821 
4822 	switch (attr->attr) {
4823 	case KVM_X86_XCOMP_GUEST_SUPP:
4824 		*val = kvm_caps.supported_xcr0;
4825 		return 0;
4826 	default:
4827 		return -ENXIO;
4828 	}
4829 }
4830 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)4831 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4832 {
4833 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4834 	int r;
4835 	u64 val;
4836 
4837 	r = __kvm_x86_dev_get_attr(attr, &val);
4838 	if (r < 0)
4839 		return r;
4840 
4841 	if (put_user(val, uaddr))
4842 		return -EFAULT;
4843 
4844 	return 0;
4845 }
4846 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)4847 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4848 {
4849 	u64 val;
4850 
4851 	return __kvm_x86_dev_get_attr(attr, &val);
4852 }
4853 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4854 long kvm_arch_dev_ioctl(struct file *filp,
4855 			unsigned int ioctl, unsigned long arg)
4856 {
4857 	void __user *argp = (void __user *)arg;
4858 	long r;
4859 
4860 	switch (ioctl) {
4861 	case KVM_GET_MSR_INDEX_LIST: {
4862 		struct kvm_msr_list __user *user_msr_list = argp;
4863 		struct kvm_msr_list msr_list;
4864 		unsigned n;
4865 
4866 		r = -EFAULT;
4867 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4868 			goto out;
4869 		n = msr_list.nmsrs;
4870 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4871 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4872 			goto out;
4873 		r = -E2BIG;
4874 		if (n < msr_list.nmsrs)
4875 			goto out;
4876 		r = -EFAULT;
4877 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4878 				 num_msrs_to_save * sizeof(u32)))
4879 			goto out;
4880 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4881 				 &emulated_msrs,
4882 				 num_emulated_msrs * sizeof(u32)))
4883 			goto out;
4884 		r = 0;
4885 		break;
4886 	}
4887 	case KVM_GET_SUPPORTED_CPUID:
4888 	case KVM_GET_EMULATED_CPUID: {
4889 		struct kvm_cpuid2 __user *cpuid_arg = argp;
4890 		struct kvm_cpuid2 cpuid;
4891 
4892 		r = -EFAULT;
4893 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4894 			goto out;
4895 
4896 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4897 					    ioctl);
4898 		if (r)
4899 			goto out;
4900 
4901 		r = -EFAULT;
4902 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4903 			goto out;
4904 		r = 0;
4905 		break;
4906 	}
4907 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
4908 		r = -EFAULT;
4909 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4910 				 sizeof(kvm_caps.supported_mce_cap)))
4911 			goto out;
4912 		r = 0;
4913 		break;
4914 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4915 		struct kvm_msr_list __user *user_msr_list = argp;
4916 		struct kvm_msr_list msr_list;
4917 		unsigned int n;
4918 
4919 		r = -EFAULT;
4920 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4921 			goto out;
4922 		n = msr_list.nmsrs;
4923 		msr_list.nmsrs = num_msr_based_features;
4924 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4925 			goto out;
4926 		r = -E2BIG;
4927 		if (n < msr_list.nmsrs)
4928 			goto out;
4929 		r = -EFAULT;
4930 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
4931 				 num_msr_based_features * sizeof(u32)))
4932 			goto out;
4933 		r = 0;
4934 		break;
4935 	}
4936 	case KVM_GET_MSRS:
4937 		r = msr_io(NULL, argp, do_get_feature_msr, 1);
4938 		break;
4939 #ifdef CONFIG_KVM_HYPERV
4940 	case KVM_GET_SUPPORTED_HV_CPUID:
4941 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4942 		break;
4943 #endif
4944 	case KVM_GET_DEVICE_ATTR: {
4945 		struct kvm_device_attr attr;
4946 		r = -EFAULT;
4947 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4948 			break;
4949 		r = kvm_x86_dev_get_attr(&attr);
4950 		break;
4951 	}
4952 	case KVM_HAS_DEVICE_ATTR: {
4953 		struct kvm_device_attr attr;
4954 		r = -EFAULT;
4955 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4956 			break;
4957 		r = kvm_x86_dev_has_attr(&attr);
4958 		break;
4959 	}
4960 	default:
4961 		r = -EINVAL;
4962 		break;
4963 	}
4964 out:
4965 	return r;
4966 }
4967 
wbinvd_ipi(void * garbage)4968 static void wbinvd_ipi(void *garbage)
4969 {
4970 	wbinvd();
4971 }
4972 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)4973 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4974 {
4975 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4976 }
4977 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)4978 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4979 {
4980 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
4981 
4982 	vcpu->arch.l1tf_flush_l1d = true;
4983 
4984 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
4985 		pmu->need_cleanup = true;
4986 		kvm_make_request(KVM_REQ_PMU, vcpu);
4987 	}
4988 
4989 	/* Address WBINVD may be executed by guest */
4990 	if (need_emulate_wbinvd(vcpu)) {
4991 		if (kvm_x86_call(has_wbinvd_exit)())
4992 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4993 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4994 			smp_call_function_single(vcpu->cpu,
4995 					wbinvd_ipi, NULL, 1);
4996 	}
4997 
4998 	kvm_x86_call(vcpu_load)(vcpu, cpu);
4999 
5000 	/* Save host pkru register if supported */
5001 	vcpu->arch.host_pkru = read_pkru();
5002 
5003 	/* Apply any externally detected TSC adjustments (due to suspend) */
5004 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5005 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5006 		vcpu->arch.tsc_offset_adjustment = 0;
5007 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5008 	}
5009 
5010 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5011 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5012 				rdtsc() - vcpu->arch.last_host_tsc;
5013 		if (tsc_delta < 0)
5014 			mark_tsc_unstable("KVM discovered backwards TSC");
5015 
5016 		if (kvm_check_tsc_unstable()) {
5017 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5018 						vcpu->arch.last_guest_tsc);
5019 			kvm_vcpu_write_tsc_offset(vcpu, offset);
5020 			if (!vcpu->arch.guest_tsc_protected)
5021 				vcpu->arch.tsc_catchup = 1;
5022 		}
5023 
5024 		if (kvm_lapic_hv_timer_in_use(vcpu))
5025 			kvm_lapic_restart_hv_timer(vcpu);
5026 
5027 		/*
5028 		 * On a host with synchronized TSC, there is no need to update
5029 		 * kvmclock on vcpu->cpu migration
5030 		 */
5031 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5032 			kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5033 		if (vcpu->cpu != cpu)
5034 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5035 		vcpu->cpu = cpu;
5036 	}
5037 
5038 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5039 }
5040 
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5041 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5042 {
5043 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5044 	struct kvm_steal_time __user *st;
5045 	struct kvm_memslots *slots;
5046 	static const u8 preempted = KVM_VCPU_PREEMPTED;
5047 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5048 
5049 	/*
5050 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
5051 	 * an instruction boundary and will not trigger guest emulation of any
5052 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
5053 	 * when this is true, for example allowing the vCPU to be marked
5054 	 * preempted if and only if the VM-Exit was due to a host interrupt.
5055 	 */
5056 	if (!vcpu->arch.at_instruction_boundary) {
5057 		vcpu->stat.preemption_other++;
5058 		return;
5059 	}
5060 
5061 	vcpu->stat.preemption_reported++;
5062 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5063 		return;
5064 
5065 	if (vcpu->arch.st.preempted)
5066 		return;
5067 
5068 	/* This happens on process exit */
5069 	if (unlikely(current->mm != vcpu->kvm->mm))
5070 		return;
5071 
5072 	slots = kvm_memslots(vcpu->kvm);
5073 
5074 	if (unlikely(slots->generation != ghc->generation ||
5075 		     gpa != ghc->gpa ||
5076 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5077 		return;
5078 
5079 	st = (struct kvm_steal_time __user *)ghc->hva;
5080 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5081 
5082 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5083 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5084 
5085 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5086 }
5087 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5088 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5089 {
5090 	int idx;
5091 
5092 	if (vcpu->preempted) {
5093 		/*
5094 		 * Assume protected guests are in-kernel.  Inefficient yielding
5095 		 * due to false positives is preferable to never yielding due
5096 		 * to false negatives.
5097 		 */
5098 		vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5099 						 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5100 
5101 		/*
5102 		 * Take the srcu lock as memslots will be accessed to check the gfn
5103 		 * cache generation against the memslots generation.
5104 		 */
5105 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5106 		if (kvm_xen_msr_enabled(vcpu->kvm))
5107 			kvm_xen_runstate_set_preempted(vcpu);
5108 		else
5109 			kvm_steal_time_set_preempted(vcpu);
5110 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5111 	}
5112 
5113 	kvm_x86_call(vcpu_put)(vcpu);
5114 	vcpu->arch.last_host_tsc = rdtsc();
5115 }
5116 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5117 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5118 				    struct kvm_lapic_state *s)
5119 {
5120 	kvm_x86_call(sync_pir_to_irr)(vcpu);
5121 
5122 	return kvm_apic_get_state(vcpu, s);
5123 }
5124 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5125 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5126 				    struct kvm_lapic_state *s)
5127 {
5128 	int r;
5129 
5130 	r = kvm_apic_set_state(vcpu, s);
5131 	if (r)
5132 		return r;
5133 	update_cr8_intercept(vcpu);
5134 
5135 	return 0;
5136 }
5137 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5138 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5139 {
5140 	/*
5141 	 * We can accept userspace's request for interrupt injection
5142 	 * as long as we have a place to store the interrupt number.
5143 	 * The actual injection will happen when the CPU is able to
5144 	 * deliver the interrupt.
5145 	 */
5146 	if (kvm_cpu_has_extint(vcpu))
5147 		return false;
5148 
5149 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
5150 	return (!lapic_in_kernel(vcpu) ||
5151 		kvm_apic_accept_pic_intr(vcpu));
5152 }
5153 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5154 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5155 {
5156 	/*
5157 	 * Do not cause an interrupt window exit if an exception
5158 	 * is pending or an event needs reinjection; userspace
5159 	 * might want to inject the interrupt manually using KVM_SET_REGS
5160 	 * or KVM_SET_SREGS.  For that to work, we must be at an
5161 	 * instruction boundary and with no events half-injected.
5162 	 */
5163 	return (kvm_arch_interrupt_allowed(vcpu) &&
5164 		kvm_cpu_accept_dm_intr(vcpu) &&
5165 		!kvm_event_needs_reinjection(vcpu) &&
5166 		!kvm_is_exception_pending(vcpu));
5167 }
5168 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5169 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5170 				    struct kvm_interrupt *irq)
5171 {
5172 	if (irq->irq >= KVM_NR_INTERRUPTS)
5173 		return -EINVAL;
5174 
5175 	if (!irqchip_in_kernel(vcpu->kvm)) {
5176 		kvm_queue_interrupt(vcpu, irq->irq, false);
5177 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5178 		return 0;
5179 	}
5180 
5181 	/*
5182 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5183 	 * fail for in-kernel 8259.
5184 	 */
5185 	if (pic_in_kernel(vcpu->kvm))
5186 		return -ENXIO;
5187 
5188 	if (vcpu->arch.pending_external_vector != -1)
5189 		return -EEXIST;
5190 
5191 	vcpu->arch.pending_external_vector = irq->irq;
5192 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5193 	return 0;
5194 }
5195 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5196 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5197 {
5198 	kvm_inject_nmi(vcpu);
5199 
5200 	return 0;
5201 }
5202 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5203 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5204 					   struct kvm_tpr_access_ctl *tac)
5205 {
5206 	if (tac->flags)
5207 		return -EINVAL;
5208 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
5209 	return 0;
5210 }
5211 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5212 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5213 					u64 mcg_cap)
5214 {
5215 	int r;
5216 	unsigned bank_num = mcg_cap & 0xff, bank;
5217 
5218 	r = -EINVAL;
5219 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5220 		goto out;
5221 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5222 		goto out;
5223 	r = 0;
5224 	vcpu->arch.mcg_cap = mcg_cap;
5225 	/* Init IA32_MCG_CTL to all 1s */
5226 	if (mcg_cap & MCG_CTL_P)
5227 		vcpu->arch.mcg_ctl = ~(u64)0;
5228 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5229 	for (bank = 0; bank < bank_num; bank++) {
5230 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5231 		if (mcg_cap & MCG_CMCI_P)
5232 			vcpu->arch.mci_ctl2_banks[bank] = 0;
5233 	}
5234 
5235 	kvm_apic_after_set_mcg_cap(vcpu);
5236 
5237 	kvm_x86_call(setup_mce)(vcpu);
5238 out:
5239 	return r;
5240 }
5241 
5242 /*
5243  * Validate this is an UCNA (uncorrectable no action) error by checking the
5244  * MCG_STATUS and MCi_STATUS registers:
5245  * - none of the bits for Machine Check Exceptions are set
5246  * - both the VAL (valid) and UC (uncorrectable) bits are set
5247  * MCI_STATUS_PCC - Processor Context Corrupted
5248  * MCI_STATUS_S - Signaled as a Machine Check Exception
5249  * MCI_STATUS_AR - Software recoverable Action Required
5250  */
is_ucna(struct kvm_x86_mce * mce)5251 static bool is_ucna(struct kvm_x86_mce *mce)
5252 {
5253 	return	!mce->mcg_status &&
5254 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5255 		(mce->status & MCI_STATUS_VAL) &&
5256 		(mce->status & MCI_STATUS_UC);
5257 }
5258 
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5259 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5260 {
5261 	u64 mcg_cap = vcpu->arch.mcg_cap;
5262 
5263 	banks[1] = mce->status;
5264 	banks[2] = mce->addr;
5265 	banks[3] = mce->misc;
5266 	vcpu->arch.mcg_status = mce->mcg_status;
5267 
5268 	if (!(mcg_cap & MCG_CMCI_P) ||
5269 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5270 		return 0;
5271 
5272 	if (lapic_in_kernel(vcpu))
5273 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5274 
5275 	return 0;
5276 }
5277 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5278 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5279 				      struct kvm_x86_mce *mce)
5280 {
5281 	u64 mcg_cap = vcpu->arch.mcg_cap;
5282 	unsigned bank_num = mcg_cap & 0xff;
5283 	u64 *banks = vcpu->arch.mce_banks;
5284 
5285 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5286 		return -EINVAL;
5287 
5288 	banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5289 
5290 	if (is_ucna(mce))
5291 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5292 
5293 	/*
5294 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5295 	 * reporting is disabled
5296 	 */
5297 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5298 	    vcpu->arch.mcg_ctl != ~(u64)0)
5299 		return 0;
5300 	/*
5301 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5302 	 * reporting is disabled for the bank
5303 	 */
5304 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5305 		return 0;
5306 	if (mce->status & MCI_STATUS_UC) {
5307 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5308 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5309 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5310 			return 0;
5311 		}
5312 		if (banks[1] & MCI_STATUS_VAL)
5313 			mce->status |= MCI_STATUS_OVER;
5314 		banks[2] = mce->addr;
5315 		banks[3] = mce->misc;
5316 		vcpu->arch.mcg_status = mce->mcg_status;
5317 		banks[1] = mce->status;
5318 		kvm_queue_exception(vcpu, MC_VECTOR);
5319 	} else if (!(banks[1] & MCI_STATUS_VAL)
5320 		   || !(banks[1] & MCI_STATUS_UC)) {
5321 		if (banks[1] & MCI_STATUS_VAL)
5322 			mce->status |= MCI_STATUS_OVER;
5323 		banks[2] = mce->addr;
5324 		banks[3] = mce->misc;
5325 		banks[1] = mce->status;
5326 	} else
5327 		banks[1] |= MCI_STATUS_OVER;
5328 	return 0;
5329 }
5330 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5331 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5332 					       struct kvm_vcpu_events *events)
5333 {
5334 	struct kvm_queued_exception *ex;
5335 
5336 	process_nmi(vcpu);
5337 
5338 #ifdef CONFIG_KVM_SMM
5339 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
5340 		process_smi(vcpu);
5341 #endif
5342 
5343 	/*
5344 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
5345 	 * the only time there can be two queued exceptions is if there's a
5346 	 * non-exiting _injected_ exception, and a pending exiting exception.
5347 	 * In that case, ignore the VM-Exiting exception as it's an extension
5348 	 * of the injected exception.
5349 	 */
5350 	if (vcpu->arch.exception_vmexit.pending &&
5351 	    !vcpu->arch.exception.pending &&
5352 	    !vcpu->arch.exception.injected)
5353 		ex = &vcpu->arch.exception_vmexit;
5354 	else
5355 		ex = &vcpu->arch.exception;
5356 
5357 	/*
5358 	 * In guest mode, payload delivery should be deferred if the exception
5359 	 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5360 	 * intercepts #PF, ditto for DR6 and #DBs.  If the per-VM capability,
5361 	 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5362 	 * propagate the payload and so it cannot be safely deferred.  Deliver
5363 	 * the payload if the capability hasn't been requested.
5364 	 */
5365 	if (!vcpu->kvm->arch.exception_payload_enabled &&
5366 	    ex->pending && ex->has_payload)
5367 		kvm_deliver_exception_payload(vcpu, ex);
5368 
5369 	memset(events, 0, sizeof(*events));
5370 
5371 	/*
5372 	 * The API doesn't provide the instruction length for software
5373 	 * exceptions, so don't report them. As long as the guest RIP
5374 	 * isn't advanced, we should expect to encounter the exception
5375 	 * again.
5376 	 */
5377 	if (!kvm_exception_is_soft(ex->vector)) {
5378 		events->exception.injected = ex->injected;
5379 		events->exception.pending = ex->pending;
5380 		/*
5381 		 * For ABI compatibility, deliberately conflate
5382 		 * pending and injected exceptions when
5383 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5384 		 */
5385 		if (!vcpu->kvm->arch.exception_payload_enabled)
5386 			events->exception.injected |= ex->pending;
5387 	}
5388 	events->exception.nr = ex->vector;
5389 	events->exception.has_error_code = ex->has_error_code;
5390 	events->exception.error_code = ex->error_code;
5391 	events->exception_has_payload = ex->has_payload;
5392 	events->exception_payload = ex->payload;
5393 
5394 	events->interrupt.injected =
5395 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5396 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5397 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5398 
5399 	events->nmi.injected = vcpu->arch.nmi_injected;
5400 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5401 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5402 
5403 	/* events->sipi_vector is never valid when reporting to user space */
5404 
5405 #ifdef CONFIG_KVM_SMM
5406 	events->smi.smm = is_smm(vcpu);
5407 	events->smi.pending = vcpu->arch.smi_pending;
5408 	events->smi.smm_inside_nmi =
5409 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5410 #endif
5411 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5412 
5413 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5414 			 | KVM_VCPUEVENT_VALID_SHADOW
5415 			 | KVM_VCPUEVENT_VALID_SMM);
5416 	if (vcpu->kvm->arch.exception_payload_enabled)
5417 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5418 	if (vcpu->kvm->arch.triple_fault_event) {
5419 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5420 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5421 	}
5422 }
5423 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5424 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5425 					      struct kvm_vcpu_events *events)
5426 {
5427 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5428 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5429 			      | KVM_VCPUEVENT_VALID_SHADOW
5430 			      | KVM_VCPUEVENT_VALID_SMM
5431 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5432 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5433 		return -EINVAL;
5434 
5435 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5436 		if (!vcpu->kvm->arch.exception_payload_enabled)
5437 			return -EINVAL;
5438 		if (events->exception.pending)
5439 			events->exception.injected = 0;
5440 		else
5441 			events->exception_has_payload = 0;
5442 	} else {
5443 		events->exception.pending = 0;
5444 		events->exception_has_payload = 0;
5445 	}
5446 
5447 	if ((events->exception.injected || events->exception.pending) &&
5448 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5449 		return -EINVAL;
5450 
5451 	/* INITs are latched while in SMM */
5452 	if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5453 	    (events->smi.smm || events->smi.pending) &&
5454 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5455 		return -EINVAL;
5456 
5457 	process_nmi(vcpu);
5458 
5459 	/*
5460 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5461 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5462 	 * pending exceptions, already-injected exceptions are not subject to
5463 	 * intercpetion.  Note, userspace that conflates pending and injected
5464 	 * is hosed, and will incorrectly convert an injected exception into a
5465 	 * pending exception, which in turn may cause a spurious VM-Exit.
5466 	 */
5467 	vcpu->arch.exception_from_userspace = events->exception.pending;
5468 
5469 	vcpu->arch.exception_vmexit.pending = false;
5470 
5471 	vcpu->arch.exception.injected = events->exception.injected;
5472 	vcpu->arch.exception.pending = events->exception.pending;
5473 	vcpu->arch.exception.vector = events->exception.nr;
5474 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5475 	vcpu->arch.exception.error_code = events->exception.error_code;
5476 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5477 	vcpu->arch.exception.payload = events->exception_payload;
5478 
5479 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5480 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5481 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5482 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5483 		kvm_x86_call(set_interrupt_shadow)(vcpu,
5484 						   events->interrupt.shadow);
5485 
5486 	vcpu->arch.nmi_injected = events->nmi.injected;
5487 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5488 		vcpu->arch.nmi_pending = 0;
5489 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5490 		if (events->nmi.pending)
5491 			kvm_make_request(KVM_REQ_NMI, vcpu);
5492 	}
5493 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5494 
5495 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5496 	    lapic_in_kernel(vcpu))
5497 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5498 
5499 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5500 #ifdef CONFIG_KVM_SMM
5501 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5502 			kvm_leave_nested(vcpu);
5503 			kvm_smm_changed(vcpu, events->smi.smm);
5504 		}
5505 
5506 		vcpu->arch.smi_pending = events->smi.pending;
5507 
5508 		if (events->smi.smm) {
5509 			if (events->smi.smm_inside_nmi)
5510 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5511 			else
5512 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5513 		}
5514 
5515 #else
5516 		if (events->smi.smm || events->smi.pending ||
5517 		    events->smi.smm_inside_nmi)
5518 			return -EINVAL;
5519 #endif
5520 
5521 		if (lapic_in_kernel(vcpu)) {
5522 			if (events->smi.latched_init)
5523 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5524 			else
5525 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5526 		}
5527 	}
5528 
5529 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5530 		if (!vcpu->kvm->arch.triple_fault_event)
5531 			return -EINVAL;
5532 		if (events->triple_fault.pending)
5533 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5534 		else
5535 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5536 	}
5537 
5538 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5539 
5540 	return 0;
5541 }
5542 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5543 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5544 					    struct kvm_debugregs *dbgregs)
5545 {
5546 	unsigned int i;
5547 
5548 	if (vcpu->kvm->arch.has_protected_state &&
5549 	    vcpu->arch.guest_state_protected)
5550 		return -EINVAL;
5551 
5552 	memset(dbgregs, 0, sizeof(*dbgregs));
5553 
5554 	BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5555 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5556 		dbgregs->db[i] = vcpu->arch.db[i];
5557 
5558 	dbgregs->dr6 = vcpu->arch.dr6;
5559 	dbgregs->dr7 = vcpu->arch.dr7;
5560 	return 0;
5561 }
5562 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5563 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5564 					    struct kvm_debugregs *dbgregs)
5565 {
5566 	unsigned int i;
5567 
5568 	if (vcpu->kvm->arch.has_protected_state &&
5569 	    vcpu->arch.guest_state_protected)
5570 		return -EINVAL;
5571 
5572 	if (dbgregs->flags)
5573 		return -EINVAL;
5574 
5575 	if (!kvm_dr6_valid(dbgregs->dr6))
5576 		return -EINVAL;
5577 	if (!kvm_dr7_valid(dbgregs->dr7))
5578 		return -EINVAL;
5579 
5580 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5581 		vcpu->arch.db[i] = dbgregs->db[i];
5582 
5583 	kvm_update_dr0123(vcpu);
5584 	vcpu->arch.dr6 = dbgregs->dr6;
5585 	vcpu->arch.dr7 = dbgregs->dr7;
5586 	kvm_update_dr7(vcpu);
5587 
5588 	return 0;
5589 }
5590 
5591 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5592 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5593 					 u8 *state, unsigned int size)
5594 {
5595 	/*
5596 	 * Only copy state for features that are enabled for the guest.  The
5597 	 * state itself isn't problematic, but setting bits in the header for
5598 	 * features that are supported in *this* host but not exposed to the
5599 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5600 	 * compatible host without the features that are NOT exposed to the
5601 	 * guest.
5602 	 *
5603 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5604 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5605 	 * supported by the host.
5606 	 */
5607 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5608 			     XFEATURE_MASK_FPSSE;
5609 
5610 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5611 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5612 
5613 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5614 				       supported_xcr0, vcpu->arch.pkru);
5615 	return 0;
5616 }
5617 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5618 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5619 					struct kvm_xsave *guest_xsave)
5620 {
5621 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5622 					     sizeof(guest_xsave->region));
5623 }
5624 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5625 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5626 					struct kvm_xsave *guest_xsave)
5627 {
5628 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5629 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5630 
5631 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5632 					      guest_xsave->region,
5633 					      kvm_caps.supported_xcr0,
5634 					      &vcpu->arch.pkru);
5635 }
5636 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5637 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5638 				       struct kvm_xcrs *guest_xcrs)
5639 {
5640 	if (vcpu->kvm->arch.has_protected_state &&
5641 	    vcpu->arch.guest_state_protected)
5642 		return -EINVAL;
5643 
5644 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5645 		guest_xcrs->nr_xcrs = 0;
5646 		return 0;
5647 	}
5648 
5649 	guest_xcrs->nr_xcrs = 1;
5650 	guest_xcrs->flags = 0;
5651 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5652 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5653 	return 0;
5654 }
5655 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5656 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5657 				       struct kvm_xcrs *guest_xcrs)
5658 {
5659 	int i, r = 0;
5660 
5661 	if (vcpu->kvm->arch.has_protected_state &&
5662 	    vcpu->arch.guest_state_protected)
5663 		return -EINVAL;
5664 
5665 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5666 		return -EINVAL;
5667 
5668 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5669 		return -EINVAL;
5670 
5671 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5672 		/* Only support XCR0 currently */
5673 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5674 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5675 				guest_xcrs->xcrs[i].value);
5676 			break;
5677 		}
5678 	if (r)
5679 		r = -EINVAL;
5680 	return r;
5681 }
5682 
5683 /*
5684  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5685  * stopped by the hypervisor.  This function will be called from the host only.
5686  * EINVAL is returned when the host attempts to set the flag for a guest that
5687  * does not support pv clocks.
5688  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5689 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5690 {
5691 	if (!vcpu->arch.pv_time.active)
5692 		return -EINVAL;
5693 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5694 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5695 	return 0;
5696 }
5697 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5698 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5699 				 struct kvm_device_attr *attr)
5700 {
5701 	int r;
5702 
5703 	switch (attr->attr) {
5704 	case KVM_VCPU_TSC_OFFSET:
5705 		r = 0;
5706 		break;
5707 	default:
5708 		r = -ENXIO;
5709 	}
5710 
5711 	return r;
5712 }
5713 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5714 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5715 				 struct kvm_device_attr *attr)
5716 {
5717 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5718 	int r;
5719 
5720 	switch (attr->attr) {
5721 	case KVM_VCPU_TSC_OFFSET:
5722 		r = -EFAULT;
5723 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5724 			break;
5725 		r = 0;
5726 		break;
5727 	default:
5728 		r = -ENXIO;
5729 	}
5730 
5731 	return r;
5732 }
5733 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5734 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5735 				 struct kvm_device_attr *attr)
5736 {
5737 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5738 	struct kvm *kvm = vcpu->kvm;
5739 	int r;
5740 
5741 	switch (attr->attr) {
5742 	case KVM_VCPU_TSC_OFFSET: {
5743 		u64 offset, tsc, ns;
5744 		unsigned long flags;
5745 		bool matched;
5746 
5747 		r = -EFAULT;
5748 		if (get_user(offset, uaddr))
5749 			break;
5750 
5751 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5752 
5753 		matched = (vcpu->arch.virtual_tsc_khz &&
5754 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5755 			   kvm->arch.last_tsc_offset == offset);
5756 
5757 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5758 		ns = get_kvmclock_base_ns();
5759 
5760 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5761 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5762 
5763 		r = 0;
5764 		break;
5765 	}
5766 	default:
5767 		r = -ENXIO;
5768 	}
5769 
5770 	return r;
5771 }
5772 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5773 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5774 				      unsigned int ioctl,
5775 				      void __user *argp)
5776 {
5777 	struct kvm_device_attr attr;
5778 	int r;
5779 
5780 	if (copy_from_user(&attr, argp, sizeof(attr)))
5781 		return -EFAULT;
5782 
5783 	if (attr.group != KVM_VCPU_TSC_CTRL)
5784 		return -ENXIO;
5785 
5786 	switch (ioctl) {
5787 	case KVM_HAS_DEVICE_ATTR:
5788 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5789 		break;
5790 	case KVM_GET_DEVICE_ATTR:
5791 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5792 		break;
5793 	case KVM_SET_DEVICE_ATTR:
5794 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5795 		break;
5796 	}
5797 
5798 	return r;
5799 }
5800 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5801 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5802 				     struct kvm_enable_cap *cap)
5803 {
5804 	if (cap->flags)
5805 		return -EINVAL;
5806 
5807 	switch (cap->cap) {
5808 #ifdef CONFIG_KVM_HYPERV
5809 	case KVM_CAP_HYPERV_SYNIC2:
5810 		if (cap->args[0])
5811 			return -EINVAL;
5812 		fallthrough;
5813 
5814 	case KVM_CAP_HYPERV_SYNIC:
5815 		if (!irqchip_in_kernel(vcpu->kvm))
5816 			return -EINVAL;
5817 		return kvm_hv_activate_synic(vcpu, cap->cap ==
5818 					     KVM_CAP_HYPERV_SYNIC2);
5819 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5820 		{
5821 			int r;
5822 			uint16_t vmcs_version;
5823 			void __user *user_ptr;
5824 
5825 			if (!kvm_x86_ops.nested_ops->enable_evmcs)
5826 				return -ENOTTY;
5827 			r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5828 			if (!r) {
5829 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
5830 				if (copy_to_user(user_ptr, &vmcs_version,
5831 						 sizeof(vmcs_version)))
5832 					r = -EFAULT;
5833 			}
5834 			return r;
5835 		}
5836 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5837 		if (!kvm_x86_ops.enable_l2_tlb_flush)
5838 			return -ENOTTY;
5839 
5840 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
5841 
5842 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
5843 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5844 #endif
5845 
5846 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5847 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
5848 		return 0;
5849 	default:
5850 		return -EINVAL;
5851 	}
5852 }
5853 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5854 long kvm_arch_vcpu_ioctl(struct file *filp,
5855 			 unsigned int ioctl, unsigned long arg)
5856 {
5857 	struct kvm_vcpu *vcpu = filp->private_data;
5858 	void __user *argp = (void __user *)arg;
5859 	int r;
5860 	union {
5861 		struct kvm_sregs2 *sregs2;
5862 		struct kvm_lapic_state *lapic;
5863 		struct kvm_xsave *xsave;
5864 		struct kvm_xcrs *xcrs;
5865 		void *buffer;
5866 	} u;
5867 
5868 	vcpu_load(vcpu);
5869 
5870 	u.buffer = NULL;
5871 	switch (ioctl) {
5872 	case KVM_GET_LAPIC: {
5873 		r = -EINVAL;
5874 		if (!lapic_in_kernel(vcpu))
5875 			goto out;
5876 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
5877 
5878 		r = -ENOMEM;
5879 		if (!u.lapic)
5880 			goto out;
5881 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5882 		if (r)
5883 			goto out;
5884 		r = -EFAULT;
5885 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5886 			goto out;
5887 		r = 0;
5888 		break;
5889 	}
5890 	case KVM_SET_LAPIC: {
5891 		r = -EINVAL;
5892 		if (!lapic_in_kernel(vcpu))
5893 			goto out;
5894 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
5895 		if (IS_ERR(u.lapic)) {
5896 			r = PTR_ERR(u.lapic);
5897 			goto out_nofree;
5898 		}
5899 
5900 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5901 		break;
5902 	}
5903 	case KVM_INTERRUPT: {
5904 		struct kvm_interrupt irq;
5905 
5906 		r = -EFAULT;
5907 		if (copy_from_user(&irq, argp, sizeof(irq)))
5908 			goto out;
5909 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5910 		break;
5911 	}
5912 	case KVM_NMI: {
5913 		r = kvm_vcpu_ioctl_nmi(vcpu);
5914 		break;
5915 	}
5916 	case KVM_SMI: {
5917 		r = kvm_inject_smi(vcpu);
5918 		break;
5919 	}
5920 	case KVM_SET_CPUID: {
5921 		struct kvm_cpuid __user *cpuid_arg = argp;
5922 		struct kvm_cpuid cpuid;
5923 
5924 		r = -EFAULT;
5925 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5926 			goto out;
5927 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5928 		break;
5929 	}
5930 	case KVM_SET_CPUID2: {
5931 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5932 		struct kvm_cpuid2 cpuid;
5933 
5934 		r = -EFAULT;
5935 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5936 			goto out;
5937 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5938 					      cpuid_arg->entries);
5939 		break;
5940 	}
5941 	case KVM_GET_CPUID2: {
5942 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5943 		struct kvm_cpuid2 cpuid;
5944 
5945 		r = -EFAULT;
5946 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5947 			goto out;
5948 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5949 					      cpuid_arg->entries);
5950 		if (r)
5951 			goto out;
5952 		r = -EFAULT;
5953 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5954 			goto out;
5955 		r = 0;
5956 		break;
5957 	}
5958 	case KVM_GET_MSRS: {
5959 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5960 		r = msr_io(vcpu, argp, do_get_msr, 1);
5961 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5962 		break;
5963 	}
5964 	case KVM_SET_MSRS: {
5965 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5966 		r = msr_io(vcpu, argp, do_set_msr, 0);
5967 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5968 		break;
5969 	}
5970 	case KVM_TPR_ACCESS_REPORTING: {
5971 		struct kvm_tpr_access_ctl tac;
5972 
5973 		r = -EFAULT;
5974 		if (copy_from_user(&tac, argp, sizeof(tac)))
5975 			goto out;
5976 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5977 		if (r)
5978 			goto out;
5979 		r = -EFAULT;
5980 		if (copy_to_user(argp, &tac, sizeof(tac)))
5981 			goto out;
5982 		r = 0;
5983 		break;
5984 	};
5985 	case KVM_SET_VAPIC_ADDR: {
5986 		struct kvm_vapic_addr va;
5987 		int idx;
5988 
5989 		r = -EINVAL;
5990 		if (!lapic_in_kernel(vcpu))
5991 			goto out;
5992 		r = -EFAULT;
5993 		if (copy_from_user(&va, argp, sizeof(va)))
5994 			goto out;
5995 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5996 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5997 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5998 		break;
5999 	}
6000 	case KVM_X86_SETUP_MCE: {
6001 		u64 mcg_cap;
6002 
6003 		r = -EFAULT;
6004 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6005 			goto out;
6006 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6007 		break;
6008 	}
6009 	case KVM_X86_SET_MCE: {
6010 		struct kvm_x86_mce mce;
6011 
6012 		r = -EFAULT;
6013 		if (copy_from_user(&mce, argp, sizeof(mce)))
6014 			goto out;
6015 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6016 		break;
6017 	}
6018 	case KVM_GET_VCPU_EVENTS: {
6019 		struct kvm_vcpu_events events;
6020 
6021 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6022 
6023 		r = -EFAULT;
6024 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6025 			break;
6026 		r = 0;
6027 		break;
6028 	}
6029 	case KVM_SET_VCPU_EVENTS: {
6030 		struct kvm_vcpu_events events;
6031 
6032 		r = -EFAULT;
6033 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6034 			break;
6035 
6036 		kvm_vcpu_srcu_read_lock(vcpu);
6037 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6038 		kvm_vcpu_srcu_read_unlock(vcpu);
6039 		break;
6040 	}
6041 	case KVM_GET_DEBUGREGS: {
6042 		struct kvm_debugregs dbgregs;
6043 
6044 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6045 		if (r < 0)
6046 			break;
6047 
6048 		r = -EFAULT;
6049 		if (copy_to_user(argp, &dbgregs,
6050 				 sizeof(struct kvm_debugregs)))
6051 			break;
6052 		r = 0;
6053 		break;
6054 	}
6055 	case KVM_SET_DEBUGREGS: {
6056 		struct kvm_debugregs dbgregs;
6057 
6058 		r = -EFAULT;
6059 		if (copy_from_user(&dbgregs, argp,
6060 				   sizeof(struct kvm_debugregs)))
6061 			break;
6062 
6063 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6064 		break;
6065 	}
6066 	case KVM_GET_XSAVE: {
6067 		r = -EINVAL;
6068 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6069 			break;
6070 
6071 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6072 		r = -ENOMEM;
6073 		if (!u.xsave)
6074 			break;
6075 
6076 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6077 		if (r < 0)
6078 			break;
6079 
6080 		r = -EFAULT;
6081 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6082 			break;
6083 		r = 0;
6084 		break;
6085 	}
6086 	case KVM_SET_XSAVE: {
6087 		int size = vcpu->arch.guest_fpu.uabi_size;
6088 
6089 		u.xsave = memdup_user(argp, size);
6090 		if (IS_ERR(u.xsave)) {
6091 			r = PTR_ERR(u.xsave);
6092 			goto out_nofree;
6093 		}
6094 
6095 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6096 		break;
6097 	}
6098 
6099 	case KVM_GET_XSAVE2: {
6100 		int size = vcpu->arch.guest_fpu.uabi_size;
6101 
6102 		u.xsave = kzalloc(size, GFP_KERNEL);
6103 		r = -ENOMEM;
6104 		if (!u.xsave)
6105 			break;
6106 
6107 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6108 		if (r < 0)
6109 			break;
6110 
6111 		r = -EFAULT;
6112 		if (copy_to_user(argp, u.xsave, size))
6113 			break;
6114 
6115 		r = 0;
6116 		break;
6117 	}
6118 
6119 	case KVM_GET_XCRS: {
6120 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6121 		r = -ENOMEM;
6122 		if (!u.xcrs)
6123 			break;
6124 
6125 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6126 		if (r < 0)
6127 			break;
6128 
6129 		r = -EFAULT;
6130 		if (copy_to_user(argp, u.xcrs,
6131 				 sizeof(struct kvm_xcrs)))
6132 			break;
6133 		r = 0;
6134 		break;
6135 	}
6136 	case KVM_SET_XCRS: {
6137 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6138 		if (IS_ERR(u.xcrs)) {
6139 			r = PTR_ERR(u.xcrs);
6140 			goto out_nofree;
6141 		}
6142 
6143 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6144 		break;
6145 	}
6146 	case KVM_SET_TSC_KHZ: {
6147 		u32 user_tsc_khz;
6148 
6149 		r = -EINVAL;
6150 		user_tsc_khz = (u32)arg;
6151 
6152 		if (kvm_caps.has_tsc_control &&
6153 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6154 			goto out;
6155 
6156 		if (user_tsc_khz == 0)
6157 			user_tsc_khz = tsc_khz;
6158 
6159 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6160 			r = 0;
6161 
6162 		goto out;
6163 	}
6164 	case KVM_GET_TSC_KHZ: {
6165 		r = vcpu->arch.virtual_tsc_khz;
6166 		goto out;
6167 	}
6168 	case KVM_KVMCLOCK_CTRL: {
6169 		r = kvm_set_guest_paused(vcpu);
6170 		goto out;
6171 	}
6172 	case KVM_ENABLE_CAP: {
6173 		struct kvm_enable_cap cap;
6174 
6175 		r = -EFAULT;
6176 		if (copy_from_user(&cap, argp, sizeof(cap)))
6177 			goto out;
6178 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6179 		break;
6180 	}
6181 	case KVM_GET_NESTED_STATE: {
6182 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6183 		u32 user_data_size;
6184 
6185 		r = -EINVAL;
6186 		if (!kvm_x86_ops.nested_ops->get_state)
6187 			break;
6188 
6189 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6190 		r = -EFAULT;
6191 		if (get_user(user_data_size, &user_kvm_nested_state->size))
6192 			break;
6193 
6194 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6195 						     user_data_size);
6196 		if (r < 0)
6197 			break;
6198 
6199 		if (r > user_data_size) {
6200 			if (put_user(r, &user_kvm_nested_state->size))
6201 				r = -EFAULT;
6202 			else
6203 				r = -E2BIG;
6204 			break;
6205 		}
6206 
6207 		r = 0;
6208 		break;
6209 	}
6210 	case KVM_SET_NESTED_STATE: {
6211 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6212 		struct kvm_nested_state kvm_state;
6213 		int idx;
6214 
6215 		r = -EINVAL;
6216 		if (!kvm_x86_ops.nested_ops->set_state)
6217 			break;
6218 
6219 		r = -EFAULT;
6220 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6221 			break;
6222 
6223 		r = -EINVAL;
6224 		if (kvm_state.size < sizeof(kvm_state))
6225 			break;
6226 
6227 		if (kvm_state.flags &
6228 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6229 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6230 		      | KVM_STATE_NESTED_GIF_SET))
6231 			break;
6232 
6233 		/* nested_run_pending implies guest_mode.  */
6234 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6235 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6236 			break;
6237 
6238 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6239 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6240 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6241 		break;
6242 	}
6243 #ifdef CONFIG_KVM_HYPERV
6244 	case KVM_GET_SUPPORTED_HV_CPUID:
6245 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6246 		break;
6247 #endif
6248 #ifdef CONFIG_KVM_XEN
6249 	case KVM_XEN_VCPU_GET_ATTR: {
6250 		struct kvm_xen_vcpu_attr xva;
6251 
6252 		r = -EFAULT;
6253 		if (copy_from_user(&xva, argp, sizeof(xva)))
6254 			goto out;
6255 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6256 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6257 			r = -EFAULT;
6258 		break;
6259 	}
6260 	case KVM_XEN_VCPU_SET_ATTR: {
6261 		struct kvm_xen_vcpu_attr xva;
6262 
6263 		r = -EFAULT;
6264 		if (copy_from_user(&xva, argp, sizeof(xva)))
6265 			goto out;
6266 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6267 		break;
6268 	}
6269 #endif
6270 	case KVM_GET_SREGS2: {
6271 		r = -EINVAL;
6272 		if (vcpu->kvm->arch.has_protected_state &&
6273 		    vcpu->arch.guest_state_protected)
6274 			goto out;
6275 
6276 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6277 		r = -ENOMEM;
6278 		if (!u.sregs2)
6279 			goto out;
6280 		__get_sregs2(vcpu, u.sregs2);
6281 		r = -EFAULT;
6282 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6283 			goto out;
6284 		r = 0;
6285 		break;
6286 	}
6287 	case KVM_SET_SREGS2: {
6288 		r = -EINVAL;
6289 		if (vcpu->kvm->arch.has_protected_state &&
6290 		    vcpu->arch.guest_state_protected)
6291 			goto out;
6292 
6293 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6294 		if (IS_ERR(u.sregs2)) {
6295 			r = PTR_ERR(u.sregs2);
6296 			u.sregs2 = NULL;
6297 			goto out;
6298 		}
6299 		r = __set_sregs2(vcpu, u.sregs2);
6300 		break;
6301 	}
6302 	case KVM_HAS_DEVICE_ATTR:
6303 	case KVM_GET_DEVICE_ATTR:
6304 	case KVM_SET_DEVICE_ATTR:
6305 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6306 		break;
6307 	default:
6308 		r = -EINVAL;
6309 	}
6310 out:
6311 	kfree(u.buffer);
6312 out_nofree:
6313 	vcpu_put(vcpu);
6314 	return r;
6315 }
6316 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6317 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6318 {
6319 	return VM_FAULT_SIGBUS;
6320 }
6321 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6322 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6323 {
6324 	int ret;
6325 
6326 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
6327 		return -EINVAL;
6328 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6329 	return ret;
6330 }
6331 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6332 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6333 					      u64 ident_addr)
6334 {
6335 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6336 }
6337 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6338 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6339 					 unsigned long kvm_nr_mmu_pages)
6340 {
6341 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6342 		return -EINVAL;
6343 
6344 	mutex_lock(&kvm->slots_lock);
6345 
6346 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6347 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6348 
6349 	mutex_unlock(&kvm->slots_lock);
6350 	return 0;
6351 }
6352 
kvm_vm_ioctl_get_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6353 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6354 {
6355 	struct kvm_pic *pic = kvm->arch.vpic;
6356 	int r;
6357 
6358 	r = 0;
6359 	switch (chip->chip_id) {
6360 	case KVM_IRQCHIP_PIC_MASTER:
6361 		memcpy(&chip->chip.pic, &pic->pics[0],
6362 			sizeof(struct kvm_pic_state));
6363 		break;
6364 	case KVM_IRQCHIP_PIC_SLAVE:
6365 		memcpy(&chip->chip.pic, &pic->pics[1],
6366 			sizeof(struct kvm_pic_state));
6367 		break;
6368 	case KVM_IRQCHIP_IOAPIC:
6369 		kvm_get_ioapic(kvm, &chip->chip.ioapic);
6370 		break;
6371 	default:
6372 		r = -EINVAL;
6373 		break;
6374 	}
6375 	return r;
6376 }
6377 
kvm_vm_ioctl_set_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6378 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6379 {
6380 	struct kvm_pic *pic = kvm->arch.vpic;
6381 	int r;
6382 
6383 	r = 0;
6384 	switch (chip->chip_id) {
6385 	case KVM_IRQCHIP_PIC_MASTER:
6386 		spin_lock(&pic->lock);
6387 		memcpy(&pic->pics[0], &chip->chip.pic,
6388 			sizeof(struct kvm_pic_state));
6389 		spin_unlock(&pic->lock);
6390 		break;
6391 	case KVM_IRQCHIP_PIC_SLAVE:
6392 		spin_lock(&pic->lock);
6393 		memcpy(&pic->pics[1], &chip->chip.pic,
6394 			sizeof(struct kvm_pic_state));
6395 		spin_unlock(&pic->lock);
6396 		break;
6397 	case KVM_IRQCHIP_IOAPIC:
6398 		kvm_set_ioapic(kvm, &chip->chip.ioapic);
6399 		break;
6400 	default:
6401 		r = -EINVAL;
6402 		break;
6403 	}
6404 	kvm_pic_update_irq(pic);
6405 	return r;
6406 }
6407 
kvm_vm_ioctl_get_pit(struct kvm * kvm,struct kvm_pit_state * ps)6408 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6409 {
6410 	struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6411 
6412 	BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6413 
6414 	mutex_lock(&kps->lock);
6415 	memcpy(ps, &kps->channels, sizeof(*ps));
6416 	mutex_unlock(&kps->lock);
6417 	return 0;
6418 }
6419 
kvm_vm_ioctl_set_pit(struct kvm * kvm,struct kvm_pit_state * ps)6420 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6421 {
6422 	int i;
6423 	struct kvm_pit *pit = kvm->arch.vpit;
6424 
6425 	mutex_lock(&pit->pit_state.lock);
6426 	memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6427 	for (i = 0; i < 3; i++)
6428 		kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6429 	mutex_unlock(&pit->pit_state.lock);
6430 	return 0;
6431 }
6432 
kvm_vm_ioctl_get_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6433 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6434 {
6435 	mutex_lock(&kvm->arch.vpit->pit_state.lock);
6436 	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6437 		sizeof(ps->channels));
6438 	ps->flags = kvm->arch.vpit->pit_state.flags;
6439 	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6440 	memset(&ps->reserved, 0, sizeof(ps->reserved));
6441 	return 0;
6442 }
6443 
kvm_vm_ioctl_set_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6444 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6445 {
6446 	int start = 0;
6447 	int i;
6448 	u32 prev_legacy, cur_legacy;
6449 	struct kvm_pit *pit = kvm->arch.vpit;
6450 
6451 	mutex_lock(&pit->pit_state.lock);
6452 	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6453 	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6454 	if (!prev_legacy && cur_legacy)
6455 		start = 1;
6456 	memcpy(&pit->pit_state.channels, &ps->channels,
6457 	       sizeof(pit->pit_state.channels));
6458 	pit->pit_state.flags = ps->flags;
6459 	for (i = 0; i < 3; i++)
6460 		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6461 				   start && i == 0);
6462 	mutex_unlock(&pit->pit_state.lock);
6463 	return 0;
6464 }
6465 
kvm_vm_ioctl_reinject(struct kvm * kvm,struct kvm_reinject_control * control)6466 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6467 				 struct kvm_reinject_control *control)
6468 {
6469 	struct kvm_pit *pit = kvm->arch.vpit;
6470 
6471 	/* pit->pit_state.lock was overloaded to prevent userspace from getting
6472 	 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6473 	 * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
6474 	 */
6475 	mutex_lock(&pit->pit_state.lock);
6476 	kvm_pit_set_reinject(pit, control->pit_reinject);
6477 	mutex_unlock(&pit->pit_state.lock);
6478 
6479 	return 0;
6480 }
6481 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6482 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6483 {
6484 
6485 	/*
6486 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6487 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6488 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6489 	 * VM-Exit.
6490 	 */
6491 	struct kvm_vcpu *vcpu;
6492 	unsigned long i;
6493 
6494 	if (!kvm_x86_ops.cpu_dirty_log_size)
6495 		return;
6496 
6497 	kvm_for_each_vcpu(i, vcpu, kvm)
6498 		kvm_vcpu_kick(vcpu);
6499 }
6500 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_event,bool line_status)6501 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6502 			bool line_status)
6503 {
6504 	if (!irqchip_in_kernel(kvm))
6505 		return -ENXIO;
6506 
6507 	irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6508 					irq_event->irq, irq_event->level,
6509 					line_status);
6510 	return 0;
6511 }
6512 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6513 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6514 			    struct kvm_enable_cap *cap)
6515 {
6516 	int r;
6517 
6518 	if (cap->flags)
6519 		return -EINVAL;
6520 
6521 	switch (cap->cap) {
6522 	case KVM_CAP_DISABLE_QUIRKS2:
6523 		r = -EINVAL;
6524 		if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6525 			break;
6526 		fallthrough;
6527 	case KVM_CAP_DISABLE_QUIRKS:
6528 		kvm->arch.disabled_quirks = cap->args[0];
6529 		r = 0;
6530 		break;
6531 	case KVM_CAP_SPLIT_IRQCHIP: {
6532 		mutex_lock(&kvm->lock);
6533 		r = -EINVAL;
6534 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6535 			goto split_irqchip_unlock;
6536 		r = -EEXIST;
6537 		if (irqchip_in_kernel(kvm))
6538 			goto split_irqchip_unlock;
6539 		if (kvm->created_vcpus)
6540 			goto split_irqchip_unlock;
6541 		/* Pairs with irqchip_in_kernel. */
6542 		smp_wmb();
6543 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6544 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6545 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6546 		r = 0;
6547 split_irqchip_unlock:
6548 		mutex_unlock(&kvm->lock);
6549 		break;
6550 	}
6551 	case KVM_CAP_X2APIC_API:
6552 		r = -EINVAL;
6553 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6554 			break;
6555 
6556 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6557 			kvm->arch.x2apic_format = true;
6558 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6559 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6560 
6561 		r = 0;
6562 		break;
6563 	case KVM_CAP_X86_DISABLE_EXITS:
6564 		r = -EINVAL;
6565 		if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6566 			break;
6567 
6568 		mutex_lock(&kvm->lock);
6569 		if (kvm->created_vcpus)
6570 			goto disable_exits_unlock;
6571 
6572 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6573 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6574 
6575 		if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6576 		    cpu_smt_possible() &&
6577 		    (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6578 			pr_warn_once(SMT_RSB_MSG);
6579 
6580 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6581 			kvm->arch.pause_in_guest = true;
6582 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT)
6583 			kvm->arch.mwait_in_guest = true;
6584 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6585 			kvm->arch.hlt_in_guest = true;
6586 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6587 			kvm->arch.cstate_in_guest = true;
6588 		r = 0;
6589 disable_exits_unlock:
6590 		mutex_unlock(&kvm->lock);
6591 		break;
6592 	case KVM_CAP_MSR_PLATFORM_INFO:
6593 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6594 		r = 0;
6595 		break;
6596 	case KVM_CAP_EXCEPTION_PAYLOAD:
6597 		kvm->arch.exception_payload_enabled = cap->args[0];
6598 		r = 0;
6599 		break;
6600 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6601 		kvm->arch.triple_fault_event = cap->args[0];
6602 		r = 0;
6603 		break;
6604 	case KVM_CAP_X86_USER_SPACE_MSR:
6605 		r = -EINVAL;
6606 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6607 			break;
6608 		kvm->arch.user_space_msr_mask = cap->args[0];
6609 		r = 0;
6610 		break;
6611 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6612 		r = -EINVAL;
6613 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6614 			break;
6615 
6616 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6617 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6618 			break;
6619 
6620 		if (kvm_caps.has_bus_lock_exit &&
6621 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6622 			kvm->arch.bus_lock_detection_enabled = true;
6623 		r = 0;
6624 		break;
6625 #ifdef CONFIG_X86_SGX_KVM
6626 	case KVM_CAP_SGX_ATTRIBUTE: {
6627 		unsigned long allowed_attributes = 0;
6628 
6629 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6630 		if (r)
6631 			break;
6632 
6633 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6634 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6635 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6636 			kvm->arch.sgx_provisioning_allowed = true;
6637 		else
6638 			r = -EINVAL;
6639 		break;
6640 	}
6641 #endif
6642 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6643 		r = -EINVAL;
6644 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6645 			break;
6646 
6647 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6648 		break;
6649 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6650 		r = -EINVAL;
6651 		if (!kvm_x86_ops.vm_move_enc_context_from)
6652 			break;
6653 
6654 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6655 		break;
6656 	case KVM_CAP_EXIT_HYPERCALL:
6657 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6658 			r = -EINVAL;
6659 			break;
6660 		}
6661 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6662 		r = 0;
6663 		break;
6664 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6665 		r = -EINVAL;
6666 		if (cap->args[0] & ~1)
6667 			break;
6668 		kvm->arch.exit_on_emulation_error = cap->args[0];
6669 		r = 0;
6670 		break;
6671 	case KVM_CAP_PMU_CAPABILITY:
6672 		r = -EINVAL;
6673 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6674 			break;
6675 
6676 		mutex_lock(&kvm->lock);
6677 		if (!kvm->created_vcpus) {
6678 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6679 			r = 0;
6680 		}
6681 		mutex_unlock(&kvm->lock);
6682 		break;
6683 	case KVM_CAP_MAX_VCPU_ID:
6684 		r = -EINVAL;
6685 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6686 			break;
6687 
6688 		mutex_lock(&kvm->lock);
6689 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6690 			;
6691 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6692 			r = 0;
6693 		} else if (!kvm->arch.max_vcpu_ids) {
6694 			kvm->arch.max_vcpu_ids = cap->args[0];
6695 			r = 0;
6696 		}
6697 		mutex_unlock(&kvm->lock);
6698 		break;
6699 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6700 		r = -EINVAL;
6701 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6702 			break;
6703 		if (!kvm_caps.has_notify_vmexit)
6704 			break;
6705 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6706 			break;
6707 		mutex_lock(&kvm->lock);
6708 		if (!kvm->created_vcpus) {
6709 			kvm->arch.notify_window = cap->args[0] >> 32;
6710 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6711 			r = 0;
6712 		}
6713 		mutex_unlock(&kvm->lock);
6714 		break;
6715 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6716 		r = -EINVAL;
6717 
6718 		/*
6719 		 * Since the risk of disabling NX hugepages is a guest crashing
6720 		 * the system, ensure the userspace process has permission to
6721 		 * reboot the system.
6722 		 *
6723 		 * Note that unlike the reboot() syscall, the process must have
6724 		 * this capability in the root namespace because exposing
6725 		 * /dev/kvm into a container does not limit the scope of the
6726 		 * iTLB multihit bug to that container. In other words,
6727 		 * this must use capable(), not ns_capable().
6728 		 */
6729 		if (!capable(CAP_SYS_BOOT)) {
6730 			r = -EPERM;
6731 			break;
6732 		}
6733 
6734 		if (cap->args[0])
6735 			break;
6736 
6737 		mutex_lock(&kvm->lock);
6738 		if (!kvm->created_vcpus) {
6739 			kvm->arch.disable_nx_huge_pages = true;
6740 			r = 0;
6741 		}
6742 		mutex_unlock(&kvm->lock);
6743 		break;
6744 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6745 		u64 bus_cycle_ns = cap->args[0];
6746 		u64 unused;
6747 
6748 		/*
6749 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
6750 		 * divide value that can be programmed in APIC_TDCR.
6751 		 */
6752 		r = -EINVAL;
6753 		if (!bus_cycle_ns ||
6754 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6755 			break;
6756 
6757 		r = 0;
6758 		mutex_lock(&kvm->lock);
6759 		if (!irqchip_in_kernel(kvm))
6760 			r = -ENXIO;
6761 		else if (kvm->created_vcpus)
6762 			r = -EINVAL;
6763 		else
6764 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6765 		mutex_unlock(&kvm->lock);
6766 		break;
6767 	}
6768 	default:
6769 		r = -EINVAL;
6770 		break;
6771 	}
6772 	return r;
6773 }
6774 
kvm_alloc_msr_filter(bool default_allow)6775 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6776 {
6777 	struct kvm_x86_msr_filter *msr_filter;
6778 
6779 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6780 	if (!msr_filter)
6781 		return NULL;
6782 
6783 	msr_filter->default_allow = default_allow;
6784 	return msr_filter;
6785 }
6786 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6787 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6788 {
6789 	u32 i;
6790 
6791 	if (!msr_filter)
6792 		return;
6793 
6794 	for (i = 0; i < msr_filter->count; i++)
6795 		kfree(msr_filter->ranges[i].bitmap);
6796 
6797 	kfree(msr_filter);
6798 }
6799 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6800 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6801 			      struct kvm_msr_filter_range *user_range)
6802 {
6803 	unsigned long *bitmap;
6804 	size_t bitmap_size;
6805 
6806 	if (!user_range->nmsrs)
6807 		return 0;
6808 
6809 	if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6810 		return -EINVAL;
6811 
6812 	if (!user_range->flags)
6813 		return -EINVAL;
6814 
6815 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6816 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6817 		return -EINVAL;
6818 
6819 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6820 	if (IS_ERR(bitmap))
6821 		return PTR_ERR(bitmap);
6822 
6823 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6824 		.flags = user_range->flags,
6825 		.base = user_range->base,
6826 		.nmsrs = user_range->nmsrs,
6827 		.bitmap = bitmap,
6828 	};
6829 
6830 	msr_filter->count++;
6831 	return 0;
6832 }
6833 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)6834 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6835 				       struct kvm_msr_filter *filter)
6836 {
6837 	struct kvm_x86_msr_filter *new_filter, *old_filter;
6838 	bool default_allow;
6839 	bool empty = true;
6840 	int r;
6841 	u32 i;
6842 
6843 	if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
6844 		return -EINVAL;
6845 
6846 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6847 		empty &= !filter->ranges[i].nmsrs;
6848 
6849 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6850 	if (empty && !default_allow)
6851 		return -EINVAL;
6852 
6853 	new_filter = kvm_alloc_msr_filter(default_allow);
6854 	if (!new_filter)
6855 		return -ENOMEM;
6856 
6857 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6858 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6859 		if (r) {
6860 			kvm_free_msr_filter(new_filter);
6861 			return r;
6862 		}
6863 	}
6864 
6865 	mutex_lock(&kvm->lock);
6866 	old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6867 					 mutex_is_locked(&kvm->lock));
6868 	mutex_unlock(&kvm->lock);
6869 	synchronize_srcu(&kvm->srcu);
6870 
6871 	kvm_free_msr_filter(old_filter);
6872 
6873 	kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6874 
6875 	return 0;
6876 }
6877 
6878 #ifdef CONFIG_KVM_COMPAT
6879 /* for KVM_X86_SET_MSR_FILTER */
6880 struct kvm_msr_filter_range_compat {
6881 	__u32 flags;
6882 	__u32 nmsrs;
6883 	__u32 base;
6884 	__u32 bitmap;
6885 };
6886 
6887 struct kvm_msr_filter_compat {
6888 	__u32 flags;
6889 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6890 };
6891 
6892 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6893 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6894 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6895 			      unsigned long arg)
6896 {
6897 	void __user *argp = (void __user *)arg;
6898 	struct kvm *kvm = filp->private_data;
6899 	long r = -ENOTTY;
6900 
6901 	switch (ioctl) {
6902 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
6903 		struct kvm_msr_filter __user *user_msr_filter = argp;
6904 		struct kvm_msr_filter_compat filter_compat;
6905 		struct kvm_msr_filter filter;
6906 		int i;
6907 
6908 		if (copy_from_user(&filter_compat, user_msr_filter,
6909 				   sizeof(filter_compat)))
6910 			return -EFAULT;
6911 
6912 		filter.flags = filter_compat.flags;
6913 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6914 			struct kvm_msr_filter_range_compat *cr;
6915 
6916 			cr = &filter_compat.ranges[i];
6917 			filter.ranges[i] = (struct kvm_msr_filter_range) {
6918 				.flags = cr->flags,
6919 				.nmsrs = cr->nmsrs,
6920 				.base = cr->base,
6921 				.bitmap = (__u8 *)(ulong)cr->bitmap,
6922 			};
6923 		}
6924 
6925 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6926 		break;
6927 	}
6928 	}
6929 
6930 	return r;
6931 }
6932 #endif
6933 
6934 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)6935 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6936 {
6937 	struct kvm_vcpu *vcpu;
6938 	unsigned long i;
6939 
6940 	/*
6941 	 * Ignore the return, marking the guest paused only "fails" if the vCPU
6942 	 * isn't using kvmclock; continuing on is correct and desirable.
6943 	 */
6944 	kvm_for_each_vcpu(i, vcpu, kvm)
6945 		(void)kvm_set_guest_paused(vcpu);
6946 
6947 	return NOTIFY_DONE;
6948 }
6949 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)6950 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6951 {
6952 	switch (state) {
6953 	case PM_HIBERNATION_PREPARE:
6954 	case PM_SUSPEND_PREPARE:
6955 		return kvm_arch_suspend_notifier(kvm);
6956 	}
6957 
6958 	return NOTIFY_DONE;
6959 }
6960 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6961 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)6962 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6963 {
6964 	struct kvm_clock_data data = { 0 };
6965 
6966 	get_kvmclock(kvm, &data);
6967 	if (copy_to_user(argp, &data, sizeof(data)))
6968 		return -EFAULT;
6969 
6970 	return 0;
6971 }
6972 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)6973 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6974 {
6975 	struct kvm_arch *ka = &kvm->arch;
6976 	struct kvm_clock_data data;
6977 	u64 now_raw_ns;
6978 
6979 	if (copy_from_user(&data, argp, sizeof(data)))
6980 		return -EFAULT;
6981 
6982 	/*
6983 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6984 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6985 	 */
6986 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6987 		return -EINVAL;
6988 
6989 	kvm_hv_request_tsc_page_update(kvm);
6990 	kvm_start_pvclock_update(kvm);
6991 	pvclock_update_vm_gtod_copy(kvm);
6992 
6993 	/*
6994 	 * This pairs with kvm_guest_time_update(): when masterclock is
6995 	 * in use, we use master_kernel_ns + kvmclock_offset to set
6996 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6997 	 * is slightly ahead) here we risk going negative on unsigned
6998 	 * 'system_time' when 'data.clock' is very small.
6999 	 */
7000 	if (data.flags & KVM_CLOCK_REALTIME) {
7001 		u64 now_real_ns = ktime_get_real_ns();
7002 
7003 		/*
7004 		 * Avoid stepping the kvmclock backwards.
7005 		 */
7006 		if (now_real_ns > data.realtime)
7007 			data.clock += now_real_ns - data.realtime;
7008 	}
7009 
7010 	if (ka->use_master_clock)
7011 		now_raw_ns = ka->master_kernel_ns;
7012 	else
7013 		now_raw_ns = get_kvmclock_base_ns();
7014 	ka->kvmclock_offset = data.clock - now_raw_ns;
7015 	kvm_end_pvclock_update(kvm);
7016 	return 0;
7017 }
7018 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7019 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7020 {
7021 	struct kvm *kvm = filp->private_data;
7022 	void __user *argp = (void __user *)arg;
7023 	int r = -ENOTTY;
7024 	/*
7025 	 * This union makes it completely explicit to gcc-3.x
7026 	 * that these two variables' stack usage should be
7027 	 * combined, not added together.
7028 	 */
7029 	union {
7030 		struct kvm_pit_state ps;
7031 		struct kvm_pit_state2 ps2;
7032 		struct kvm_pit_config pit_config;
7033 	} u;
7034 
7035 	switch (ioctl) {
7036 	case KVM_SET_TSS_ADDR:
7037 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7038 		break;
7039 	case KVM_SET_IDENTITY_MAP_ADDR: {
7040 		u64 ident_addr;
7041 
7042 		mutex_lock(&kvm->lock);
7043 		r = -EINVAL;
7044 		if (kvm->created_vcpus)
7045 			goto set_identity_unlock;
7046 		r = -EFAULT;
7047 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7048 			goto set_identity_unlock;
7049 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7050 set_identity_unlock:
7051 		mutex_unlock(&kvm->lock);
7052 		break;
7053 	}
7054 	case KVM_SET_NR_MMU_PAGES:
7055 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7056 		break;
7057 	case KVM_CREATE_IRQCHIP: {
7058 		mutex_lock(&kvm->lock);
7059 
7060 		r = -EEXIST;
7061 		if (irqchip_in_kernel(kvm))
7062 			goto create_irqchip_unlock;
7063 
7064 		r = -EINVAL;
7065 		if (kvm->created_vcpus)
7066 			goto create_irqchip_unlock;
7067 
7068 		r = kvm_pic_init(kvm);
7069 		if (r)
7070 			goto create_irqchip_unlock;
7071 
7072 		r = kvm_ioapic_init(kvm);
7073 		if (r) {
7074 			kvm_pic_destroy(kvm);
7075 			goto create_irqchip_unlock;
7076 		}
7077 
7078 		r = kvm_setup_default_irq_routing(kvm);
7079 		if (r) {
7080 			kvm_ioapic_destroy(kvm);
7081 			kvm_pic_destroy(kvm);
7082 			goto create_irqchip_unlock;
7083 		}
7084 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7085 		smp_wmb();
7086 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7087 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7088 	create_irqchip_unlock:
7089 		mutex_unlock(&kvm->lock);
7090 		break;
7091 	}
7092 	case KVM_CREATE_PIT:
7093 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7094 		goto create_pit;
7095 	case KVM_CREATE_PIT2:
7096 		r = -EFAULT;
7097 		if (copy_from_user(&u.pit_config, argp,
7098 				   sizeof(struct kvm_pit_config)))
7099 			goto out;
7100 	create_pit:
7101 		mutex_lock(&kvm->lock);
7102 		r = -EEXIST;
7103 		if (kvm->arch.vpit)
7104 			goto create_pit_unlock;
7105 		r = -ENOENT;
7106 		if (!pic_in_kernel(kvm))
7107 			goto create_pit_unlock;
7108 		r = -ENOMEM;
7109 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7110 		if (kvm->arch.vpit)
7111 			r = 0;
7112 	create_pit_unlock:
7113 		mutex_unlock(&kvm->lock);
7114 		break;
7115 	case KVM_GET_IRQCHIP: {
7116 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7117 		struct kvm_irqchip *chip;
7118 
7119 		chip = memdup_user(argp, sizeof(*chip));
7120 		if (IS_ERR(chip)) {
7121 			r = PTR_ERR(chip);
7122 			goto out;
7123 		}
7124 
7125 		r = -ENXIO;
7126 		if (!irqchip_kernel(kvm))
7127 			goto get_irqchip_out;
7128 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7129 		if (r)
7130 			goto get_irqchip_out;
7131 		r = -EFAULT;
7132 		if (copy_to_user(argp, chip, sizeof(*chip)))
7133 			goto get_irqchip_out;
7134 		r = 0;
7135 	get_irqchip_out:
7136 		kfree(chip);
7137 		break;
7138 	}
7139 	case KVM_SET_IRQCHIP: {
7140 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7141 		struct kvm_irqchip *chip;
7142 
7143 		chip = memdup_user(argp, sizeof(*chip));
7144 		if (IS_ERR(chip)) {
7145 			r = PTR_ERR(chip);
7146 			goto out;
7147 		}
7148 
7149 		r = -ENXIO;
7150 		if (!irqchip_kernel(kvm))
7151 			goto set_irqchip_out;
7152 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7153 	set_irqchip_out:
7154 		kfree(chip);
7155 		break;
7156 	}
7157 	case KVM_GET_PIT: {
7158 		r = -EFAULT;
7159 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7160 			goto out;
7161 		r = -ENXIO;
7162 		if (!kvm->arch.vpit)
7163 			goto out;
7164 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7165 		if (r)
7166 			goto out;
7167 		r = -EFAULT;
7168 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7169 			goto out;
7170 		r = 0;
7171 		break;
7172 	}
7173 	case KVM_SET_PIT: {
7174 		r = -EFAULT;
7175 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7176 			goto out;
7177 		mutex_lock(&kvm->lock);
7178 		r = -ENXIO;
7179 		if (!kvm->arch.vpit)
7180 			goto set_pit_out;
7181 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7182 set_pit_out:
7183 		mutex_unlock(&kvm->lock);
7184 		break;
7185 	}
7186 	case KVM_GET_PIT2: {
7187 		r = -ENXIO;
7188 		if (!kvm->arch.vpit)
7189 			goto out;
7190 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7191 		if (r)
7192 			goto out;
7193 		r = -EFAULT;
7194 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7195 			goto out;
7196 		r = 0;
7197 		break;
7198 	}
7199 	case KVM_SET_PIT2: {
7200 		r = -EFAULT;
7201 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7202 			goto out;
7203 		mutex_lock(&kvm->lock);
7204 		r = -ENXIO;
7205 		if (!kvm->arch.vpit)
7206 			goto set_pit2_out;
7207 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7208 set_pit2_out:
7209 		mutex_unlock(&kvm->lock);
7210 		break;
7211 	}
7212 	case KVM_REINJECT_CONTROL: {
7213 		struct kvm_reinject_control control;
7214 		r =  -EFAULT;
7215 		if (copy_from_user(&control, argp, sizeof(control)))
7216 			goto out;
7217 		r = -ENXIO;
7218 		if (!kvm->arch.vpit)
7219 			goto out;
7220 		r = kvm_vm_ioctl_reinject(kvm, &control);
7221 		break;
7222 	}
7223 	case KVM_SET_BOOT_CPU_ID:
7224 		r = 0;
7225 		mutex_lock(&kvm->lock);
7226 		if (kvm->created_vcpus)
7227 			r = -EBUSY;
7228 		else if (arg > KVM_MAX_VCPU_IDS ||
7229 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7230 			r = -EINVAL;
7231 		else
7232 			kvm->arch.bsp_vcpu_id = arg;
7233 		mutex_unlock(&kvm->lock);
7234 		break;
7235 #ifdef CONFIG_KVM_XEN
7236 	case KVM_XEN_HVM_CONFIG: {
7237 		struct kvm_xen_hvm_config xhc;
7238 		r = -EFAULT;
7239 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
7240 			goto out;
7241 		r = kvm_xen_hvm_config(kvm, &xhc);
7242 		break;
7243 	}
7244 	case KVM_XEN_HVM_GET_ATTR: {
7245 		struct kvm_xen_hvm_attr xha;
7246 
7247 		r = -EFAULT;
7248 		if (copy_from_user(&xha, argp, sizeof(xha)))
7249 			goto out;
7250 		r = kvm_xen_hvm_get_attr(kvm, &xha);
7251 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7252 			r = -EFAULT;
7253 		break;
7254 	}
7255 	case KVM_XEN_HVM_SET_ATTR: {
7256 		struct kvm_xen_hvm_attr xha;
7257 
7258 		r = -EFAULT;
7259 		if (copy_from_user(&xha, argp, sizeof(xha)))
7260 			goto out;
7261 		r = kvm_xen_hvm_set_attr(kvm, &xha);
7262 		break;
7263 	}
7264 	case KVM_XEN_HVM_EVTCHN_SEND: {
7265 		struct kvm_irq_routing_xen_evtchn uxe;
7266 
7267 		r = -EFAULT;
7268 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
7269 			goto out;
7270 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7271 		break;
7272 	}
7273 #endif
7274 	case KVM_SET_CLOCK:
7275 		r = kvm_vm_ioctl_set_clock(kvm, argp);
7276 		break;
7277 	case KVM_GET_CLOCK:
7278 		r = kvm_vm_ioctl_get_clock(kvm, argp);
7279 		break;
7280 	case KVM_SET_TSC_KHZ: {
7281 		u32 user_tsc_khz;
7282 
7283 		r = -EINVAL;
7284 		user_tsc_khz = (u32)arg;
7285 
7286 		if (kvm_caps.has_tsc_control &&
7287 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7288 			goto out;
7289 
7290 		if (user_tsc_khz == 0)
7291 			user_tsc_khz = tsc_khz;
7292 
7293 		WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7294 		r = 0;
7295 
7296 		goto out;
7297 	}
7298 	case KVM_GET_TSC_KHZ: {
7299 		r = READ_ONCE(kvm->arch.default_tsc_khz);
7300 		goto out;
7301 	}
7302 	case KVM_MEMORY_ENCRYPT_OP: {
7303 		r = -ENOTTY;
7304 		if (!kvm_x86_ops.mem_enc_ioctl)
7305 			goto out;
7306 
7307 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7308 		break;
7309 	}
7310 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
7311 		struct kvm_enc_region region;
7312 
7313 		r = -EFAULT;
7314 		if (copy_from_user(&region, argp, sizeof(region)))
7315 			goto out;
7316 
7317 		r = -ENOTTY;
7318 		if (!kvm_x86_ops.mem_enc_register_region)
7319 			goto out;
7320 
7321 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
7322 		break;
7323 	}
7324 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7325 		struct kvm_enc_region region;
7326 
7327 		r = -EFAULT;
7328 		if (copy_from_user(&region, argp, sizeof(region)))
7329 			goto out;
7330 
7331 		r = -ENOTTY;
7332 		if (!kvm_x86_ops.mem_enc_unregister_region)
7333 			goto out;
7334 
7335 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
7336 		break;
7337 	}
7338 #ifdef CONFIG_KVM_HYPERV
7339 	case KVM_HYPERV_EVENTFD: {
7340 		struct kvm_hyperv_eventfd hvevfd;
7341 
7342 		r = -EFAULT;
7343 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7344 			goto out;
7345 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7346 		break;
7347 	}
7348 #endif
7349 	case KVM_SET_PMU_EVENT_FILTER:
7350 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7351 		break;
7352 	case KVM_X86_SET_MSR_FILTER: {
7353 		struct kvm_msr_filter __user *user_msr_filter = argp;
7354 		struct kvm_msr_filter filter;
7355 
7356 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7357 			return -EFAULT;
7358 
7359 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7360 		break;
7361 	}
7362 	default:
7363 		r = -ENOTTY;
7364 	}
7365 out:
7366 	return r;
7367 }
7368 
kvm_probe_feature_msr(u32 msr_index)7369 static void kvm_probe_feature_msr(u32 msr_index)
7370 {
7371 	u64 data;
7372 
7373 	if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7374 		return;
7375 
7376 	msr_based_features[num_msr_based_features++] = msr_index;
7377 }
7378 
kvm_probe_msr_to_save(u32 msr_index)7379 static void kvm_probe_msr_to_save(u32 msr_index)
7380 {
7381 	u32 dummy[2];
7382 
7383 	if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7384 		return;
7385 
7386 	/*
7387 	 * Even MSRs that are valid in the host may not be exposed to guests in
7388 	 * some cases.
7389 	 */
7390 	switch (msr_index) {
7391 	case MSR_IA32_BNDCFGS:
7392 		if (!kvm_mpx_supported())
7393 			return;
7394 		break;
7395 	case MSR_TSC_AUX:
7396 		if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7397 		    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7398 			return;
7399 		break;
7400 	case MSR_IA32_UMWAIT_CONTROL:
7401 		if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7402 			return;
7403 		break;
7404 	case MSR_IA32_RTIT_CTL:
7405 	case MSR_IA32_RTIT_STATUS:
7406 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7407 			return;
7408 		break;
7409 	case MSR_IA32_RTIT_CR3_MATCH:
7410 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7411 		    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7412 			return;
7413 		break;
7414 	case MSR_IA32_RTIT_OUTPUT_BASE:
7415 	case MSR_IA32_RTIT_OUTPUT_MASK:
7416 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7417 		    (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7418 		     !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7419 			return;
7420 		break;
7421 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7422 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7423 		    (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7424 		     intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7425 			return;
7426 		break;
7427 	case MSR_ARCH_PERFMON_PERFCTR0 ...
7428 	     MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7429 		if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7430 		    kvm_pmu_cap.num_counters_gp)
7431 			return;
7432 		break;
7433 	case MSR_ARCH_PERFMON_EVENTSEL0 ...
7434 	     MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7435 		if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7436 		    kvm_pmu_cap.num_counters_gp)
7437 			return;
7438 		break;
7439 	case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7440 	     MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7441 		if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7442 		    kvm_pmu_cap.num_counters_fixed)
7443 			return;
7444 		break;
7445 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7446 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7447 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7448 		if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7449 			return;
7450 		break;
7451 	case MSR_IA32_XFD:
7452 	case MSR_IA32_XFD_ERR:
7453 		if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7454 			return;
7455 		break;
7456 	case MSR_IA32_TSX_CTRL:
7457 		if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7458 			return;
7459 		break;
7460 	default:
7461 		break;
7462 	}
7463 
7464 	msrs_to_save[num_msrs_to_save++] = msr_index;
7465 }
7466 
kvm_init_msr_lists(void)7467 static void kvm_init_msr_lists(void)
7468 {
7469 	unsigned i;
7470 
7471 	BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7472 			 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7473 
7474 	num_msrs_to_save = 0;
7475 	num_emulated_msrs = 0;
7476 	num_msr_based_features = 0;
7477 
7478 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7479 		kvm_probe_msr_to_save(msrs_to_save_base[i]);
7480 
7481 	if (enable_pmu) {
7482 		for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7483 			kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7484 	}
7485 
7486 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7487 		if (!kvm_x86_call(has_emulated_msr)(NULL,
7488 						    emulated_msrs_all[i]))
7489 			continue;
7490 
7491 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7492 	}
7493 
7494 	for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7495 		kvm_probe_feature_msr(i);
7496 
7497 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7498 		kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7499 }
7500 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7501 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7502 			   const void *v)
7503 {
7504 	int handled = 0;
7505 	int n;
7506 
7507 	do {
7508 		n = min(len, 8);
7509 		if (!(lapic_in_kernel(vcpu) &&
7510 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7511 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7512 			break;
7513 		handled += n;
7514 		addr += n;
7515 		len -= n;
7516 		v += n;
7517 	} while (len);
7518 
7519 	return handled;
7520 }
7521 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7522 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7523 {
7524 	int handled = 0;
7525 	int n;
7526 
7527 	do {
7528 		n = min(len, 8);
7529 		if (!(lapic_in_kernel(vcpu) &&
7530 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7531 					 addr, n, v))
7532 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7533 			break;
7534 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7535 		handled += n;
7536 		addr += n;
7537 		len -= n;
7538 		v += n;
7539 	} while (len);
7540 
7541 	return handled;
7542 }
7543 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7544 void kvm_set_segment(struct kvm_vcpu *vcpu,
7545 		     struct kvm_segment *var, int seg)
7546 {
7547 	kvm_x86_call(set_segment)(vcpu, var, seg);
7548 }
7549 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7550 void kvm_get_segment(struct kvm_vcpu *vcpu,
7551 		     struct kvm_segment *var, int seg)
7552 {
7553 	kvm_x86_call(get_segment)(vcpu, var, seg);
7554 }
7555 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7556 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7557 			   struct x86_exception *exception)
7558 {
7559 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7560 	gpa_t t_gpa;
7561 
7562 	BUG_ON(!mmu_is_nested(vcpu));
7563 
7564 	/* NPT walks are always user-walks */
7565 	access |= PFERR_USER_MASK;
7566 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7567 
7568 	return t_gpa;
7569 }
7570 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7571 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7572 			      struct x86_exception *exception)
7573 {
7574 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7575 
7576 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7577 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7578 }
7579 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7580 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7581 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7582 			       struct x86_exception *exception)
7583 {
7584 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7585 
7586 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7587 	access |= PFERR_WRITE_MASK;
7588 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7589 }
7590 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7591 
7592 /* 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)7593 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7594 				struct x86_exception *exception)
7595 {
7596 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7597 
7598 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7599 }
7600 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7601 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7602 				      struct kvm_vcpu *vcpu, u64 access,
7603 				      struct x86_exception *exception)
7604 {
7605 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7606 	void *data = val;
7607 	int r = X86EMUL_CONTINUE;
7608 
7609 	while (bytes) {
7610 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7611 		unsigned offset = addr & (PAGE_SIZE-1);
7612 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7613 		int ret;
7614 
7615 		if (gpa == INVALID_GPA)
7616 			return X86EMUL_PROPAGATE_FAULT;
7617 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7618 					       offset, toread);
7619 		if (ret < 0) {
7620 			r = X86EMUL_IO_NEEDED;
7621 			goto out;
7622 		}
7623 
7624 		bytes -= toread;
7625 		data += toread;
7626 		addr += toread;
7627 	}
7628 out:
7629 	return r;
7630 }
7631 
7632 /* 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)7633 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7634 				gva_t addr, void *val, unsigned int bytes,
7635 				struct x86_exception *exception)
7636 {
7637 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7638 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7639 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7640 	unsigned offset;
7641 	int ret;
7642 
7643 	/* Inline kvm_read_guest_virt_helper for speed.  */
7644 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7645 				    exception);
7646 	if (unlikely(gpa == INVALID_GPA))
7647 		return X86EMUL_PROPAGATE_FAULT;
7648 
7649 	offset = addr & (PAGE_SIZE-1);
7650 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7651 		bytes = (unsigned)PAGE_SIZE - offset;
7652 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7653 				       offset, bytes);
7654 	if (unlikely(ret < 0))
7655 		return X86EMUL_IO_NEEDED;
7656 
7657 	return X86EMUL_CONTINUE;
7658 }
7659 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7660 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7661 			       gva_t addr, void *val, unsigned int bytes,
7662 			       struct x86_exception *exception)
7663 {
7664 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7665 
7666 	/*
7667 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7668 	 * is returned, but our callers are not ready for that and they blindly
7669 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7670 	 * uninitialized kernel stack memory into cr2 and error code.
7671 	 */
7672 	memset(exception, 0, sizeof(*exception));
7673 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7674 					  exception);
7675 }
7676 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7677 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7678 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7679 			     gva_t addr, void *val, unsigned int bytes,
7680 			     struct x86_exception *exception, bool system)
7681 {
7682 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7683 	u64 access = 0;
7684 
7685 	if (system)
7686 		access |= PFERR_IMPLICIT_ACCESS;
7687 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7688 		access |= PFERR_USER_MASK;
7689 
7690 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7691 }
7692 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7693 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7694 				      struct kvm_vcpu *vcpu, u64 access,
7695 				      struct x86_exception *exception)
7696 {
7697 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7698 	void *data = val;
7699 	int r = X86EMUL_CONTINUE;
7700 
7701 	while (bytes) {
7702 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7703 		unsigned offset = addr & (PAGE_SIZE-1);
7704 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7705 		int ret;
7706 
7707 		if (gpa == INVALID_GPA)
7708 			return X86EMUL_PROPAGATE_FAULT;
7709 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7710 		if (ret < 0) {
7711 			r = X86EMUL_IO_NEEDED;
7712 			goto out;
7713 		}
7714 
7715 		bytes -= towrite;
7716 		data += towrite;
7717 		addr += towrite;
7718 	}
7719 out:
7720 	return r;
7721 }
7722 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7723 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7724 			      unsigned int bytes, struct x86_exception *exception,
7725 			      bool system)
7726 {
7727 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7728 	u64 access = PFERR_WRITE_MASK;
7729 
7730 	if (system)
7731 		access |= PFERR_IMPLICIT_ACCESS;
7732 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7733 		access |= PFERR_USER_MASK;
7734 
7735 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7736 					   access, exception);
7737 }
7738 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7739 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7740 				unsigned int bytes, struct x86_exception *exception)
7741 {
7742 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7743 	vcpu->arch.l1tf_flush_l1d = true;
7744 
7745 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7746 					   PFERR_WRITE_MASK, exception);
7747 }
7748 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7749 
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7750 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7751 				  void *insn, int insn_len)
7752 {
7753 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7754 						       insn, insn_len);
7755 }
7756 
handle_ud(struct kvm_vcpu * vcpu)7757 int handle_ud(struct kvm_vcpu *vcpu)
7758 {
7759 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7760 	int fep_flags = READ_ONCE(force_emulation_prefix);
7761 	int emul_type = EMULTYPE_TRAP_UD;
7762 	char sig[5]; /* ud2; .ascii "kvm" */
7763 	struct x86_exception e;
7764 	int r;
7765 
7766 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7767 	if (r != X86EMUL_CONTINUE)
7768 		return 1;
7769 
7770 	if (fep_flags &&
7771 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7772 				sig, sizeof(sig), &e) == 0 &&
7773 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7774 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7775 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7776 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7777 		emul_type = EMULTYPE_TRAP_UD_FORCED;
7778 	}
7779 
7780 	return kvm_emulate_instruction(vcpu, emul_type);
7781 }
7782 EXPORT_SYMBOL_GPL(handle_ud);
7783 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)7784 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7785 			    gpa_t gpa, bool write)
7786 {
7787 	/* For APIC access vmexit */
7788 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7789 		return 1;
7790 
7791 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7792 		trace_vcpu_match_mmio(gva, gpa, write, true);
7793 		return 1;
7794 	}
7795 
7796 	return 0;
7797 }
7798 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)7799 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7800 				gpa_t *gpa, struct x86_exception *exception,
7801 				bool write)
7802 {
7803 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7804 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7805 		     | (write ? PFERR_WRITE_MASK : 0);
7806 
7807 	/*
7808 	 * currently PKRU is only applied to ept enabled guest so
7809 	 * there is no pkey in EPT page table for L1 guest or EPT
7810 	 * shadow page table for L2 guest.
7811 	 */
7812 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7813 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
7814 			      vcpu->arch.mmio_access, 0, access))) {
7815 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7816 					(gva & (PAGE_SIZE - 1));
7817 		trace_vcpu_match_mmio(gva, *gpa, write, false);
7818 		return 1;
7819 	}
7820 
7821 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7822 
7823 	if (*gpa == INVALID_GPA)
7824 		return -1;
7825 
7826 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7827 }
7828 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)7829 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7830 			const void *val, int bytes)
7831 {
7832 	int ret;
7833 
7834 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7835 	if (ret < 0)
7836 		return 0;
7837 	kvm_page_track_write(vcpu, gpa, val, bytes);
7838 	return 1;
7839 }
7840 
7841 struct read_write_emulator_ops {
7842 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7843 				  int bytes);
7844 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7845 				  void *val, int bytes);
7846 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7847 			       int bytes, void *val);
7848 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7849 				    void *val, int bytes);
7850 	bool write;
7851 };
7852 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)7853 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7854 {
7855 	if (vcpu->mmio_read_completed) {
7856 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7857 			       vcpu->mmio_fragments[0].gpa, val);
7858 		vcpu->mmio_read_completed = 0;
7859 		return 1;
7860 	}
7861 
7862 	return 0;
7863 }
7864 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7865 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7866 			void *val, int bytes)
7867 {
7868 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7869 }
7870 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7871 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7872 			 void *val, int bytes)
7873 {
7874 	return emulator_write_phys(vcpu, gpa, val, bytes);
7875 }
7876 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)7877 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7878 {
7879 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7880 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
7881 }
7882 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7883 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7884 			  void *val, int bytes)
7885 {
7886 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7887 	return X86EMUL_IO_NEEDED;
7888 }
7889 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7890 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7891 			   void *val, int bytes)
7892 {
7893 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7894 
7895 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7896 	return X86EMUL_CONTINUE;
7897 }
7898 
7899 static const struct read_write_emulator_ops read_emultor = {
7900 	.read_write_prepare = read_prepare,
7901 	.read_write_emulate = read_emulate,
7902 	.read_write_mmio = vcpu_mmio_read,
7903 	.read_write_exit_mmio = read_exit_mmio,
7904 };
7905 
7906 static const struct read_write_emulator_ops write_emultor = {
7907 	.read_write_emulate = write_emulate,
7908 	.read_write_mmio = write_mmio,
7909 	.read_write_exit_mmio = write_exit_mmio,
7910 	.write = true,
7911 };
7912 
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)7913 static int emulator_read_write_onepage(unsigned long addr, void *val,
7914 				       unsigned int bytes,
7915 				       struct x86_exception *exception,
7916 				       struct kvm_vcpu *vcpu,
7917 				       const struct read_write_emulator_ops *ops)
7918 {
7919 	gpa_t gpa;
7920 	int handled, ret;
7921 	bool write = ops->write;
7922 	struct kvm_mmio_fragment *frag;
7923 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7924 
7925 	/*
7926 	 * If the exit was due to a NPF we may already have a GPA.
7927 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7928 	 * Note, this cannot be used on string operations since string
7929 	 * operation using rep will only have the initial GPA from the NPF
7930 	 * occurred.
7931 	 */
7932 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7933 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7934 		gpa = ctxt->gpa_val;
7935 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7936 	} else {
7937 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7938 		if (ret < 0)
7939 			return X86EMUL_PROPAGATE_FAULT;
7940 	}
7941 
7942 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7943 		return X86EMUL_CONTINUE;
7944 
7945 	/*
7946 	 * Is this MMIO handled locally?
7947 	 */
7948 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7949 	if (handled == bytes)
7950 		return X86EMUL_CONTINUE;
7951 
7952 	gpa += handled;
7953 	bytes -= handled;
7954 	val += handled;
7955 
7956 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7957 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7958 	frag->gpa = gpa;
7959 	frag->data = val;
7960 	frag->len = bytes;
7961 	return X86EMUL_CONTINUE;
7962 }
7963 
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)7964 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7965 			unsigned long addr,
7966 			void *val, unsigned int bytes,
7967 			struct x86_exception *exception,
7968 			const struct read_write_emulator_ops *ops)
7969 {
7970 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7971 	gpa_t gpa;
7972 	int rc;
7973 
7974 	if (ops->read_write_prepare &&
7975 		  ops->read_write_prepare(vcpu, val, bytes))
7976 		return X86EMUL_CONTINUE;
7977 
7978 	vcpu->mmio_nr_fragments = 0;
7979 
7980 	/* Crossing a page boundary? */
7981 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7982 		int now;
7983 
7984 		now = -addr & ~PAGE_MASK;
7985 		rc = emulator_read_write_onepage(addr, val, now, exception,
7986 						 vcpu, ops);
7987 
7988 		if (rc != X86EMUL_CONTINUE)
7989 			return rc;
7990 		addr += now;
7991 		if (ctxt->mode != X86EMUL_MODE_PROT64)
7992 			addr = (u32)addr;
7993 		val += now;
7994 		bytes -= now;
7995 	}
7996 
7997 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
7998 					 vcpu, ops);
7999 	if (rc != X86EMUL_CONTINUE)
8000 		return rc;
8001 
8002 	if (!vcpu->mmio_nr_fragments)
8003 		return rc;
8004 
8005 	gpa = vcpu->mmio_fragments[0].gpa;
8006 
8007 	vcpu->mmio_needed = 1;
8008 	vcpu->mmio_cur_fragment = 0;
8009 
8010 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8011 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8012 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
8013 	vcpu->run->mmio.phys_addr = gpa;
8014 
8015 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8016 }
8017 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8018 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8019 				  unsigned long addr,
8020 				  void *val,
8021 				  unsigned int bytes,
8022 				  struct x86_exception *exception)
8023 {
8024 	return emulator_read_write(ctxt, addr, val, bytes,
8025 				   exception, &read_emultor);
8026 }
8027 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8028 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8029 			    unsigned long addr,
8030 			    const void *val,
8031 			    unsigned int bytes,
8032 			    struct x86_exception *exception)
8033 {
8034 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
8035 				   exception, &write_emultor);
8036 }
8037 
8038 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8039 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8040 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8041 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8042 				     unsigned long addr,
8043 				     const void *old,
8044 				     const void *new,
8045 				     unsigned int bytes,
8046 				     struct x86_exception *exception)
8047 {
8048 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8049 	u64 page_line_mask;
8050 	unsigned long hva;
8051 	gpa_t gpa;
8052 	int r;
8053 
8054 	/* guests cmpxchg8b have to be emulated atomically */
8055 	if (bytes > 8 || (bytes & (bytes - 1)))
8056 		goto emul_write;
8057 
8058 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8059 
8060 	if (gpa == INVALID_GPA ||
8061 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8062 		goto emul_write;
8063 
8064 	/*
8065 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
8066 	 * enabled in the host and the access splits a cache line.
8067 	 */
8068 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8069 		page_line_mask = ~(cache_line_size() - 1);
8070 	else
8071 		page_line_mask = PAGE_MASK;
8072 
8073 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8074 		goto emul_write;
8075 
8076 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8077 	if (kvm_is_error_hva(hva))
8078 		goto emul_write;
8079 
8080 	hva += offset_in_page(gpa);
8081 
8082 	switch (bytes) {
8083 	case 1:
8084 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
8085 		break;
8086 	case 2:
8087 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
8088 		break;
8089 	case 4:
8090 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
8091 		break;
8092 	case 8:
8093 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
8094 		break;
8095 	default:
8096 		BUG();
8097 	}
8098 
8099 	if (r < 0)
8100 		return X86EMUL_UNHANDLEABLE;
8101 
8102 	/*
8103 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8104 	 * successful, as the old value is written back on failure.  Note, for
8105 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
8106 	 * back the original value and the access is atomic, but KVM's ABI is
8107 	 * that all writes are dirty logged, regardless of the value written.
8108 	 */
8109 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8110 
8111 	if (r)
8112 		return X86EMUL_CMPXCHG_FAILED;
8113 
8114 	kvm_page_track_write(vcpu, gpa, new, bytes);
8115 
8116 	return X86EMUL_CONTINUE;
8117 
8118 emul_write:
8119 	pr_warn_once("emulating exchange as write\n");
8120 
8121 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8122 }
8123 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8124 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8125 			       unsigned short port, void *data,
8126 			       unsigned int count, bool in)
8127 {
8128 	unsigned i;
8129 	int r;
8130 
8131 	WARN_ON_ONCE(vcpu->arch.pio.count);
8132 	for (i = 0; i < count; i++) {
8133 		if (in)
8134 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8135 		else
8136 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8137 
8138 		if (r) {
8139 			if (i == 0)
8140 				goto userspace_io;
8141 
8142 			/*
8143 			 * Userspace must have unregistered the device while PIO
8144 			 * was running.  Drop writes / read as 0.
8145 			 */
8146 			if (in)
8147 				memset(data, 0, size * (count - i));
8148 			break;
8149 		}
8150 
8151 		data += size;
8152 	}
8153 	return 1;
8154 
8155 userspace_io:
8156 	vcpu->arch.pio.port = port;
8157 	vcpu->arch.pio.in = in;
8158 	vcpu->arch.pio.count = count;
8159 	vcpu->arch.pio.size = size;
8160 
8161 	if (in)
8162 		memset(vcpu->arch.pio_data, 0, size * count);
8163 	else
8164 		memcpy(vcpu->arch.pio_data, data, size * count);
8165 
8166 	vcpu->run->exit_reason = KVM_EXIT_IO;
8167 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8168 	vcpu->run->io.size = size;
8169 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8170 	vcpu->run->io.count = count;
8171 	vcpu->run->io.port = port;
8172 	return 0;
8173 }
8174 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8175 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8176       			   unsigned short port, void *val, unsigned int count)
8177 {
8178 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8179 	if (r)
8180 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8181 
8182 	return r;
8183 }
8184 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8185 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8186 {
8187 	int size = vcpu->arch.pio.size;
8188 	unsigned int count = vcpu->arch.pio.count;
8189 	memcpy(val, vcpu->arch.pio_data, size * count);
8190 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8191 	vcpu->arch.pio.count = 0;
8192 }
8193 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8194 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8195 				    int size, unsigned short port, void *val,
8196 				    unsigned int count)
8197 {
8198 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8199 	if (vcpu->arch.pio.count) {
8200 		/*
8201 		 * Complete a previous iteration that required userspace I/O.
8202 		 * Note, @count isn't guaranteed to match pio.count as userspace
8203 		 * can modify ECX before rerunning the vCPU.  Ignore any such
8204 		 * shenanigans as KVM doesn't support modifying the rep count,
8205 		 * and the emulator ensures @count doesn't overflow the buffer.
8206 		 */
8207 		complete_emulator_pio_in(vcpu, val);
8208 		return 1;
8209 	}
8210 
8211 	return emulator_pio_in(vcpu, size, port, val, count);
8212 }
8213 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8214 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8215 			    unsigned short port, const void *val,
8216 			    unsigned int count)
8217 {
8218 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8219 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8220 }
8221 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8222 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8223 				     int size, unsigned short port,
8224 				     const void *val, unsigned int count)
8225 {
8226 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8227 }
8228 
get_segment_base(struct kvm_vcpu * vcpu,int seg)8229 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8230 {
8231 	return kvm_x86_call(get_segment_base)(vcpu, seg);
8232 }
8233 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8234 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8235 {
8236 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8237 }
8238 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8239 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8240 {
8241 	if (!need_emulate_wbinvd(vcpu))
8242 		return X86EMUL_CONTINUE;
8243 
8244 	if (kvm_x86_call(has_wbinvd_exit)()) {
8245 		int cpu = get_cpu();
8246 
8247 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8248 		on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
8249 				wbinvd_ipi, NULL, 1);
8250 		put_cpu();
8251 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8252 	} else
8253 		wbinvd();
8254 	return X86EMUL_CONTINUE;
8255 }
8256 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8257 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8258 {
8259 	kvm_emulate_wbinvd_noskip(vcpu);
8260 	return kvm_skip_emulated_instruction(vcpu);
8261 }
8262 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8263 
8264 
8265 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8266 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8267 {
8268 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8269 }
8270 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8271 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8272 {
8273 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8274 }
8275 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8276 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8277 			   unsigned long value)
8278 {
8279 
8280 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8281 }
8282 
mk_cr_64(u64 curr_cr,u32 new_val)8283 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8284 {
8285 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8286 }
8287 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8288 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8289 {
8290 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8291 	unsigned long value;
8292 
8293 	switch (cr) {
8294 	case 0:
8295 		value = kvm_read_cr0(vcpu);
8296 		break;
8297 	case 2:
8298 		value = vcpu->arch.cr2;
8299 		break;
8300 	case 3:
8301 		value = kvm_read_cr3(vcpu);
8302 		break;
8303 	case 4:
8304 		value = kvm_read_cr4(vcpu);
8305 		break;
8306 	case 8:
8307 		value = kvm_get_cr8(vcpu);
8308 		break;
8309 	default:
8310 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8311 		return 0;
8312 	}
8313 
8314 	return value;
8315 }
8316 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8317 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8318 {
8319 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8320 	int res = 0;
8321 
8322 	switch (cr) {
8323 	case 0:
8324 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8325 		break;
8326 	case 2:
8327 		vcpu->arch.cr2 = val;
8328 		break;
8329 	case 3:
8330 		res = kvm_set_cr3(vcpu, val);
8331 		break;
8332 	case 4:
8333 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8334 		break;
8335 	case 8:
8336 		res = kvm_set_cr8(vcpu, val);
8337 		break;
8338 	default:
8339 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8340 		res = -1;
8341 	}
8342 
8343 	return res;
8344 }
8345 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8346 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8347 {
8348 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8349 }
8350 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8351 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8352 {
8353 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8354 }
8355 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8356 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8357 {
8358 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8359 }
8360 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8361 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8362 {
8363 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8364 }
8365 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8366 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8367 {
8368 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8369 }
8370 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8371 static unsigned long emulator_get_cached_segment_base(
8372 	struct x86_emulate_ctxt *ctxt, int seg)
8373 {
8374 	return get_segment_base(emul_to_vcpu(ctxt), seg);
8375 }
8376 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8377 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8378 				 struct desc_struct *desc, u32 *base3,
8379 				 int seg)
8380 {
8381 	struct kvm_segment var;
8382 
8383 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8384 	*selector = var.selector;
8385 
8386 	if (var.unusable) {
8387 		memset(desc, 0, sizeof(*desc));
8388 		if (base3)
8389 			*base3 = 0;
8390 		return false;
8391 	}
8392 
8393 	if (var.g)
8394 		var.limit >>= 12;
8395 	set_desc_limit(desc, var.limit);
8396 	set_desc_base(desc, (unsigned long)var.base);
8397 #ifdef CONFIG_X86_64
8398 	if (base3)
8399 		*base3 = var.base >> 32;
8400 #endif
8401 	desc->type = var.type;
8402 	desc->s = var.s;
8403 	desc->dpl = var.dpl;
8404 	desc->p = var.present;
8405 	desc->avl = var.avl;
8406 	desc->l = var.l;
8407 	desc->d = var.db;
8408 	desc->g = var.g;
8409 
8410 	return true;
8411 }
8412 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8413 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8414 				 struct desc_struct *desc, u32 base3,
8415 				 int seg)
8416 {
8417 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8418 	struct kvm_segment var;
8419 
8420 	var.selector = selector;
8421 	var.base = get_desc_base(desc);
8422 #ifdef CONFIG_X86_64
8423 	var.base |= ((u64)base3) << 32;
8424 #endif
8425 	var.limit = get_desc_limit(desc);
8426 	if (desc->g)
8427 		var.limit = (var.limit << 12) | 0xfff;
8428 	var.type = desc->type;
8429 	var.dpl = desc->dpl;
8430 	var.db = desc->d;
8431 	var.s = desc->s;
8432 	var.l = desc->l;
8433 	var.g = desc->g;
8434 	var.avl = desc->avl;
8435 	var.present = desc->p;
8436 	var.unusable = !var.present;
8437 	var.padding = 0;
8438 
8439 	kvm_set_segment(vcpu, &var, seg);
8440 	return;
8441 }
8442 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8443 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8444 					u32 msr_index, u64 *pdata)
8445 {
8446 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8447 	int r;
8448 
8449 	r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8450 	if (r < 0)
8451 		return X86EMUL_UNHANDLEABLE;
8452 
8453 	if (r) {
8454 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8455 				       complete_emulated_rdmsr, r))
8456 			return X86EMUL_IO_NEEDED;
8457 
8458 		trace_kvm_msr_read_ex(msr_index);
8459 		return X86EMUL_PROPAGATE_FAULT;
8460 	}
8461 
8462 	trace_kvm_msr_read(msr_index, *pdata);
8463 	return X86EMUL_CONTINUE;
8464 }
8465 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8466 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8467 					u32 msr_index, u64 data)
8468 {
8469 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8470 	int r;
8471 
8472 	r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8473 	if (r < 0)
8474 		return X86EMUL_UNHANDLEABLE;
8475 
8476 	if (r) {
8477 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8478 				       complete_emulated_msr_access, r))
8479 			return X86EMUL_IO_NEEDED;
8480 
8481 		trace_kvm_msr_write_ex(msr_index, data);
8482 		return X86EMUL_PROPAGATE_FAULT;
8483 	}
8484 
8485 	trace_kvm_msr_write(msr_index, data);
8486 	return X86EMUL_CONTINUE;
8487 }
8488 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8489 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8490 			    u32 msr_index, u64 *pdata)
8491 {
8492 	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8493 }
8494 
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8495 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8496 {
8497 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8498 }
8499 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8500 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8501 			     u32 pmc, u64 *pdata)
8502 {
8503 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8504 }
8505 
emulator_halt(struct x86_emulate_ctxt * ctxt)8506 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8507 {
8508 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8509 }
8510 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8511 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8512 			      struct x86_instruction_info *info,
8513 			      enum x86_intercept_stage stage)
8514 {
8515 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8516 					     &ctxt->exception);
8517 }
8518 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8519 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8520 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8521 			      bool exact_only)
8522 {
8523 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8524 }
8525 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8526 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8527 {
8528 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8529 }
8530 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8531 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8532 {
8533 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8534 }
8535 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8536 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8537 {
8538 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8539 }
8540 
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8541 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8542 {
8543 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8544 }
8545 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8546 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8547 {
8548 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8549 }
8550 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8551 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8552 {
8553 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8554 }
8555 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8556 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8557 {
8558 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8559 }
8560 
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8561 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8562 {
8563 	return is_smm(emul_to_vcpu(ctxt));
8564 }
8565 
emulator_is_guest_mode(struct x86_emulate_ctxt * ctxt)8566 static bool emulator_is_guest_mode(struct x86_emulate_ctxt *ctxt)
8567 {
8568 	return is_guest_mode(emul_to_vcpu(ctxt));
8569 }
8570 
8571 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8572 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8573 {
8574 	WARN_ON_ONCE(1);
8575 	return X86EMUL_UNHANDLEABLE;
8576 }
8577 #endif
8578 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8579 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8580 {
8581 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8582 }
8583 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8584 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8585 {
8586 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8587 }
8588 
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8589 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8590 {
8591 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8592 
8593 	if (!kvm->vm_bugged)
8594 		kvm_vm_bugged(kvm);
8595 }
8596 
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8597 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8598 					gva_t addr, unsigned int flags)
8599 {
8600 	if (!kvm_x86_ops.get_untagged_addr)
8601 		return addr;
8602 
8603 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8604 					       addr, flags);
8605 }
8606 
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8607 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8608 				       gva_t addr, unsigned int flags)
8609 {
8610 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8611 }
8612 
8613 static const struct x86_emulate_ops emulate_ops = {
8614 	.vm_bugged           = emulator_vm_bugged,
8615 	.read_gpr            = emulator_read_gpr,
8616 	.write_gpr           = emulator_write_gpr,
8617 	.read_std            = emulator_read_std,
8618 	.write_std           = emulator_write_std,
8619 	.fetch               = kvm_fetch_guest_virt,
8620 	.read_emulated       = emulator_read_emulated,
8621 	.write_emulated      = emulator_write_emulated,
8622 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8623 	.invlpg              = emulator_invlpg,
8624 	.pio_in_emulated     = emulator_pio_in_emulated,
8625 	.pio_out_emulated    = emulator_pio_out_emulated,
8626 	.get_segment         = emulator_get_segment,
8627 	.set_segment         = emulator_set_segment,
8628 	.get_cached_segment_base = emulator_get_cached_segment_base,
8629 	.get_gdt             = emulator_get_gdt,
8630 	.get_idt	     = emulator_get_idt,
8631 	.set_gdt             = emulator_set_gdt,
8632 	.set_idt	     = emulator_set_idt,
8633 	.get_cr              = emulator_get_cr,
8634 	.set_cr              = emulator_set_cr,
8635 	.cpl                 = emulator_get_cpl,
8636 	.get_dr              = emulator_get_dr,
8637 	.set_dr              = emulator_set_dr,
8638 	.set_msr_with_filter = emulator_set_msr_with_filter,
8639 	.get_msr_with_filter = emulator_get_msr_with_filter,
8640 	.get_msr             = emulator_get_msr,
8641 	.check_rdpmc_early   = emulator_check_rdpmc_early,
8642 	.read_pmc            = emulator_read_pmc,
8643 	.halt                = emulator_halt,
8644 	.wbinvd              = emulator_wbinvd,
8645 	.fix_hypercall       = emulator_fix_hypercall,
8646 	.intercept           = emulator_intercept,
8647 	.get_cpuid           = emulator_get_cpuid,
8648 	.guest_has_movbe     = emulator_guest_has_movbe,
8649 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8650 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8651 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8652 	.set_nmi_mask        = emulator_set_nmi_mask,
8653 	.is_smm              = emulator_is_smm,
8654 	.is_guest_mode       = emulator_is_guest_mode,
8655 	.leave_smm           = emulator_leave_smm,
8656 	.triple_fault        = emulator_triple_fault,
8657 	.set_xcr             = emulator_set_xcr,
8658 	.get_untagged_addr   = emulator_get_untagged_addr,
8659 	.is_canonical_addr   = emulator_is_canonical_addr,
8660 };
8661 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8662 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8663 {
8664 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8665 	/*
8666 	 * an sti; sti; sequence only disable interrupts for the first
8667 	 * instruction. So, if the last instruction, be it emulated or
8668 	 * not, left the system with the INT_STI flag enabled, it
8669 	 * means that the last instruction is an sti. We should not
8670 	 * leave the flag on in this case. The same goes for mov ss
8671 	 */
8672 	if (int_shadow & mask)
8673 		mask = 0;
8674 	if (unlikely(int_shadow || mask)) {
8675 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8676 		if (!mask)
8677 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8678 	}
8679 }
8680 
inject_emulated_exception(struct kvm_vcpu * vcpu)8681 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8682 {
8683 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8684 
8685 	if (ctxt->exception.vector == PF_VECTOR)
8686 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8687 	else if (ctxt->exception.error_code_valid)
8688 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8689 				      ctxt->exception.error_code);
8690 	else
8691 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8692 }
8693 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8694 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8695 {
8696 	struct x86_emulate_ctxt *ctxt;
8697 
8698 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8699 	if (!ctxt) {
8700 		pr_err("failed to allocate vcpu's emulator\n");
8701 		return NULL;
8702 	}
8703 
8704 	ctxt->vcpu = vcpu;
8705 	ctxt->ops = &emulate_ops;
8706 	vcpu->arch.emulate_ctxt = ctxt;
8707 
8708 	return ctxt;
8709 }
8710 
init_emulate_ctxt(struct kvm_vcpu * vcpu)8711 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8712 {
8713 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8714 	int cs_db, cs_l;
8715 
8716 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8717 
8718 	ctxt->gpa_available = false;
8719 	ctxt->eflags = kvm_get_rflags(vcpu);
8720 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8721 
8722 	ctxt->eip = kvm_rip_read(vcpu);
8723 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8724 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8725 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8726 		     cs_db				? X86EMUL_MODE_PROT32 :
8727 							  X86EMUL_MODE_PROT16;
8728 	ctxt->interruptibility = 0;
8729 	ctxt->have_exception = false;
8730 	ctxt->exception.vector = -1;
8731 	ctxt->perm_ok = false;
8732 
8733 	init_decode_cache(ctxt);
8734 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8735 }
8736 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8737 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8738 {
8739 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8740 	int ret;
8741 
8742 	init_emulate_ctxt(vcpu);
8743 
8744 	ctxt->op_bytes = 2;
8745 	ctxt->ad_bytes = 2;
8746 	ctxt->_eip = ctxt->eip + inc_eip;
8747 	ret = emulate_int_real(ctxt, irq);
8748 
8749 	if (ret != X86EMUL_CONTINUE) {
8750 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8751 	} else {
8752 		ctxt->eip = ctxt->_eip;
8753 		kvm_rip_write(vcpu, ctxt->eip);
8754 		kvm_set_rflags(vcpu, ctxt->eflags);
8755 	}
8756 }
8757 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8758 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)8759 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8760 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
8761 {
8762 	struct kvm_run *run = vcpu->run;
8763 	u64 info[5];
8764 	u8 info_start;
8765 
8766 	/*
8767 	 * Zero the whole array used to retrieve the exit info, as casting to
8768 	 * u32 for select entries will leave some chunks uninitialized.
8769 	 */
8770 	memset(&info, 0, sizeof(info));
8771 
8772 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
8773 				    (u32 *)&info[3], (u32 *)&info[4]);
8774 
8775 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8776 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8777 
8778 	/*
8779 	 * There's currently space for 13 entries, but 5 are used for the exit
8780 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
8781 	 * when expanding kvm_run.emulation_failure in the future.
8782 	 */
8783 	if (WARN_ON_ONCE(ndata > 4))
8784 		ndata = 4;
8785 
8786 	/* Always include the flags as a 'data' entry. */
8787 	info_start = 1;
8788 	run->emulation_failure.flags = 0;
8789 
8790 	if (insn_size) {
8791 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8792 			      sizeof(run->emulation_failure.insn_bytes) != 16));
8793 		info_start += 2;
8794 		run->emulation_failure.flags |=
8795 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8796 		run->emulation_failure.insn_size = insn_size;
8797 		memset(run->emulation_failure.insn_bytes, 0x90,
8798 		       sizeof(run->emulation_failure.insn_bytes));
8799 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8800 	}
8801 
8802 	memcpy(&run->internal.data[info_start], info, sizeof(info));
8803 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8804 	       ndata * sizeof(data[0]));
8805 
8806 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8807 }
8808 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)8809 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8810 {
8811 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8812 
8813 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8814 				       ctxt->fetch.end - ctxt->fetch.data);
8815 }
8816 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)8817 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8818 					  u8 ndata)
8819 {
8820 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8821 }
8822 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8823 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)8824 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8825 {
8826 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8827 }
8828 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8829 
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)8830 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
8831 {
8832 	u32 reason, intr_info, error_code;
8833 	struct kvm_run *run = vcpu->run;
8834 	u64 info1, info2;
8835 	int ndata = 0;
8836 
8837 	kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
8838 				    &intr_info, &error_code);
8839 
8840 	run->internal.data[ndata++] = info2;
8841 	run->internal.data[ndata++] = reason;
8842 	run->internal.data[ndata++] = info1;
8843 	run->internal.data[ndata++] = gpa;
8844 	run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
8845 
8846 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8847 	run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8848 	run->internal.ndata = ndata;
8849 }
8850 EXPORT_SYMBOL_GPL(kvm_prepare_event_vectoring_exit);
8851 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)8852 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8853 {
8854 	struct kvm *kvm = vcpu->kvm;
8855 
8856 	++vcpu->stat.insn_emulation_fail;
8857 	trace_kvm_emulate_insn_failed(vcpu);
8858 
8859 	if (emulation_type & EMULTYPE_VMWARE_GP) {
8860 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8861 		return 1;
8862 	}
8863 
8864 	if (kvm->arch.exit_on_emulation_error ||
8865 	    (emulation_type & EMULTYPE_SKIP)) {
8866 		prepare_emulation_ctxt_failure_exit(vcpu);
8867 		return 0;
8868 	}
8869 
8870 	kvm_queue_exception(vcpu, UD_VECTOR);
8871 
8872 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
8873 		prepare_emulation_ctxt_failure_exit(vcpu);
8874 		return 0;
8875 	}
8876 
8877 	return 1;
8878 }
8879 
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)8880 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
8881 					       gpa_t cr2_or_gpa,
8882 					       int emulation_type)
8883 {
8884 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8885 		return false;
8886 
8887 	/*
8888 	 * If the failed instruction faulted on an access to page tables that
8889 	 * are used to translate any part of the instruction, KVM can't resolve
8890 	 * the issue by unprotecting the gfn, as zapping the shadow page will
8891 	 * result in the instruction taking a !PRESENT page fault and thus put
8892 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
8893 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8894 	 * then zap the SPTE to unprotect the gfn, and then do it all over
8895 	 * again.  Report the error to userspace.
8896 	 */
8897 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
8898 		return false;
8899 
8900 	/*
8901 	 * If emulation may have been triggered by a write to a shadowed page
8902 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8903 	 * guest to let the CPU re-execute the instruction in the hope that the
8904 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
8905 	 */
8906 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
8907 
8908 	/*
8909 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
8910 	 * all SPTEs were already zapped by a different task.  The alternative
8911 	 * is to report the error to userspace and likely terminate the guest,
8912 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
8913 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
8914 	 */
8915 	return true;
8916 }
8917 
8918 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8919 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8920 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)8921 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8922 				unsigned long *db)
8923 {
8924 	u32 dr6 = 0;
8925 	int i;
8926 	u32 enable, rwlen;
8927 
8928 	enable = dr7;
8929 	rwlen = dr7 >> 16;
8930 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8931 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8932 			dr6 |= (1 << i);
8933 	return dr6;
8934 }
8935 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)8936 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8937 {
8938 	struct kvm_run *kvm_run = vcpu->run;
8939 
8940 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8941 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8942 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8943 		kvm_run->debug.arch.exception = DB_VECTOR;
8944 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
8945 		return 0;
8946 	}
8947 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8948 	return 1;
8949 }
8950 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)8951 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8952 {
8953 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
8954 	int r;
8955 
8956 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
8957 	if (unlikely(!r))
8958 		return 0;
8959 
8960 	kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
8961 
8962 	/*
8963 	 * rflags is the old, "raw" value of the flags.  The new value has
8964 	 * not been saved yet.
8965 	 *
8966 	 * This is correct even for TF set by the guest, because "the
8967 	 * processor will not generate this exception after the instruction
8968 	 * that sets the TF flag".
8969 	 */
8970 	if (unlikely(rflags & X86_EFLAGS_TF))
8971 		r = kvm_vcpu_do_singlestep(vcpu);
8972 	return r;
8973 }
8974 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8975 
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)8976 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
8977 {
8978 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8979 		return true;
8980 
8981 	/*
8982 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
8983 	 * active, but AMD compatible CPUs do not.
8984 	 */
8985 	if (!guest_cpuid_is_intel_compatible(vcpu))
8986 		return false;
8987 
8988 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
8989 }
8990 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)8991 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8992 					   int emulation_type, int *r)
8993 {
8994 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8995 
8996 	/*
8997 	 * Do not check for code breakpoints if hardware has already done the
8998 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
8999 	 * the instruction has passed all exception checks, and all intercepted
9000 	 * exceptions that trigger emulation have lower priority than code
9001 	 * breakpoints, i.e. the fact that the intercepted exception occurred
9002 	 * means any code breakpoints have already been serviced.
9003 	 *
9004 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9005 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
9006 	 * the instruction being emulated.  The intent of forced emulation is
9007 	 * to behave as if KVM intercepted the instruction without an exception
9008 	 * and without a prefix.
9009 	 */
9010 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9011 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9012 		return false;
9013 
9014 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9015 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9016 		struct kvm_run *kvm_run = vcpu->run;
9017 		unsigned long eip = kvm_get_linear_rip(vcpu);
9018 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9019 					   vcpu->arch.guest_debug_dr7,
9020 					   vcpu->arch.eff_db);
9021 
9022 		if (dr6 != 0) {
9023 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9024 			kvm_run->debug.arch.pc = eip;
9025 			kvm_run->debug.arch.exception = DB_VECTOR;
9026 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
9027 			*r = 0;
9028 			return true;
9029 		}
9030 	}
9031 
9032 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9033 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
9034 		unsigned long eip = kvm_get_linear_rip(vcpu);
9035 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9036 					   vcpu->arch.dr7,
9037 					   vcpu->arch.db);
9038 
9039 		if (dr6 != 0) {
9040 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9041 			*r = 1;
9042 			return true;
9043 		}
9044 	}
9045 
9046 	return false;
9047 }
9048 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9049 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9050 {
9051 	switch (ctxt->opcode_len) {
9052 	case 1:
9053 		switch (ctxt->b) {
9054 		case 0xe4:	/* IN */
9055 		case 0xe5:
9056 		case 0xec:
9057 		case 0xed:
9058 		case 0xe6:	/* OUT */
9059 		case 0xe7:
9060 		case 0xee:
9061 		case 0xef:
9062 		case 0x6c:	/* INS */
9063 		case 0x6d:
9064 		case 0x6e:	/* OUTS */
9065 		case 0x6f:
9066 			return true;
9067 		}
9068 		break;
9069 	case 2:
9070 		switch (ctxt->b) {
9071 		case 0x33:	/* RDPMC */
9072 			return true;
9073 		}
9074 		break;
9075 	}
9076 
9077 	return false;
9078 }
9079 
9080 /*
9081  * Decode an instruction for emulation.  The caller is responsible for handling
9082  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
9083  * (and wrong) when emulating on an intercepted fault-like exception[*], as
9084  * code breakpoints have higher priority and thus have already been done by
9085  * hardware.
9086  *
9087  * [*] Except #MC, which is higher priority, but KVM should never emulate in
9088  *     response to a machine check.
9089  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9090 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9091 				    void *insn, int insn_len)
9092 {
9093 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9094 	int r;
9095 
9096 	init_emulate_ctxt(vcpu);
9097 
9098 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9099 
9100 	trace_kvm_emulate_insn_start(vcpu);
9101 	++vcpu->stat.insn_emulation;
9102 
9103 	return r;
9104 }
9105 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9106 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9107 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9108 			    int emulation_type, void *insn, int insn_len)
9109 {
9110 	int r;
9111 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9112 	bool writeback = true;
9113 
9114 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9115 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9116 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9117 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9118 
9119 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9120 	if (r != X86EMUL_CONTINUE) {
9121 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9122 			return 1;
9123 
9124 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9125 						       emulation_type))
9126 			return 1;
9127 
9128 		if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9129 			kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9130 			return 0;
9131 		}
9132 
9133 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9134 		return handle_emulation_failure(vcpu, emulation_type);
9135 	}
9136 
9137 	vcpu->arch.l1tf_flush_l1d = true;
9138 
9139 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9140 		kvm_clear_exception_queue(vcpu);
9141 
9142 		/*
9143 		 * Return immediately if RIP hits a code breakpoint, such #DBs
9144 		 * are fault-like and are higher priority than any faults on
9145 		 * the code fetch itself.
9146 		 */
9147 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9148 			return r;
9149 
9150 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
9151 						    insn, insn_len);
9152 		if (r != EMULATION_OK)  {
9153 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
9154 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9155 				kvm_queue_exception(vcpu, UD_VECTOR);
9156 				return 1;
9157 			}
9158 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9159 							       emulation_type))
9160 				return 1;
9161 
9162 			if (ctxt->have_exception &&
9163 			    !(emulation_type & EMULTYPE_SKIP)) {
9164 				/*
9165 				 * #UD should result in just EMULATION_FAILED, and trap-like
9166 				 * exception should not be encountered during decode.
9167 				 */
9168 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9169 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9170 				inject_emulated_exception(vcpu);
9171 				return 1;
9172 			}
9173 			return handle_emulation_failure(vcpu, emulation_type);
9174 		}
9175 	}
9176 
9177 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9178 	    !is_vmware_backdoor_opcode(ctxt)) {
9179 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9180 		return 1;
9181 	}
9182 
9183 	/*
9184 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9185 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9186 	 * The caller is responsible for updating interruptibility state and
9187 	 * injecting single-step #DBs.
9188 	 */
9189 	if (emulation_type & EMULTYPE_SKIP) {
9190 		if (ctxt->mode != X86EMUL_MODE_PROT64)
9191 			ctxt->eip = (u32)ctxt->_eip;
9192 		else
9193 			ctxt->eip = ctxt->_eip;
9194 
9195 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9196 			r = 1;
9197 			goto writeback;
9198 		}
9199 
9200 		kvm_rip_write(vcpu, ctxt->eip);
9201 		if (ctxt->eflags & X86_EFLAGS_RF)
9202 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9203 		return 1;
9204 	}
9205 
9206 	/*
9207 	 * If emulation was caused by a write-protection #PF on a non-page_table
9208 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9209 	 * and retry the instruction, as the vCPU is likely no longer using the
9210 	 * gfn as a page table.
9211 	 */
9212 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9213 	    !x86_page_table_writing_insn(ctxt) &&
9214 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9215 		return 1;
9216 
9217 	/* this is needed for vmware backdoor interface to work since it
9218 	   changes registers values  during IO operation */
9219 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9220 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9221 		emulator_invalidate_register_cache(ctxt);
9222 	}
9223 
9224 restart:
9225 	if (emulation_type & EMULTYPE_PF) {
9226 		/* Save the faulting GPA (cr2) in the address field */
9227 		ctxt->exception.address = cr2_or_gpa;
9228 
9229 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
9230 		if (vcpu->arch.mmu->root_role.direct) {
9231 			ctxt->gpa_available = true;
9232 			ctxt->gpa_val = cr2_or_gpa;
9233 		}
9234 	} else {
9235 		/* Sanitize the address out of an abundance of paranoia. */
9236 		ctxt->exception.address = 0;
9237 	}
9238 
9239 	r = x86_emulate_insn(ctxt);
9240 
9241 	if (r == EMULATION_INTERCEPTED)
9242 		return 1;
9243 
9244 	if (r == EMULATION_FAILED) {
9245 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9246 						       emulation_type))
9247 			return 1;
9248 
9249 		return handle_emulation_failure(vcpu, emulation_type);
9250 	}
9251 
9252 	if (ctxt->have_exception) {
9253 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9254 		vcpu->mmio_needed = false;
9255 		r = 1;
9256 		inject_emulated_exception(vcpu);
9257 	} else if (vcpu->arch.pio.count) {
9258 		if (!vcpu->arch.pio.in) {
9259 			/* FIXME: return into emulator if single-stepping.  */
9260 			vcpu->arch.pio.count = 0;
9261 		} else {
9262 			writeback = false;
9263 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
9264 		}
9265 		r = 0;
9266 	} else if (vcpu->mmio_needed) {
9267 		++vcpu->stat.mmio_exits;
9268 
9269 		if (!vcpu->mmio_is_write)
9270 			writeback = false;
9271 		r = 0;
9272 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9273 	} else if (vcpu->arch.complete_userspace_io) {
9274 		writeback = false;
9275 		r = 0;
9276 	} else if (r == EMULATION_RESTART)
9277 		goto restart;
9278 	else
9279 		r = 1;
9280 
9281 writeback:
9282 	if (writeback) {
9283 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9284 		toggle_interruptibility(vcpu, ctxt->interruptibility);
9285 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9286 
9287 		/*
9288 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9289 		 * only supports code breakpoints and general detect #DB, both
9290 		 * of which are fault-like.
9291 		 */
9292 		if (!ctxt->have_exception ||
9293 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9294 			kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9295 			if (ctxt->is_branch)
9296 				kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
9297 			kvm_rip_write(vcpu, ctxt->eip);
9298 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9299 				r = kvm_vcpu_do_singlestep(vcpu);
9300 			kvm_x86_call(update_emulated_instruction)(vcpu);
9301 			__kvm_set_rflags(vcpu, ctxt->eflags);
9302 		}
9303 
9304 		/*
9305 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9306 		 * do nothing, and it will be requested again as soon as
9307 		 * the shadow expires.  But we still need to check here,
9308 		 * because POPF has no interrupt shadow.
9309 		 */
9310 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9311 			kvm_make_request(KVM_REQ_EVENT, vcpu);
9312 	} else
9313 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9314 
9315 	return r;
9316 }
9317 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9318 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9319 {
9320 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9321 }
9322 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9323 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9324 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9325 					void *insn, int insn_len)
9326 {
9327 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9328 }
9329 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9330 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9331 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9332 {
9333 	vcpu->arch.pio.count = 0;
9334 	return 1;
9335 }
9336 
complete_fast_pio_out(struct kvm_vcpu * vcpu)9337 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9338 {
9339 	vcpu->arch.pio.count = 0;
9340 
9341 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
9342 		return 1;
9343 
9344 	return kvm_skip_emulated_instruction(vcpu);
9345 }
9346 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9347 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9348 			    unsigned short port)
9349 {
9350 	unsigned long val = kvm_rax_read(vcpu);
9351 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9352 
9353 	if (ret)
9354 		return ret;
9355 
9356 	/*
9357 	 * Workaround userspace that relies on old KVM behavior of %rip being
9358 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9359 	 */
9360 	if (port == 0x7e &&
9361 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9362 		vcpu->arch.complete_userspace_io =
9363 			complete_fast_pio_out_port_0x7e;
9364 		kvm_skip_emulated_instruction(vcpu);
9365 	} else {
9366 		vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9367 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9368 	}
9369 	return 0;
9370 }
9371 
complete_fast_pio_in(struct kvm_vcpu * vcpu)9372 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9373 {
9374 	unsigned long val;
9375 
9376 	/* We should only ever be called with arch.pio.count equal to 1 */
9377 	BUG_ON(vcpu->arch.pio.count != 1);
9378 
9379 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
9380 		vcpu->arch.pio.count = 0;
9381 		return 1;
9382 	}
9383 
9384 	/* For size less than 4 we merge, else we zero extend */
9385 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9386 
9387 	complete_emulator_pio_in(vcpu, &val);
9388 	kvm_rax_write(vcpu, val);
9389 
9390 	return kvm_skip_emulated_instruction(vcpu);
9391 }
9392 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9393 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9394 			   unsigned short port)
9395 {
9396 	unsigned long val;
9397 	int ret;
9398 
9399 	/* For size less than 4 we merge, else we zero extend */
9400 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9401 
9402 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
9403 	if (ret) {
9404 		kvm_rax_write(vcpu, val);
9405 		return ret;
9406 	}
9407 
9408 	vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9409 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9410 
9411 	return 0;
9412 }
9413 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9414 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9415 {
9416 	int ret;
9417 
9418 	if (in)
9419 		ret = kvm_fast_pio_in(vcpu, size, port);
9420 	else
9421 		ret = kvm_fast_pio_out(vcpu, size, port);
9422 	return ret && kvm_skip_emulated_instruction(vcpu);
9423 }
9424 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9425 
kvmclock_cpu_down_prep(unsigned int cpu)9426 static int kvmclock_cpu_down_prep(unsigned int cpu)
9427 {
9428 	__this_cpu_write(cpu_tsc_khz, 0);
9429 	return 0;
9430 }
9431 
tsc_khz_changed(void * data)9432 static void tsc_khz_changed(void *data)
9433 {
9434 	struct cpufreq_freqs *freq = data;
9435 	unsigned long khz;
9436 
9437 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9438 
9439 	if (data)
9440 		khz = freq->new;
9441 	else
9442 		khz = cpufreq_quick_get(raw_smp_processor_id());
9443 	if (!khz)
9444 		khz = tsc_khz;
9445 	__this_cpu_write(cpu_tsc_khz, khz);
9446 }
9447 
9448 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9449 static void kvm_hyperv_tsc_notifier(void)
9450 {
9451 	struct kvm *kvm;
9452 	int cpu;
9453 
9454 	mutex_lock(&kvm_lock);
9455 	list_for_each_entry(kvm, &vm_list, vm_list)
9456 		kvm_make_mclock_inprogress_request(kvm);
9457 
9458 	/* no guest entries from this point */
9459 	hyperv_stop_tsc_emulation();
9460 
9461 	/* TSC frequency always matches when on Hyper-V */
9462 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9463 		for_each_present_cpu(cpu)
9464 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9465 	}
9466 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9467 
9468 	list_for_each_entry(kvm, &vm_list, vm_list) {
9469 		__kvm_start_pvclock_update(kvm);
9470 		pvclock_update_vm_gtod_copy(kvm);
9471 		kvm_end_pvclock_update(kvm);
9472 	}
9473 
9474 	mutex_unlock(&kvm_lock);
9475 }
9476 #endif
9477 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9478 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9479 {
9480 	struct kvm *kvm;
9481 	struct kvm_vcpu *vcpu;
9482 	int send_ipi = 0;
9483 	unsigned long i;
9484 
9485 	/*
9486 	 * We allow guests to temporarily run on slowing clocks,
9487 	 * provided we notify them after, or to run on accelerating
9488 	 * clocks, provided we notify them before.  Thus time never
9489 	 * goes backwards.
9490 	 *
9491 	 * However, we have a problem.  We can't atomically update
9492 	 * the frequency of a given CPU from this function; it is
9493 	 * merely a notifier, which can be called from any CPU.
9494 	 * Changing the TSC frequency at arbitrary points in time
9495 	 * requires a recomputation of local variables related to
9496 	 * the TSC for each VCPU.  We must flag these local variables
9497 	 * to be updated and be sure the update takes place with the
9498 	 * new frequency before any guests proceed.
9499 	 *
9500 	 * Unfortunately, the combination of hotplug CPU and frequency
9501 	 * change creates an intractable locking scenario; the order
9502 	 * of when these callouts happen is undefined with respect to
9503 	 * CPU hotplug, and they can race with each other.  As such,
9504 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9505 	 * undefined; you can actually have a CPU frequency change take
9506 	 * place in between the computation of X and the setting of the
9507 	 * variable.  To protect against this problem, all updates of
9508 	 * the per_cpu tsc_khz variable are done in an interrupt
9509 	 * protected IPI, and all callers wishing to update the value
9510 	 * must wait for a synchronous IPI to complete (which is trivial
9511 	 * if the caller is on the CPU already).  This establishes the
9512 	 * necessary total order on variable updates.
9513 	 *
9514 	 * Note that because a guest time update may take place
9515 	 * anytime after the setting of the VCPU's request bit, the
9516 	 * correct TSC value must be set before the request.  However,
9517 	 * to ensure the update actually makes it to any guest which
9518 	 * starts running in hardware virtualization between the set
9519 	 * and the acquisition of the spinlock, we must also ping the
9520 	 * CPU after setting the request bit.
9521 	 *
9522 	 */
9523 
9524 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9525 
9526 	mutex_lock(&kvm_lock);
9527 	list_for_each_entry(kvm, &vm_list, vm_list) {
9528 		kvm_for_each_vcpu(i, vcpu, kvm) {
9529 			if (vcpu->cpu != cpu)
9530 				continue;
9531 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9532 			if (vcpu->cpu != raw_smp_processor_id())
9533 				send_ipi = 1;
9534 		}
9535 	}
9536 	mutex_unlock(&kvm_lock);
9537 
9538 	if (freq->old < freq->new && send_ipi) {
9539 		/*
9540 		 * We upscale the frequency.  Must make the guest
9541 		 * doesn't see old kvmclock values while running with
9542 		 * the new frequency, otherwise we risk the guest sees
9543 		 * time go backwards.
9544 		 *
9545 		 * In case we update the frequency for another cpu
9546 		 * (which might be in guest context) send an interrupt
9547 		 * to kick the cpu out of guest context.  Next time
9548 		 * guest context is entered kvmclock will be updated,
9549 		 * so the guest will not see stale values.
9550 		 */
9551 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9552 	}
9553 }
9554 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9555 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9556 				     void *data)
9557 {
9558 	struct cpufreq_freqs *freq = data;
9559 	int cpu;
9560 
9561 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9562 		return 0;
9563 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9564 		return 0;
9565 
9566 	for_each_cpu(cpu, freq->policy->cpus)
9567 		__kvmclock_cpufreq_notifier(freq, cpu);
9568 
9569 	return 0;
9570 }
9571 
9572 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9573 	.notifier_call  = kvmclock_cpufreq_notifier
9574 };
9575 
kvmclock_cpu_online(unsigned int cpu)9576 static int kvmclock_cpu_online(unsigned int cpu)
9577 {
9578 	tsc_khz_changed(NULL);
9579 	return 0;
9580 }
9581 
kvm_timer_init(void)9582 static void kvm_timer_init(void)
9583 {
9584 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9585 		max_tsc_khz = tsc_khz;
9586 
9587 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9588 			struct cpufreq_policy *policy;
9589 			int cpu;
9590 
9591 			cpu = get_cpu();
9592 			policy = cpufreq_cpu_get(cpu);
9593 			if (policy) {
9594 				if (policy->cpuinfo.max_freq)
9595 					max_tsc_khz = policy->cpuinfo.max_freq;
9596 				cpufreq_cpu_put(policy);
9597 			}
9598 			put_cpu();
9599 		}
9600 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9601 					  CPUFREQ_TRANSITION_NOTIFIER);
9602 
9603 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9604 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9605 	}
9606 }
9607 
9608 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9609 static void pvclock_gtod_update_fn(struct work_struct *work)
9610 {
9611 	struct kvm *kvm;
9612 	struct kvm_vcpu *vcpu;
9613 	unsigned long i;
9614 
9615 	mutex_lock(&kvm_lock);
9616 	list_for_each_entry(kvm, &vm_list, vm_list)
9617 		kvm_for_each_vcpu(i, vcpu, kvm)
9618 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9619 	atomic_set(&kvm_guest_has_master_clock, 0);
9620 	mutex_unlock(&kvm_lock);
9621 }
9622 
9623 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9624 
9625 /*
9626  * Indirection to move queue_work() out of the tk_core.seq write held
9627  * region to prevent possible deadlocks against time accessors which
9628  * are invoked with work related locks held.
9629  */
pvclock_irq_work_fn(struct irq_work * w)9630 static void pvclock_irq_work_fn(struct irq_work *w)
9631 {
9632 	queue_work(system_long_wq, &pvclock_gtod_work);
9633 }
9634 
9635 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9636 
9637 /*
9638  * Notification about pvclock gtod data update.
9639  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9640 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9641 			       void *priv)
9642 {
9643 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9644 	struct timekeeper *tk = priv;
9645 
9646 	update_pvclock_gtod(tk);
9647 
9648 	/*
9649 	 * Disable master clock if host does not trust, or does not use,
9650 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9651 	 * this is invoked with tk_core.seq write held.
9652 	 */
9653 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9654 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9655 		irq_work_queue(&pvclock_irq_work);
9656 	return 0;
9657 }
9658 
9659 static struct notifier_block pvclock_gtod_notifier = {
9660 	.notifier_call = pvclock_gtod_notify,
9661 };
9662 #endif
9663 
kvm_ops_update(struct kvm_x86_init_ops * ops)9664 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9665 {
9666 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9667 
9668 #define __KVM_X86_OP(func) \
9669 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9670 #define KVM_X86_OP(func) \
9671 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9672 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9673 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9674 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9675 					   (void *)__static_call_return0);
9676 #include <asm/kvm-x86-ops.h>
9677 #undef __KVM_X86_OP
9678 
9679 	kvm_pmu_ops_update(ops->pmu_ops);
9680 }
9681 
kvm_x86_check_processor_compatibility(void)9682 static int kvm_x86_check_processor_compatibility(void)
9683 {
9684 	int cpu = smp_processor_id();
9685 	struct cpuinfo_x86 *c = &cpu_data(cpu);
9686 
9687 	/*
9688 	 * Compatibility checks are done when loading KVM and when enabling
9689 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9690 	 * compatible, i.e. KVM should never perform a compatibility check on
9691 	 * an offline CPU.
9692 	 */
9693 	WARN_ON(!cpu_online(cpu));
9694 
9695 	if (__cr4_reserved_bits(cpu_has, c) !=
9696 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9697 		return -EIO;
9698 
9699 	return kvm_x86_call(check_processor_compatibility)();
9700 }
9701 
kvm_x86_check_cpu_compat(void * ret)9702 static void kvm_x86_check_cpu_compat(void *ret)
9703 {
9704 	*(int *)ret = kvm_x86_check_processor_compatibility();
9705 }
9706 
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9707 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9708 {
9709 	u64 host_pat;
9710 	int r, cpu;
9711 
9712 	guard(mutex)(&vendor_module_lock);
9713 
9714 	if (kvm_x86_ops.enable_virtualization_cpu) {
9715 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9716 		return -EEXIST;
9717 	}
9718 
9719 	/*
9720 	 * KVM explicitly assumes that the guest has an FPU and
9721 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9722 	 * vCPU's FPU state as a fxregs_state struct.
9723 	 */
9724 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9725 		pr_err("inadequate fpu\n");
9726 		return -EOPNOTSUPP;
9727 	}
9728 
9729 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9730 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9731 		return -EOPNOTSUPP;
9732 	}
9733 
9734 	/*
9735 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9736 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
9737 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
9738 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
9739 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9740 	 */
9741 	if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9742 	    (host_pat & GENMASK(2, 0)) != 6) {
9743 		pr_err("host PAT[0] is not WB\n");
9744 		return -EIO;
9745 	}
9746 
9747 	memset(&kvm_caps, 0, sizeof(kvm_caps));
9748 
9749 	x86_emulator_cache = kvm_alloc_emulator_cache();
9750 	if (!x86_emulator_cache) {
9751 		pr_err("failed to allocate cache for x86 emulator\n");
9752 		return -ENOMEM;
9753 	}
9754 
9755 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9756 	if (!user_return_msrs) {
9757 		pr_err("failed to allocate percpu kvm_user_return_msrs\n");
9758 		r = -ENOMEM;
9759 		goto out_free_x86_emulator_cache;
9760 	}
9761 	kvm_nr_uret_msrs = 0;
9762 
9763 	r = kvm_mmu_vendor_module_init();
9764 	if (r)
9765 		goto out_free_percpu;
9766 
9767 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
9768 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
9769 
9770 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9771 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9772 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
9773 	}
9774 
9775 	rdmsrl_safe(MSR_EFER, &kvm_host.efer);
9776 
9777 	if (boot_cpu_has(X86_FEATURE_XSAVES))
9778 		rdmsrl(MSR_IA32_XSS, kvm_host.xss);
9779 
9780 	kvm_init_pmu_capability(ops->pmu_ops);
9781 
9782 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
9783 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
9784 
9785 	r = ops->hardware_setup();
9786 	if (r != 0)
9787 		goto out_mmu_exit;
9788 
9789 	kvm_ops_update(ops);
9790 
9791 	for_each_online_cpu(cpu) {
9792 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
9793 		if (r < 0)
9794 			goto out_unwind_ops;
9795 	}
9796 
9797 	/*
9798 	 * Point of no return!  DO NOT add error paths below this point unless
9799 	 * absolutely necessary, as most operations from this point forward
9800 	 * require unwinding.
9801 	 */
9802 	kvm_timer_init();
9803 
9804 	if (pi_inject_timer == -1)
9805 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9806 #ifdef CONFIG_X86_64
9807 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9808 
9809 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9810 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9811 #endif
9812 
9813 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9814 
9815 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9816 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9817 
9818 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9819 		kvm_caps.supported_xss = 0;
9820 
9821 	if (kvm_caps.has_tsc_control) {
9822 		/*
9823 		 * Make sure the user can only configure tsc_khz values that
9824 		 * fit into a signed integer.
9825 		 * A min value is not calculated because it will always
9826 		 * be 1 on all machines.
9827 		 */
9828 		u64 max = min(0x7fffffffULL,
9829 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9830 		kvm_caps.max_guest_tsc_khz = max;
9831 	}
9832 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9833 	kvm_init_msr_lists();
9834 	return 0;
9835 
9836 out_unwind_ops:
9837 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9838 	kvm_x86_call(hardware_unsetup)();
9839 out_mmu_exit:
9840 	kvm_mmu_vendor_module_exit();
9841 out_free_percpu:
9842 	free_percpu(user_return_msrs);
9843 out_free_x86_emulator_cache:
9844 	kmem_cache_destroy(x86_emulator_cache);
9845 	return r;
9846 }
9847 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9848 
kvm_x86_vendor_exit(void)9849 void kvm_x86_vendor_exit(void)
9850 {
9851 	kvm_unregister_perf_callbacks();
9852 
9853 #ifdef CONFIG_X86_64
9854 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9855 		clear_hv_tscchange_cb();
9856 #endif
9857 	kvm_lapic_exit();
9858 
9859 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9860 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9861 					    CPUFREQ_TRANSITION_NOTIFIER);
9862 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9863 	}
9864 #ifdef CONFIG_X86_64
9865 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9866 	irq_work_sync(&pvclock_irq_work);
9867 	cancel_work_sync(&pvclock_gtod_work);
9868 #endif
9869 	kvm_x86_call(hardware_unsetup)();
9870 	kvm_mmu_vendor_module_exit();
9871 	free_percpu(user_return_msrs);
9872 	kmem_cache_destroy(x86_emulator_cache);
9873 #ifdef CONFIG_KVM_XEN
9874 	static_key_deferred_flush(&kvm_xen_enabled);
9875 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9876 #endif
9877 	mutex_lock(&vendor_module_lock);
9878 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9879 	mutex_unlock(&vendor_module_lock);
9880 }
9881 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9882 
9883 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)9884 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9885 			        unsigned long clock_type)
9886 {
9887 	struct kvm_clock_pairing clock_pairing;
9888 	struct timespec64 ts;
9889 	u64 cycle;
9890 	int ret;
9891 
9892 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9893 		return -KVM_EOPNOTSUPP;
9894 
9895 	/*
9896 	 * When tsc is in permanent catchup mode guests won't be able to use
9897 	 * pvclock_read_retry loop to get consistent view of pvclock
9898 	 */
9899 	if (vcpu->arch.tsc_always_catchup)
9900 		return -KVM_EOPNOTSUPP;
9901 
9902 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9903 		return -KVM_EOPNOTSUPP;
9904 
9905 	clock_pairing.sec = ts.tv_sec;
9906 	clock_pairing.nsec = ts.tv_nsec;
9907 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9908 	clock_pairing.flags = 0;
9909 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9910 
9911 	ret = 0;
9912 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9913 			    sizeof(struct kvm_clock_pairing)))
9914 		ret = -KVM_EFAULT;
9915 
9916 	return ret;
9917 }
9918 #endif
9919 
9920 /*
9921  * kvm_pv_kick_cpu_op:  Kick a vcpu.
9922  *
9923  * @apicid - apicid of vcpu to be kicked.
9924  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)9925 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9926 {
9927 	/*
9928 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9929 	 * common code, e.g. for tracing. Defer initialization to the compiler.
9930 	 */
9931 	struct kvm_lapic_irq lapic_irq = {
9932 		.delivery_mode = APIC_DM_REMRD,
9933 		.dest_mode = APIC_DEST_PHYSICAL,
9934 		.shorthand = APIC_DEST_NOSHORT,
9935 		.dest_id = apicid,
9936 	};
9937 
9938 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9939 }
9940 
kvm_apicv_activated(struct kvm * kvm)9941 bool kvm_apicv_activated(struct kvm *kvm)
9942 {
9943 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9944 }
9945 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9946 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)9947 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9948 {
9949 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9950 	ulong vcpu_reasons =
9951 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
9952 
9953 	return (vm_reasons | vcpu_reasons) == 0;
9954 }
9955 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9956 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)9957 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9958 				       enum kvm_apicv_inhibit reason, bool set)
9959 {
9960 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
9961 
9962 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
9963 
9964 	if (set)
9965 		__set_bit(reason, inhibits);
9966 	else
9967 		__clear_bit(reason, inhibits);
9968 
9969 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9970 }
9971 
kvm_apicv_init(struct kvm * kvm)9972 static void kvm_apicv_init(struct kvm *kvm)
9973 {
9974 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
9975 						       APICV_INHIBIT_REASON_DISABLED;
9976 
9977 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
9978 
9979 	init_rwsem(&kvm->arch.apicv_update_lock);
9980 }
9981 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)9982 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9983 {
9984 	struct kvm_vcpu *target = NULL;
9985 	struct kvm_apic_map *map;
9986 
9987 	vcpu->stat.directed_yield_attempted++;
9988 
9989 	if (single_task_running())
9990 		goto no_yield;
9991 
9992 	rcu_read_lock();
9993 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
9994 
9995 	if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9996 		target = map->phys_map[dest_id]->vcpu;
9997 
9998 	rcu_read_unlock();
9999 
10000 	if (!target || !READ_ONCE(target->ready))
10001 		goto no_yield;
10002 
10003 	/* Ignore requests to yield to self */
10004 	if (vcpu == target)
10005 		goto no_yield;
10006 
10007 	if (kvm_vcpu_yield_to(target) <= 0)
10008 		goto no_yield;
10009 
10010 	vcpu->stat.directed_yield_successful++;
10011 
10012 no_yield:
10013 	return;
10014 }
10015 
complete_hypercall_exit(struct kvm_vcpu * vcpu)10016 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10017 {
10018 	u64 ret = vcpu->run->hypercall.ret;
10019 
10020 	if (!is_64_bit_hypercall(vcpu))
10021 		ret = (u32)ret;
10022 	kvm_rax_write(vcpu, ret);
10023 	return kvm_skip_emulated_instruction(vcpu);
10024 }
10025 
____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 *))10026 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, unsigned long nr,
10027 			      unsigned long a0, unsigned long a1,
10028 			      unsigned long a2, unsigned long a3,
10029 			      int op_64_bit, int cpl,
10030 			      int (*complete_hypercall)(struct kvm_vcpu *))
10031 {
10032 	unsigned long ret;
10033 
10034 	++vcpu->stat.hypercalls;
10035 
10036 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
10037 
10038 	if (!op_64_bit) {
10039 		nr &= 0xFFFFFFFF;
10040 		a0 &= 0xFFFFFFFF;
10041 		a1 &= 0xFFFFFFFF;
10042 		a2 &= 0xFFFFFFFF;
10043 		a3 &= 0xFFFFFFFF;
10044 	}
10045 
10046 	if (cpl) {
10047 		ret = -KVM_EPERM;
10048 		goto out;
10049 	}
10050 
10051 	ret = -KVM_ENOSYS;
10052 
10053 	switch (nr) {
10054 	case KVM_HC_VAPIC_POLL_IRQ:
10055 		ret = 0;
10056 		break;
10057 	case KVM_HC_KICK_CPU:
10058 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10059 			break;
10060 
10061 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10062 		kvm_sched_yield(vcpu, a1);
10063 		ret = 0;
10064 		break;
10065 #ifdef CONFIG_X86_64
10066 	case KVM_HC_CLOCK_PAIRING:
10067 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10068 		break;
10069 #endif
10070 	case KVM_HC_SEND_IPI:
10071 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10072 			break;
10073 
10074 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10075 		break;
10076 	case KVM_HC_SCHED_YIELD:
10077 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10078 			break;
10079 
10080 		kvm_sched_yield(vcpu, a0);
10081 		ret = 0;
10082 		break;
10083 	case KVM_HC_MAP_GPA_RANGE: {
10084 		u64 gpa = a0, npages = a1, attrs = a2;
10085 
10086 		ret = -KVM_ENOSYS;
10087 		if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10088 			break;
10089 
10090 		if (!PAGE_ALIGNED(gpa) || !npages ||
10091 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10092 			ret = -KVM_EINVAL;
10093 			break;
10094 		}
10095 
10096 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
10097 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
10098 		/*
10099 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10100 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10101 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
10102 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10103 		 */
10104 		vcpu->run->hypercall.ret = 0;
10105 		vcpu->run->hypercall.args[0]  = gpa;
10106 		vcpu->run->hypercall.args[1]  = npages;
10107 		vcpu->run->hypercall.args[2]  = attrs;
10108 		vcpu->run->hypercall.flags    = 0;
10109 		if (op_64_bit)
10110 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10111 
10112 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10113 		vcpu->arch.complete_userspace_io = complete_hypercall;
10114 		return 0;
10115 	}
10116 	default:
10117 		ret = -KVM_ENOSYS;
10118 		break;
10119 	}
10120 
10121 out:
10122 	vcpu->run->hypercall.ret = ret;
10123 	return 1;
10124 }
10125 EXPORT_SYMBOL_GPL(____kvm_emulate_hypercall);
10126 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10127 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10128 {
10129 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
10130 		return kvm_xen_hypercall(vcpu);
10131 
10132 	if (kvm_hv_hypercall_enabled(vcpu))
10133 		return kvm_hv_hypercall(vcpu);
10134 
10135 	return __kvm_emulate_hypercall(vcpu, rax, rbx, rcx, rdx, rsi,
10136 				       is_64_bit_hypercall(vcpu),
10137 				       kvm_x86_call(get_cpl)(vcpu),
10138 				       complete_hypercall_exit);
10139 }
10140 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10141 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10142 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10143 {
10144 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10145 	char instruction[3];
10146 	unsigned long rip = kvm_rip_read(vcpu);
10147 
10148 	/*
10149 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10150 	 * the pieces.
10151 	 */
10152 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10153 		ctxt->exception.error_code_valid = false;
10154 		ctxt->exception.vector = UD_VECTOR;
10155 		ctxt->have_exception = true;
10156 		return X86EMUL_PROPAGATE_FAULT;
10157 	}
10158 
10159 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
10160 
10161 	return emulator_write_emulated(ctxt, rip, instruction, 3,
10162 		&ctxt->exception);
10163 }
10164 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10165 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10166 {
10167 	return vcpu->run->request_interrupt_window &&
10168 		likely(!pic_in_kernel(vcpu->kvm));
10169 }
10170 
10171 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)10172 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10173 {
10174 	struct kvm_run *kvm_run = vcpu->run;
10175 
10176 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10177 	kvm_run->cr8 = kvm_get_cr8(vcpu);
10178 	kvm_run->apic_base = vcpu->arch.apic_base;
10179 
10180 	kvm_run->ready_for_interrupt_injection =
10181 		pic_in_kernel(vcpu->kvm) ||
10182 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
10183 
10184 	if (is_smm(vcpu))
10185 		kvm_run->flags |= KVM_RUN_X86_SMM;
10186 	if (is_guest_mode(vcpu))
10187 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10188 }
10189 
update_cr8_intercept(struct kvm_vcpu * vcpu)10190 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10191 {
10192 	int max_irr, tpr;
10193 
10194 	if (!kvm_x86_ops.update_cr8_intercept)
10195 		return;
10196 
10197 	if (!lapic_in_kernel(vcpu))
10198 		return;
10199 
10200 	if (vcpu->arch.apic->apicv_active)
10201 		return;
10202 
10203 	if (!vcpu->arch.apic->vapic_addr)
10204 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10205 	else
10206 		max_irr = -1;
10207 
10208 	if (max_irr != -1)
10209 		max_irr >>= 4;
10210 
10211 	tpr = kvm_lapic_get_cr8(vcpu);
10212 
10213 	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10214 }
10215 
10216 
kvm_check_nested_events(struct kvm_vcpu * vcpu)10217 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10218 {
10219 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10220 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
10221 		return 1;
10222 	}
10223 
10224 	return kvm_x86_ops.nested_ops->check_events(vcpu);
10225 }
10226 
kvm_inject_exception(struct kvm_vcpu * vcpu)10227 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10228 {
10229 	/*
10230 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10231 	 * exceptions don't report error codes.  The presence of an error code
10232 	 * is carried with the exception and only stripped when the exception
10233 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10234 	 * report an error code despite the CPU being in Real Mode.
10235 	 */
10236 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10237 
10238 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
10239 				vcpu->arch.exception.has_error_code,
10240 				vcpu->arch.exception.error_code,
10241 				vcpu->arch.exception.injected);
10242 
10243 	kvm_x86_call(inject_exception)(vcpu);
10244 }
10245 
10246 /*
10247  * Check for any event (interrupt or exception) that is ready to be injected,
10248  * and if there is at least one event, inject the event with the highest
10249  * priority.  This handles both "pending" events, i.e. events that have never
10250  * been injected into the guest, and "injected" events, i.e. events that were
10251  * injected as part of a previous VM-Enter, but weren't successfully delivered
10252  * and need to be re-injected.
10253  *
10254  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10255  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
10256  * be able to inject exceptions in the "middle" of an instruction, and so must
10257  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10258  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10259  * boundaries is necessary and correct.
10260  *
10261  * For simplicity, KVM uses a single path to inject all events (except events
10262  * that are injected directly from L1 to L2) and doesn't explicitly track
10263  * instruction boundaries for asynchronous events.  However, because VM-Exits
10264  * that can occur during instruction execution typically result in KVM skipping
10265  * the instruction or injecting an exception, e.g. instruction and exception
10266  * intercepts, and because pending exceptions have higher priority than pending
10267  * interrupts, KVM still honors instruction boundaries in most scenarios.
10268  *
10269  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10270  * the instruction or inject an exception, then KVM can incorrecty inject a new
10271  * asynchronous event if the event became pending after the CPU fetched the
10272  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
10273  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10274  * injected on the restarted instruction instead of being deferred until the
10275  * instruction completes.
10276  *
10277  * In practice, this virtualization hole is unlikely to be observed by the
10278  * guest, and even less likely to cause functional problems.  To detect the
10279  * hole, the guest would have to trigger an event on a side effect of an early
10280  * phase of instruction execution, e.g. on the instruction fetch from memory.
10281  * And for it to be a functional problem, the guest would need to depend on the
10282  * ordering between that side effect, the instruction completing, _and_ the
10283  * delivery of the asynchronous event.
10284  */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10285 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10286 				       bool *req_immediate_exit)
10287 {
10288 	bool can_inject;
10289 	int r;
10290 
10291 	/*
10292 	 * Process nested events first, as nested VM-Exit supersedes event
10293 	 * re-injection.  If there's an event queued for re-injection, it will
10294 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10295 	 */
10296 	if (is_guest_mode(vcpu))
10297 		r = kvm_check_nested_events(vcpu);
10298 	else
10299 		r = 0;
10300 
10301 	/*
10302 	 * Re-inject exceptions and events *especially* if immediate entry+exit
10303 	 * to/from L2 is needed, as any event that has already been injected
10304 	 * into L2 needs to complete its lifecycle before injecting a new event.
10305 	 *
10306 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
10307 	 * This collision arises if an exception occurred while vectoring the
10308 	 * injected event, KVM intercepted said exception, and KVM ultimately
10309 	 * determined the fault belongs to the guest and queues the exception
10310 	 * for injection back into the guest.
10311 	 *
10312 	 * "Injected" interrupts can also collide with pending exceptions if
10313 	 * userspace ignores the "ready for injection" flag and blindly queues
10314 	 * an interrupt.  In that case, prioritizing the exception is correct,
10315 	 * as the exception "occurred" before the exit to userspace.  Trap-like
10316 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10317 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10318 	 * priority, they're only generated (pended) during instruction
10319 	 * execution, and interrupts are recognized at instruction boundaries.
10320 	 * Thus a pending fault-like exception means the fault occurred on the
10321 	 * *previous* instruction and must be serviced prior to recognizing any
10322 	 * new events in order to fully complete the previous instruction.
10323 	 */
10324 	if (vcpu->arch.exception.injected)
10325 		kvm_inject_exception(vcpu);
10326 	else if (kvm_is_exception_pending(vcpu))
10327 		; /* see above */
10328 	else if (vcpu->arch.nmi_injected)
10329 		kvm_x86_call(inject_nmi)(vcpu);
10330 	else if (vcpu->arch.interrupt.injected)
10331 		kvm_x86_call(inject_irq)(vcpu, true);
10332 
10333 	/*
10334 	 * Exceptions that morph to VM-Exits are handled above, and pending
10335 	 * exceptions on top of injected exceptions that do not VM-Exit should
10336 	 * either morph to #DF or, sadly, override the injected exception.
10337 	 */
10338 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
10339 		     vcpu->arch.exception.pending);
10340 
10341 	/*
10342 	 * Bail if immediate entry+exit to/from the guest is needed to complete
10343 	 * nested VM-Enter or event re-injection so that a different pending
10344 	 * event can be serviced (or if KVM needs to exit to userspace).
10345 	 *
10346 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
10347 	 * VM-Exit will have cleared exceptions that were meant for L2, but
10348 	 * there may now be events that can be injected into L1.
10349 	 */
10350 	if (r < 0)
10351 		goto out;
10352 
10353 	/*
10354 	 * A pending exception VM-Exit should either result in nested VM-Exit
10355 	 * or force an immediate re-entry and exit to/from L2, and exception
10356 	 * VM-Exits cannot be injected (flag should _never_ be set).
10357 	 */
10358 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10359 		     vcpu->arch.exception_vmexit.pending);
10360 
10361 	/*
10362 	 * New events, other than exceptions, cannot be injected if KVM needs
10363 	 * to re-inject a previous event.  See above comments on re-injecting
10364 	 * for why pending exceptions get priority.
10365 	 */
10366 	can_inject = !kvm_event_needs_reinjection(vcpu);
10367 
10368 	if (vcpu->arch.exception.pending) {
10369 		/*
10370 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10371 		 * value pushed on the stack.  Trap-like exception and all #DBs
10372 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
10373 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10374 		 *
10375 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10376 		 * describe the behavior of General Detect #DBs, which are
10377 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
10378 		 */
10379 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10380 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10381 					     X86_EFLAGS_RF);
10382 
10383 		if (vcpu->arch.exception.vector == DB_VECTOR) {
10384 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10385 			if (vcpu->arch.dr7 & DR7_GD) {
10386 				vcpu->arch.dr7 &= ~DR7_GD;
10387 				kvm_update_dr7(vcpu);
10388 			}
10389 		}
10390 
10391 		kvm_inject_exception(vcpu);
10392 
10393 		vcpu->arch.exception.pending = false;
10394 		vcpu->arch.exception.injected = true;
10395 
10396 		can_inject = false;
10397 	}
10398 
10399 	/* Don't inject interrupts if the user asked to avoid doing so */
10400 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10401 		return 0;
10402 
10403 	/*
10404 	 * Finally, inject interrupt events.  If an event cannot be injected
10405 	 * due to architectural conditions (e.g. IF=0) a window-open exit
10406 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
10407 	 * and can architecturally be injected, but we cannot do it right now:
10408 	 * an interrupt could have arrived just now and we have to inject it
10409 	 * as a vmexit, or there could already an event in the queue, which is
10410 	 * indicated by can_inject.  In that case we request an immediate exit
10411 	 * in order to make progress and get back here for another iteration.
10412 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10413 	 */
10414 #ifdef CONFIG_KVM_SMM
10415 	if (vcpu->arch.smi_pending) {
10416 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10417 				 -EBUSY;
10418 		if (r < 0)
10419 			goto out;
10420 		if (r) {
10421 			vcpu->arch.smi_pending = false;
10422 			++vcpu->arch.smi_count;
10423 			enter_smm(vcpu);
10424 			can_inject = false;
10425 		} else
10426 			kvm_x86_call(enable_smi_window)(vcpu);
10427 	}
10428 #endif
10429 
10430 	if (vcpu->arch.nmi_pending) {
10431 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10432 				 -EBUSY;
10433 		if (r < 0)
10434 			goto out;
10435 		if (r) {
10436 			--vcpu->arch.nmi_pending;
10437 			vcpu->arch.nmi_injected = true;
10438 			kvm_x86_call(inject_nmi)(vcpu);
10439 			can_inject = false;
10440 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10441 		}
10442 		if (vcpu->arch.nmi_pending)
10443 			kvm_x86_call(enable_nmi_window)(vcpu);
10444 	}
10445 
10446 	if (kvm_cpu_has_injectable_intr(vcpu)) {
10447 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10448 				 -EBUSY;
10449 		if (r < 0)
10450 			goto out;
10451 		if (r) {
10452 			int irq = kvm_cpu_get_interrupt(vcpu);
10453 
10454 			if (!WARN_ON_ONCE(irq == -1)) {
10455 				kvm_queue_interrupt(vcpu, irq, false);
10456 				kvm_x86_call(inject_irq)(vcpu, false);
10457 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10458 			}
10459 		}
10460 		if (kvm_cpu_has_injectable_intr(vcpu))
10461 			kvm_x86_call(enable_irq_window)(vcpu);
10462 	}
10463 
10464 	if (is_guest_mode(vcpu) &&
10465 	    kvm_x86_ops.nested_ops->has_events &&
10466 	    kvm_x86_ops.nested_ops->has_events(vcpu, true))
10467 		*req_immediate_exit = true;
10468 
10469 	/*
10470 	 * KVM must never queue a new exception while injecting an event; KVM
10471 	 * is done emulating and should only propagate the to-be-injected event
10472 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
10473 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
10474 	 * exception and start the cycle all over.
10475 	 *
10476 	 * Exempt triple faults as they have special handling and won't put the
10477 	 * vCPU into an infinite loop.  Triple fault can be queued when running
10478 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
10479 	 * Mode events (see kvm_inject_realmode_interrupt()).
10480 	 */
10481 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
10482 		     vcpu->arch.exception_vmexit.pending);
10483 	return 0;
10484 
10485 out:
10486 	if (r == -EBUSY) {
10487 		*req_immediate_exit = true;
10488 		r = 0;
10489 	}
10490 	return r;
10491 }
10492 
process_nmi(struct kvm_vcpu * vcpu)10493 static void process_nmi(struct kvm_vcpu *vcpu)
10494 {
10495 	unsigned int limit;
10496 
10497 	/*
10498 	 * x86 is limited to one NMI pending, but because KVM can't react to
10499 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10500 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
10501 	 * up at the same time.  To handle this scenario, allow two NMIs to be
10502 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10503 	 * waiting for a previous NMI injection to complete (which effectively
10504 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
10505 	 * will request an NMI window to handle the second NMI.
10506 	 */
10507 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10508 		limit = 1;
10509 	else
10510 		limit = 2;
10511 
10512 	/*
10513 	 * Adjust the limit to account for pending virtual NMIs, which aren't
10514 	 * tracked in vcpu->arch.nmi_pending.
10515 	 */
10516 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
10517 		limit--;
10518 
10519 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10520 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10521 
10522 	if (vcpu->arch.nmi_pending &&
10523 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
10524 		vcpu->arch.nmi_pending--;
10525 
10526 	if (vcpu->arch.nmi_pending)
10527 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10528 }
10529 
10530 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10531 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10532 {
10533 	return vcpu->arch.nmi_pending +
10534 	       kvm_x86_call(is_vnmi_pending)(vcpu);
10535 }
10536 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10537 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10538 				       unsigned long *vcpu_bitmap)
10539 {
10540 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10541 }
10542 
kvm_make_scan_ioapic_request(struct kvm * kvm)10543 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10544 {
10545 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10546 }
10547 
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10548 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10549 {
10550 	struct kvm_lapic *apic = vcpu->arch.apic;
10551 	bool activate;
10552 
10553 	if (!lapic_in_kernel(vcpu))
10554 		return;
10555 
10556 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10557 	preempt_disable();
10558 
10559 	/* Do not activate APICV when APIC is disabled */
10560 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10561 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10562 
10563 	if (apic->apicv_active == activate)
10564 		goto out;
10565 
10566 	apic->apicv_active = activate;
10567 	kvm_apic_update_apicv(vcpu);
10568 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10569 
10570 	/*
10571 	 * When APICv gets disabled, we may still have injected interrupts
10572 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10573 	 * still active when the interrupt got accepted. Make sure
10574 	 * kvm_check_and_inject_events() is called to check for that.
10575 	 */
10576 	if (!apic->apicv_active)
10577 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10578 
10579 out:
10580 	preempt_enable();
10581 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10582 }
10583 EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10584 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10585 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10586 {
10587 	if (!lapic_in_kernel(vcpu))
10588 		return;
10589 
10590 	/*
10591 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10592 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10593 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
10594 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
10595 	 * this case so that KVM can use the AVIC doorbell to inject interrupts
10596 	 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10597 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10598 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
10599 	 * access page is sticky.
10600 	 */
10601 	if (apic_x2apic_mode(vcpu->arch.apic) &&
10602 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10603 		kvm_inhibit_apic_access_page(vcpu);
10604 
10605 	__kvm_vcpu_update_apicv(vcpu);
10606 }
10607 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10608 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10609 				      enum kvm_apicv_inhibit reason, bool set)
10610 {
10611 	unsigned long old, new;
10612 
10613 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10614 
10615 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10616 		return;
10617 
10618 	old = new = kvm->arch.apicv_inhibit_reasons;
10619 
10620 	set_or_clear_apicv_inhibit(&new, reason, set);
10621 
10622 	if (!!old != !!new) {
10623 		/*
10624 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10625 		 * false positives in the sanity check WARN in vcpu_enter_guest().
10626 		 * This task will wait for all vCPUs to ack the kick IRQ before
10627 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10628 		 * block on acquiring apicv_update_lock so that vCPUs can't
10629 		 * redo vcpu_enter_guest() without seeing the new inhibit state.
10630 		 *
10631 		 * Note, holding apicv_update_lock and taking it in the read
10632 		 * side (handling the request) also prevents other vCPUs from
10633 		 * servicing the request with a stale apicv_inhibit_reasons.
10634 		 */
10635 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10636 		kvm->arch.apicv_inhibit_reasons = new;
10637 		if (new) {
10638 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10639 			int idx = srcu_read_lock(&kvm->srcu);
10640 
10641 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10642 			srcu_read_unlock(&kvm->srcu, idx);
10643 		}
10644 	} else {
10645 		kvm->arch.apicv_inhibit_reasons = new;
10646 	}
10647 }
10648 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10649 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10650 				    enum kvm_apicv_inhibit reason, bool set)
10651 {
10652 	if (!enable_apicv)
10653 		return;
10654 
10655 	down_write(&kvm->arch.apicv_update_lock);
10656 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10657 	up_write(&kvm->arch.apicv_update_lock);
10658 }
10659 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10660 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10661 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10662 {
10663 	if (!kvm_apic_present(vcpu))
10664 		return;
10665 
10666 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10667 
10668 	kvm_x86_call(sync_pir_to_irr)(vcpu);
10669 
10670 	if (irqchip_split(vcpu->kvm))
10671 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10672 	else if (ioapic_in_kernel(vcpu->kvm))
10673 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10674 
10675 	if (is_guest_mode(vcpu))
10676 		vcpu->arch.load_eoi_exitmap_pending = true;
10677 	else
10678 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10679 }
10680 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10681 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10682 {
10683 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10684 		return;
10685 
10686 #ifdef CONFIG_KVM_HYPERV
10687 	if (to_hv_vcpu(vcpu)) {
10688 		u64 eoi_exit_bitmap[4];
10689 
10690 		bitmap_or((ulong *)eoi_exit_bitmap,
10691 			  vcpu->arch.ioapic_handled_vectors,
10692 			  to_hv_synic(vcpu)->vec_bitmap, 256);
10693 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10694 		return;
10695 	}
10696 #endif
10697 	kvm_x86_call(load_eoi_exitmap)(
10698 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10699 }
10700 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)10701 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10702 {
10703 	kvm_x86_call(guest_memory_reclaimed)(kvm);
10704 }
10705 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)10706 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10707 {
10708 	if (!lapic_in_kernel(vcpu))
10709 		return;
10710 
10711 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
10712 }
10713 
10714 /*
10715  * Called within kvm->srcu read side.
10716  * Returns 1 to let vcpu_run() continue the guest execution loop without
10717  * exiting to the userspace.  Otherwise, the value will be returned to the
10718  * userspace.
10719  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)10720 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10721 {
10722 	int r;
10723 	bool req_int_win =
10724 		dm_request_for_irq_injection(vcpu) &&
10725 		kvm_cpu_accept_dm_intr(vcpu);
10726 	fastpath_t exit_fastpath;
10727 
10728 	bool req_immediate_exit = false;
10729 
10730 	if (kvm_request_pending(vcpu)) {
10731 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10732 			r = -EIO;
10733 			goto out;
10734 		}
10735 
10736 		if (kvm_dirty_ring_check_request(vcpu)) {
10737 			r = 0;
10738 			goto out;
10739 		}
10740 
10741 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10742 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10743 				r = 0;
10744 				goto out;
10745 			}
10746 		}
10747 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10748 			kvm_mmu_free_obsolete_roots(vcpu);
10749 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10750 			__kvm_migrate_timers(vcpu);
10751 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10752 			kvm_update_masterclock(vcpu->kvm);
10753 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10754 			kvm_gen_kvmclock_update(vcpu);
10755 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10756 			r = kvm_guest_time_update(vcpu);
10757 			if (unlikely(r))
10758 				goto out;
10759 		}
10760 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10761 			kvm_mmu_sync_roots(vcpu);
10762 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10763 			kvm_mmu_load_pgd(vcpu);
10764 
10765 		/*
10766 		 * Note, the order matters here, as flushing "all" TLB entries
10767 		 * also flushes the "current" TLB entries, i.e. servicing the
10768 		 * flush "all" will clear any request to flush "current".
10769 		 */
10770 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
10771 			kvm_vcpu_flush_tlb_all(vcpu);
10772 
10773 		kvm_service_local_tlb_flush_requests(vcpu);
10774 
10775 		/*
10776 		 * Fall back to a "full" guest flush if Hyper-V's precise
10777 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
10778 		 * the flushes are considered "remote" and not "local" because
10779 		 * the requests can be initiated from other vCPUs.
10780 		 */
10781 #ifdef CONFIG_KVM_HYPERV
10782 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10783 		    kvm_hv_vcpu_flush_tlb(vcpu))
10784 			kvm_vcpu_flush_tlb_guest(vcpu);
10785 #endif
10786 
10787 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10788 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10789 			r = 0;
10790 			goto out;
10791 		}
10792 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10793 			if (is_guest_mode(vcpu))
10794 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
10795 
10796 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10797 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10798 				vcpu->mmio_needed = 0;
10799 				r = 0;
10800 				goto out;
10801 			}
10802 		}
10803 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10804 			/* Page is swapped out. Do synthetic halt */
10805 			vcpu->arch.apf.halted = true;
10806 			r = 1;
10807 			goto out;
10808 		}
10809 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10810 			record_steal_time(vcpu);
10811 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
10812 			kvm_pmu_handle_event(vcpu);
10813 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
10814 			kvm_pmu_deliver_pmi(vcpu);
10815 #ifdef CONFIG_KVM_SMM
10816 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
10817 			process_smi(vcpu);
10818 #endif
10819 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
10820 			process_nmi(vcpu);
10821 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10822 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10823 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
10824 				     vcpu->arch.ioapic_handled_vectors)) {
10825 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10826 				vcpu->run->eoi.vector =
10827 						vcpu->arch.pending_ioapic_eoi;
10828 				r = 0;
10829 				goto out;
10830 			}
10831 		}
10832 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10833 			vcpu_scan_ioapic(vcpu);
10834 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10835 			vcpu_load_eoi_exitmap(vcpu);
10836 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10837 			kvm_vcpu_reload_apic_access_page(vcpu);
10838 #ifdef CONFIG_KVM_HYPERV
10839 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10840 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10841 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10842 			vcpu->run->system_event.ndata = 0;
10843 			r = 0;
10844 			goto out;
10845 		}
10846 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10847 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10848 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10849 			vcpu->run->system_event.ndata = 0;
10850 			r = 0;
10851 			goto out;
10852 		}
10853 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10854 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10855 
10856 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10857 			vcpu->run->hyperv = hv_vcpu->exit;
10858 			r = 0;
10859 			goto out;
10860 		}
10861 
10862 		/*
10863 		 * KVM_REQ_HV_STIMER has to be processed after
10864 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10865 		 * depend on the guest clock being up-to-date
10866 		 */
10867 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10868 			kvm_hv_process_stimers(vcpu);
10869 #endif
10870 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10871 			kvm_vcpu_update_apicv(vcpu);
10872 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10873 			kvm_check_async_pf_completion(vcpu);
10874 		if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10875 			kvm_x86_call(msr_filter_changed)(vcpu);
10876 
10877 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10878 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
10879 
10880 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
10881 			kvm_vcpu_reset(vcpu, true);
10882 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
10883 				r = 1;
10884 				goto out;
10885 			}
10886 		}
10887 	}
10888 
10889 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10890 	    kvm_xen_has_interrupt(vcpu)) {
10891 		++vcpu->stat.req_event;
10892 		r = kvm_apic_accept_events(vcpu);
10893 		if (r < 0) {
10894 			r = 0;
10895 			goto out;
10896 		}
10897 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10898 			r = 1;
10899 			goto out;
10900 		}
10901 
10902 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10903 		if (r < 0) {
10904 			r = 0;
10905 			goto out;
10906 		}
10907 		if (req_int_win)
10908 			kvm_x86_call(enable_irq_window)(vcpu);
10909 
10910 		if (kvm_lapic_enabled(vcpu)) {
10911 			update_cr8_intercept(vcpu);
10912 			kvm_lapic_sync_to_vapic(vcpu);
10913 		}
10914 	}
10915 
10916 	r = kvm_mmu_reload(vcpu);
10917 	if (unlikely(r)) {
10918 		goto cancel_injection;
10919 	}
10920 
10921 	preempt_disable();
10922 
10923 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
10924 
10925 	/*
10926 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
10927 	 * IPI are then delayed after guest entry, which ensures that they
10928 	 * result in virtual interrupt delivery.
10929 	 */
10930 	local_irq_disable();
10931 
10932 	/* Store vcpu->apicv_active before vcpu->mode.  */
10933 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10934 
10935 	kvm_vcpu_srcu_read_unlock(vcpu);
10936 
10937 	/*
10938 	 * 1) We should set ->mode before checking ->requests.  Please see
10939 	 * the comment in kvm_vcpu_exiting_guest_mode().
10940 	 *
10941 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
10942 	 * pairs with the memory barrier implicit in pi_test_and_set_on
10943 	 * (see vmx_deliver_posted_interrupt).
10944 	 *
10945 	 * 3) This also orders the write to mode from any reads to the page
10946 	 * tables done while the VCPU is running.  Please see the comment
10947 	 * in kvm_flush_remote_tlbs.
10948 	 */
10949 	smp_mb__after_srcu_read_unlock();
10950 
10951 	/*
10952 	 * Process pending posted interrupts to handle the case where the
10953 	 * notification IRQ arrived in the host, or was never sent (because the
10954 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
10955 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
10956 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
10957 	 */
10958 	if (kvm_lapic_enabled(vcpu))
10959 		kvm_x86_call(sync_pir_to_irr)(vcpu);
10960 
10961 	if (kvm_vcpu_exit_request(vcpu)) {
10962 		vcpu->mode = OUTSIDE_GUEST_MODE;
10963 		smp_wmb();
10964 		local_irq_enable();
10965 		preempt_enable();
10966 		kvm_vcpu_srcu_read_lock(vcpu);
10967 		r = 1;
10968 		goto cancel_injection;
10969 	}
10970 
10971 	if (req_immediate_exit)
10972 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10973 
10974 	fpregs_assert_state_consistent();
10975 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
10976 		switch_fpu_return();
10977 
10978 	if (vcpu->arch.guest_fpu.xfd_err)
10979 		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10980 
10981 	if (unlikely(vcpu->arch.switch_db_regs)) {
10982 		set_debugreg(0, 7);
10983 		set_debugreg(vcpu->arch.eff_db[0], 0);
10984 		set_debugreg(vcpu->arch.eff_db[1], 1);
10985 		set_debugreg(vcpu->arch.eff_db[2], 2);
10986 		set_debugreg(vcpu->arch.eff_db[3], 3);
10987 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
10988 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
10989 			kvm_x86_call(set_dr6)(vcpu, vcpu->arch.dr6);
10990 	} else if (unlikely(hw_breakpoint_active())) {
10991 		set_debugreg(0, 7);
10992 	}
10993 
10994 	vcpu->arch.host_debugctl = get_debugctlmsr();
10995 
10996 	guest_timing_enter_irqoff();
10997 
10998 	for (;;) {
10999 		/*
11000 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
11001 		 * update must kick and wait for all vCPUs before toggling the
11002 		 * per-VM state, and responding vCPUs must wait for the update
11003 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
11004 		 */
11005 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11006 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11007 
11008 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu,
11009 						       req_immediate_exit);
11010 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11011 			break;
11012 
11013 		if (kvm_lapic_enabled(vcpu))
11014 			kvm_x86_call(sync_pir_to_irr)(vcpu);
11015 
11016 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11017 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11018 			break;
11019 		}
11020 
11021 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
11022 		++vcpu->stat.exits;
11023 	}
11024 
11025 	/*
11026 	 * Do this here before restoring debug registers on the host.  And
11027 	 * since we do this before handling the vmexit, a DR access vmexit
11028 	 * can (a) read the correct value of the debug registers, (b) set
11029 	 * KVM_DEBUGREG_WONT_EXIT again.
11030 	 */
11031 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11032 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11033 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11034 		kvm_update_dr0123(vcpu);
11035 		kvm_update_dr7(vcpu);
11036 	}
11037 
11038 	/*
11039 	 * If the guest has used debug registers, at least dr7
11040 	 * will be disabled while returning to the host.
11041 	 * If we don't have active breakpoints in the host, we don't
11042 	 * care about the messed up debug address registers. But if
11043 	 * we have some of them active, restore the old state.
11044 	 */
11045 	if (hw_breakpoint_active())
11046 		hw_breakpoint_restore();
11047 
11048 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11049 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11050 
11051 	vcpu->mode = OUTSIDE_GUEST_MODE;
11052 	smp_wmb();
11053 
11054 	/*
11055 	 * Sync xfd before calling handle_exit_irqoff() which may
11056 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11057 	 * in #NM irqoff handler).
11058 	 */
11059 	if (vcpu->arch.xfd_no_write_intercept)
11060 		fpu_sync_guest_vmexit_xfd_state();
11061 
11062 	kvm_x86_call(handle_exit_irqoff)(vcpu);
11063 
11064 	if (vcpu->arch.guest_fpu.xfd_err)
11065 		wrmsrl(MSR_IA32_XFD_ERR, 0);
11066 
11067 	/*
11068 	 * Consume any pending interrupts, including the possible source of
11069 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11070 	 * An instruction is required after local_irq_enable() to fully unblock
11071 	 * interrupts on processors that implement an interrupt shadow, the
11072 	 * stat.exits increment will do nicely.
11073 	 */
11074 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11075 	local_irq_enable();
11076 	++vcpu->stat.exits;
11077 	local_irq_disable();
11078 	kvm_after_interrupt(vcpu);
11079 
11080 	/*
11081 	 * Wait until after servicing IRQs to account guest time so that any
11082 	 * ticks that occurred while running the guest are properly accounted
11083 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
11084 	 * of accounting via context tracking, but the loss of accuracy is
11085 	 * acceptable for all known use cases.
11086 	 */
11087 	guest_timing_exit_irqoff();
11088 
11089 	local_irq_enable();
11090 	preempt_enable();
11091 
11092 	kvm_vcpu_srcu_read_lock(vcpu);
11093 
11094 	/*
11095 	 * Call this to ensure WC buffers in guest are evicted after each VM
11096 	 * Exit, so that the evicted WC writes can be snooped across all cpus
11097 	 */
11098 	smp_mb__after_srcu_read_lock();
11099 
11100 	/*
11101 	 * Profile KVM exit RIPs:
11102 	 */
11103 	if (unlikely(prof_on == KVM_PROFILING &&
11104 		     !vcpu->arch.guest_state_protected)) {
11105 		unsigned long rip = kvm_rip_read(vcpu);
11106 		profile_hit(KVM_PROFILING, (void *)rip);
11107 	}
11108 
11109 	if (unlikely(vcpu->arch.tsc_always_catchup))
11110 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11111 
11112 	if (vcpu->arch.apic_attention)
11113 		kvm_lapic_sync_from_vapic(vcpu);
11114 
11115 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11116 		return 0;
11117 
11118 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11119 	return r;
11120 
11121 cancel_injection:
11122 	if (req_immediate_exit)
11123 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11124 	kvm_x86_call(cancel_injection)(vcpu);
11125 	if (unlikely(vcpu->arch.apic_attention))
11126 		kvm_lapic_sync_from_vapic(vcpu);
11127 out:
11128 	return r;
11129 }
11130 
kvm_vcpu_running(struct kvm_vcpu * vcpu)11131 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11132 {
11133 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11134 		!vcpu->arch.apf.halted);
11135 }
11136 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11137 static bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11138 {
11139 	if (!list_empty_careful(&vcpu->async_pf.done))
11140 		return true;
11141 
11142 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11143 	    kvm_apic_init_sipi_allowed(vcpu))
11144 		return true;
11145 
11146 	if (vcpu->arch.pv.pv_unhalted)
11147 		return true;
11148 
11149 	if (kvm_is_exception_pending(vcpu))
11150 		return true;
11151 
11152 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11153 	    (vcpu->arch.nmi_pending &&
11154 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
11155 		return true;
11156 
11157 #ifdef CONFIG_KVM_SMM
11158 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11159 	    (vcpu->arch.smi_pending &&
11160 	     kvm_x86_call(smi_allowed)(vcpu, false)))
11161 		return true;
11162 #endif
11163 
11164 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
11165 		return true;
11166 
11167 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11168 		return true;
11169 
11170 	if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11171 		return true;
11172 
11173 	if (kvm_hv_has_stimer_pending(vcpu))
11174 		return true;
11175 
11176 	if (is_guest_mode(vcpu) &&
11177 	    kvm_x86_ops.nested_ops->has_events &&
11178 	    kvm_x86_ops.nested_ops->has_events(vcpu, false))
11179 		return true;
11180 
11181 	if (kvm_xen_has_pending_events(vcpu))
11182 		return true;
11183 
11184 	return false;
11185 }
11186 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11187 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11188 {
11189 	return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
11190 }
11191 
11192 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)11193 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11194 {
11195 	bool hv_timer;
11196 
11197 	if (!kvm_arch_vcpu_runnable(vcpu)) {
11198 		/*
11199 		 * Switch to the software timer before halt-polling/blocking as
11200 		 * the guest's timer may be a break event for the vCPU, and the
11201 		 * hypervisor timer runs only when the CPU is in guest mode.
11202 		 * Switch before halt-polling so that KVM recognizes an expired
11203 		 * timer before blocking.
11204 		 */
11205 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11206 		if (hv_timer)
11207 			kvm_lapic_switch_to_sw_timer(vcpu);
11208 
11209 		kvm_vcpu_srcu_read_unlock(vcpu);
11210 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11211 			kvm_vcpu_halt(vcpu);
11212 		else
11213 			kvm_vcpu_block(vcpu);
11214 		kvm_vcpu_srcu_read_lock(vcpu);
11215 
11216 		if (hv_timer)
11217 			kvm_lapic_switch_to_hv_timer(vcpu);
11218 
11219 		/*
11220 		 * If the vCPU is not runnable, a signal or another host event
11221 		 * of some kind is pending; service it without changing the
11222 		 * vCPU's activity state.
11223 		 */
11224 		if (!kvm_arch_vcpu_runnable(vcpu))
11225 			return 1;
11226 	}
11227 
11228 	/*
11229 	 * Evaluate nested events before exiting the halted state.  This allows
11230 	 * the halt state to be recorded properly in the VMCS12's activity
11231 	 * state field (AMD does not have a similar field and a VM-Exit always
11232 	 * causes a spurious wakeup from HLT).
11233 	 */
11234 	if (is_guest_mode(vcpu)) {
11235 		int r = kvm_check_nested_events(vcpu);
11236 
11237 		WARN_ON_ONCE(r == -EBUSY);
11238 		if (r < 0)
11239 			return 0;
11240 	}
11241 
11242 	if (kvm_apic_accept_events(vcpu) < 0)
11243 		return 0;
11244 	switch(vcpu->arch.mp_state) {
11245 	case KVM_MP_STATE_HALTED:
11246 	case KVM_MP_STATE_AP_RESET_HOLD:
11247 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11248 		fallthrough;
11249 	case KVM_MP_STATE_RUNNABLE:
11250 		vcpu->arch.apf.halted = false;
11251 		break;
11252 	case KVM_MP_STATE_INIT_RECEIVED:
11253 		break;
11254 	default:
11255 		WARN_ON_ONCE(1);
11256 		break;
11257 	}
11258 	return 1;
11259 }
11260 
11261 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)11262 static int vcpu_run(struct kvm_vcpu *vcpu)
11263 {
11264 	int r;
11265 
11266 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11267 
11268 	for (;;) {
11269 		/*
11270 		 * If another guest vCPU requests a PV TLB flush in the middle
11271 		 * of instruction emulation, the rest of the emulation could
11272 		 * use a stale page translation. Assume that any code after
11273 		 * this point can start executing an instruction.
11274 		 */
11275 		vcpu->arch.at_instruction_boundary = false;
11276 		if (kvm_vcpu_running(vcpu)) {
11277 			r = vcpu_enter_guest(vcpu);
11278 		} else {
11279 			r = vcpu_block(vcpu);
11280 		}
11281 
11282 		if (r <= 0)
11283 			break;
11284 
11285 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11286 		if (kvm_xen_has_pending_events(vcpu))
11287 			kvm_xen_inject_pending_events(vcpu);
11288 
11289 		if (kvm_cpu_has_pending_timer(vcpu))
11290 			kvm_inject_pending_timer_irqs(vcpu);
11291 
11292 		if (dm_request_for_irq_injection(vcpu) &&
11293 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11294 			r = 0;
11295 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11296 			++vcpu->stat.request_irq_exits;
11297 			break;
11298 		}
11299 
11300 		if (__xfer_to_guest_mode_work_pending()) {
11301 			kvm_vcpu_srcu_read_unlock(vcpu);
11302 			r = xfer_to_guest_mode_handle_work(vcpu);
11303 			kvm_vcpu_srcu_read_lock(vcpu);
11304 			if (r)
11305 				return r;
11306 		}
11307 	}
11308 
11309 	return r;
11310 }
11311 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11312 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11313 {
11314 	/*
11315 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
11316 	 * local APIC is in-kernel, the run loop will detect the non-runnable
11317 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
11318 	 * managed by userspace, in which case userspace is responsible for
11319 	 * handling wake events.
11320 	 */
11321 	++vcpu->stat.halt_exits;
11322 	if (lapic_in_kernel(vcpu)) {
11323 		if (kvm_vcpu_has_events(vcpu))
11324 			state = KVM_MP_STATE_RUNNABLE;
11325 		kvm_set_mp_state(vcpu, state);
11326 		return 1;
11327 	} else {
11328 		vcpu->run->exit_reason = reason;
11329 		return 0;
11330 	}
11331 }
11332 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11333 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11334 {
11335 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11336 }
11337 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
11338 
kvm_emulate_halt(struct kvm_vcpu * vcpu)11339 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11340 {
11341 	int ret = kvm_skip_emulated_instruction(vcpu);
11342 	/*
11343 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11344 	 * KVM_EXIT_DEBUG here.
11345 	 */
11346 	return kvm_emulate_halt_noskip(vcpu) && ret;
11347 }
11348 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
11349 
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11350 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11351 {
11352 	int ret;
11353 
11354 	kvm_vcpu_srcu_read_lock(vcpu);
11355 	ret = kvm_emulate_halt(vcpu);
11356 	kvm_vcpu_srcu_read_unlock(vcpu);
11357 
11358 	if (!ret)
11359 		return EXIT_FASTPATH_EXIT_USERSPACE;
11360 
11361 	if (kvm_vcpu_running(vcpu))
11362 		return EXIT_FASTPATH_REENTER_GUEST;
11363 
11364 	return EXIT_FASTPATH_EXIT_HANDLED;
11365 }
11366 EXPORT_SYMBOL_GPL(handle_fastpath_hlt);
11367 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11368 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11369 {
11370 	int ret = kvm_skip_emulated_instruction(vcpu);
11371 
11372 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11373 					KVM_EXIT_AP_RESET_HOLD) && ret;
11374 }
11375 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
11376 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11377 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11378 {
11379 	return kvm_vcpu_apicv_active(vcpu) &&
11380 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11381 }
11382 
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11383 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11384 {
11385 	return vcpu->arch.preempted_in_kernel;
11386 }
11387 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11388 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11389 {
11390 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11391 		return true;
11392 
11393 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11394 #ifdef CONFIG_KVM_SMM
11395 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
11396 #endif
11397 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
11398 		return true;
11399 
11400 	return kvm_arch_dy_has_pending_interrupt(vcpu);
11401 }
11402 
complete_emulated_io(struct kvm_vcpu * vcpu)11403 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11404 {
11405 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11406 }
11407 
complete_emulated_pio(struct kvm_vcpu * vcpu)11408 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11409 {
11410 	BUG_ON(!vcpu->arch.pio.count);
11411 
11412 	return complete_emulated_io(vcpu);
11413 }
11414 
11415 /*
11416  * Implements the following, as a state machine:
11417  *
11418  * read:
11419  *   for each fragment
11420  *     for each mmio piece in the fragment
11421  *       write gpa, len
11422  *       exit
11423  *       copy data
11424  *   execute insn
11425  *
11426  * write:
11427  *   for each fragment
11428  *     for each mmio piece in the fragment
11429  *       write gpa, len
11430  *       copy data
11431  *       exit
11432  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11433 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11434 {
11435 	struct kvm_run *run = vcpu->run;
11436 	struct kvm_mmio_fragment *frag;
11437 	unsigned len;
11438 
11439 	BUG_ON(!vcpu->mmio_needed);
11440 
11441 	/* Complete previous fragment */
11442 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11443 	len = min(8u, frag->len);
11444 	if (!vcpu->mmio_is_write)
11445 		memcpy(frag->data, run->mmio.data, len);
11446 
11447 	if (frag->len <= 8) {
11448 		/* Switch to the next fragment. */
11449 		frag++;
11450 		vcpu->mmio_cur_fragment++;
11451 	} else {
11452 		/* Go forward to the next mmio piece. */
11453 		frag->data += len;
11454 		frag->gpa += len;
11455 		frag->len -= len;
11456 	}
11457 
11458 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11459 		vcpu->mmio_needed = 0;
11460 
11461 		/* FIXME: return into emulator if single-stepping.  */
11462 		if (vcpu->mmio_is_write)
11463 			return 1;
11464 		vcpu->mmio_read_completed = 1;
11465 		return complete_emulated_io(vcpu);
11466 	}
11467 
11468 	run->exit_reason = KVM_EXIT_MMIO;
11469 	run->mmio.phys_addr = frag->gpa;
11470 	if (vcpu->mmio_is_write)
11471 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11472 	run->mmio.len = min(8u, frag->len);
11473 	run->mmio.is_write = vcpu->mmio_is_write;
11474 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11475 	return 0;
11476 }
11477 
11478 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11479 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11480 {
11481 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11482 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11483 	trace_kvm_fpu(1);
11484 }
11485 
11486 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11487 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11488 {
11489 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11490 	++vcpu->stat.fpu_reload;
11491 	trace_kvm_fpu(0);
11492 }
11493 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11494 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11495 {
11496 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
11497 	struct kvm_run *kvm_run = vcpu->run;
11498 	u64 sync_valid_fields;
11499 	int r;
11500 
11501 	r = kvm_mmu_post_init_vm(vcpu->kvm);
11502 	if (r)
11503 		return r;
11504 
11505 	vcpu_load(vcpu);
11506 	kvm_sigset_activate(vcpu);
11507 	kvm_run->flags = 0;
11508 	kvm_load_guest_fpu(vcpu);
11509 
11510 	kvm_vcpu_srcu_read_lock(vcpu);
11511 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11512 		if (!vcpu->wants_to_run) {
11513 			r = -EINTR;
11514 			goto out;
11515 		}
11516 
11517 		/*
11518 		 * Don't bother switching APIC timer emulation from the
11519 		 * hypervisor timer to the software timer, the only way for the
11520 		 * APIC timer to be active is if userspace stuffed vCPU state,
11521 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
11522 		 * will transition the vCPU out of UNINITIALIZED (without more
11523 		 * state stuffing from userspace), which will reset the local
11524 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
11525 		 * already expired).
11526 		 */
11527 		kvm_vcpu_srcu_read_unlock(vcpu);
11528 		kvm_vcpu_block(vcpu);
11529 		kvm_vcpu_srcu_read_lock(vcpu);
11530 
11531 		if (kvm_apic_accept_events(vcpu) < 0) {
11532 			r = 0;
11533 			goto out;
11534 		}
11535 		r = -EAGAIN;
11536 		if (signal_pending(current)) {
11537 			r = -EINTR;
11538 			kvm_run->exit_reason = KVM_EXIT_INTR;
11539 			++vcpu->stat.signal_exits;
11540 		}
11541 		goto out;
11542 	}
11543 
11544 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11545 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11546 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11547 		r = -EINVAL;
11548 		goto out;
11549 	}
11550 
11551 	if (kvm_run->kvm_dirty_regs) {
11552 		r = sync_regs(vcpu);
11553 		if (r != 0)
11554 			goto out;
11555 	}
11556 
11557 	/* re-sync apic's tpr */
11558 	if (!lapic_in_kernel(vcpu)) {
11559 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11560 			r = -EINVAL;
11561 			goto out;
11562 		}
11563 	}
11564 
11565 	/*
11566 	 * If userspace set a pending exception and L2 is active, convert it to
11567 	 * a pending VM-Exit if L1 wants to intercept the exception.
11568 	 */
11569 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11570 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11571 							ex->error_code)) {
11572 		kvm_queue_exception_vmexit(vcpu, ex->vector,
11573 					   ex->has_error_code, ex->error_code,
11574 					   ex->has_payload, ex->payload);
11575 		ex->injected = false;
11576 		ex->pending = false;
11577 	}
11578 	vcpu->arch.exception_from_userspace = false;
11579 
11580 	if (unlikely(vcpu->arch.complete_userspace_io)) {
11581 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11582 		vcpu->arch.complete_userspace_io = NULL;
11583 		r = cui(vcpu);
11584 		if (r <= 0)
11585 			goto out;
11586 	} else {
11587 		WARN_ON_ONCE(vcpu->arch.pio.count);
11588 		WARN_ON_ONCE(vcpu->mmio_needed);
11589 	}
11590 
11591 	if (!vcpu->wants_to_run) {
11592 		r = -EINTR;
11593 		goto out;
11594 	}
11595 
11596 	r = kvm_x86_call(vcpu_pre_run)(vcpu);
11597 	if (r <= 0)
11598 		goto out;
11599 
11600 	r = vcpu_run(vcpu);
11601 
11602 out:
11603 	kvm_put_guest_fpu(vcpu);
11604 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11605 		store_regs(vcpu);
11606 	post_kvm_run_save(vcpu);
11607 	kvm_vcpu_srcu_read_unlock(vcpu);
11608 
11609 	kvm_sigset_deactivate(vcpu);
11610 	vcpu_put(vcpu);
11611 	return r;
11612 }
11613 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11614 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11615 {
11616 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11617 		/*
11618 		 * We are here if userspace calls get_regs() in the middle of
11619 		 * instruction emulation. Registers state needs to be copied
11620 		 * back from emulation context to vcpu. Userspace shouldn't do
11621 		 * that usually, but some bad designed PV devices (vmware
11622 		 * backdoor interface) need this to work
11623 		 */
11624 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11625 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11626 	}
11627 	regs->rax = kvm_rax_read(vcpu);
11628 	regs->rbx = kvm_rbx_read(vcpu);
11629 	regs->rcx = kvm_rcx_read(vcpu);
11630 	regs->rdx = kvm_rdx_read(vcpu);
11631 	regs->rsi = kvm_rsi_read(vcpu);
11632 	regs->rdi = kvm_rdi_read(vcpu);
11633 	regs->rsp = kvm_rsp_read(vcpu);
11634 	regs->rbp = kvm_rbp_read(vcpu);
11635 #ifdef CONFIG_X86_64
11636 	regs->r8 = kvm_r8_read(vcpu);
11637 	regs->r9 = kvm_r9_read(vcpu);
11638 	regs->r10 = kvm_r10_read(vcpu);
11639 	regs->r11 = kvm_r11_read(vcpu);
11640 	regs->r12 = kvm_r12_read(vcpu);
11641 	regs->r13 = kvm_r13_read(vcpu);
11642 	regs->r14 = kvm_r14_read(vcpu);
11643 	regs->r15 = kvm_r15_read(vcpu);
11644 #endif
11645 
11646 	regs->rip = kvm_rip_read(vcpu);
11647 	regs->rflags = kvm_get_rflags(vcpu);
11648 }
11649 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11650 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11651 {
11652 	if (vcpu->kvm->arch.has_protected_state &&
11653 	    vcpu->arch.guest_state_protected)
11654 		return -EINVAL;
11655 
11656 	vcpu_load(vcpu);
11657 	__get_regs(vcpu, regs);
11658 	vcpu_put(vcpu);
11659 	return 0;
11660 }
11661 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11662 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11663 {
11664 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11665 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11666 
11667 	kvm_rax_write(vcpu, regs->rax);
11668 	kvm_rbx_write(vcpu, regs->rbx);
11669 	kvm_rcx_write(vcpu, regs->rcx);
11670 	kvm_rdx_write(vcpu, regs->rdx);
11671 	kvm_rsi_write(vcpu, regs->rsi);
11672 	kvm_rdi_write(vcpu, regs->rdi);
11673 	kvm_rsp_write(vcpu, regs->rsp);
11674 	kvm_rbp_write(vcpu, regs->rbp);
11675 #ifdef CONFIG_X86_64
11676 	kvm_r8_write(vcpu, regs->r8);
11677 	kvm_r9_write(vcpu, regs->r9);
11678 	kvm_r10_write(vcpu, regs->r10);
11679 	kvm_r11_write(vcpu, regs->r11);
11680 	kvm_r12_write(vcpu, regs->r12);
11681 	kvm_r13_write(vcpu, regs->r13);
11682 	kvm_r14_write(vcpu, regs->r14);
11683 	kvm_r15_write(vcpu, regs->r15);
11684 #endif
11685 
11686 	kvm_rip_write(vcpu, regs->rip);
11687 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11688 
11689 	vcpu->arch.exception.pending = false;
11690 	vcpu->arch.exception_vmexit.pending = false;
11691 
11692 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11693 }
11694 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11695 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11696 {
11697 	if (vcpu->kvm->arch.has_protected_state &&
11698 	    vcpu->arch.guest_state_protected)
11699 		return -EINVAL;
11700 
11701 	vcpu_load(vcpu);
11702 	__set_regs(vcpu, regs);
11703 	vcpu_put(vcpu);
11704 	return 0;
11705 }
11706 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11707 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11708 {
11709 	struct desc_ptr dt;
11710 
11711 	if (vcpu->arch.guest_state_protected)
11712 		goto skip_protected_regs;
11713 
11714 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11715 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11716 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11717 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11718 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11719 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11720 
11721 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11722 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11723 
11724 	kvm_x86_call(get_idt)(vcpu, &dt);
11725 	sregs->idt.limit = dt.size;
11726 	sregs->idt.base = dt.address;
11727 	kvm_x86_call(get_gdt)(vcpu, &dt);
11728 	sregs->gdt.limit = dt.size;
11729 	sregs->gdt.base = dt.address;
11730 
11731 	sregs->cr2 = vcpu->arch.cr2;
11732 	sregs->cr3 = kvm_read_cr3(vcpu);
11733 
11734 skip_protected_regs:
11735 	sregs->cr0 = kvm_read_cr0(vcpu);
11736 	sregs->cr4 = kvm_read_cr4(vcpu);
11737 	sregs->cr8 = kvm_get_cr8(vcpu);
11738 	sregs->efer = vcpu->arch.efer;
11739 	sregs->apic_base = vcpu->arch.apic_base;
11740 }
11741 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11742 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11743 {
11744 	__get_sregs_common(vcpu, sregs);
11745 
11746 	if (vcpu->arch.guest_state_protected)
11747 		return;
11748 
11749 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11750 		set_bit(vcpu->arch.interrupt.nr,
11751 			(unsigned long *)sregs->interrupt_bitmap);
11752 }
11753 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)11754 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11755 {
11756 	int i;
11757 
11758 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11759 
11760 	if (vcpu->arch.guest_state_protected)
11761 		return;
11762 
11763 	if (is_pae_paging(vcpu)) {
11764 		for (i = 0 ; i < 4 ; i++)
11765 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11766 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11767 	}
11768 }
11769 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11770 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11771 				  struct kvm_sregs *sregs)
11772 {
11773 	if (vcpu->kvm->arch.has_protected_state &&
11774 	    vcpu->arch.guest_state_protected)
11775 		return -EINVAL;
11776 
11777 	vcpu_load(vcpu);
11778 	__get_sregs(vcpu, sregs);
11779 	vcpu_put(vcpu);
11780 	return 0;
11781 }
11782 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11783 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11784 				    struct kvm_mp_state *mp_state)
11785 {
11786 	int r;
11787 
11788 	vcpu_load(vcpu);
11789 	if (kvm_mpx_supported())
11790 		kvm_load_guest_fpu(vcpu);
11791 
11792 	kvm_vcpu_srcu_read_lock(vcpu);
11793 
11794 	r = kvm_apic_accept_events(vcpu);
11795 	if (r < 0)
11796 		goto out;
11797 	r = 0;
11798 
11799 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11800 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11801 	    vcpu->arch.pv.pv_unhalted)
11802 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11803 	else
11804 		mp_state->mp_state = vcpu->arch.mp_state;
11805 
11806 out:
11807 	kvm_vcpu_srcu_read_unlock(vcpu);
11808 
11809 	if (kvm_mpx_supported())
11810 		kvm_put_guest_fpu(vcpu);
11811 	vcpu_put(vcpu);
11812 	return r;
11813 }
11814 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11815 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11816 				    struct kvm_mp_state *mp_state)
11817 {
11818 	int ret = -EINVAL;
11819 
11820 	vcpu_load(vcpu);
11821 
11822 	switch (mp_state->mp_state) {
11823 	case KVM_MP_STATE_UNINITIALIZED:
11824 	case KVM_MP_STATE_HALTED:
11825 	case KVM_MP_STATE_AP_RESET_HOLD:
11826 	case KVM_MP_STATE_INIT_RECEIVED:
11827 	case KVM_MP_STATE_SIPI_RECEIVED:
11828 		if (!lapic_in_kernel(vcpu))
11829 			goto out;
11830 		break;
11831 
11832 	case KVM_MP_STATE_RUNNABLE:
11833 		break;
11834 
11835 	default:
11836 		goto out;
11837 	}
11838 
11839 	/*
11840 	 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11841 	 * forcing the guest into INIT/SIPI if those events are supposed to be
11842 	 * blocked.  KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11843 	 * if an SMI is pending as well.
11844 	 */
11845 	if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11846 	    (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11847 	     mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11848 		goto out;
11849 
11850 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11851 		kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
11852 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11853 	} else
11854 		kvm_set_mp_state(vcpu, mp_state->mp_state);
11855 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11856 
11857 	ret = 0;
11858 out:
11859 	vcpu_put(vcpu);
11860 	return ret;
11861 }
11862 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)11863 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11864 		    int reason, bool has_error_code, u32 error_code)
11865 {
11866 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11867 	int ret;
11868 
11869 	init_emulate_ctxt(vcpu);
11870 
11871 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11872 				   has_error_code, error_code);
11873 
11874 	/*
11875 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
11876 	 * MMIO during a task switch (or any other complex operation).
11877 	 */
11878 	if (ret || vcpu->mmio_needed) {
11879 		vcpu->mmio_needed = false;
11880 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11881 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11882 		vcpu->run->internal.ndata = 0;
11883 		return 0;
11884 	}
11885 
11886 	kvm_rip_write(vcpu, ctxt->eip);
11887 	kvm_set_rflags(vcpu, ctxt->eflags);
11888 	return 1;
11889 }
11890 EXPORT_SYMBOL_GPL(kvm_task_switch);
11891 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11892 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11893 {
11894 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11895 		/*
11896 		 * When EFER.LME and CR0.PG are set, the processor is in
11897 		 * 64-bit mode (though maybe in a 32-bit code segment).
11898 		 * CR4.PAE and EFER.LMA must be set.
11899 		 */
11900 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11901 			return false;
11902 		if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
11903 			return false;
11904 	} else {
11905 		/*
11906 		 * Not in 64-bit mode: EFER.LMA is clear and the code
11907 		 * segment cannot be 64-bit.
11908 		 */
11909 		if (sregs->efer & EFER_LMA || sregs->cs.l)
11910 			return false;
11911 	}
11912 
11913 	return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11914 	       kvm_is_valid_cr0(vcpu, sregs->cr0);
11915 }
11916 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)11917 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11918 		int *mmu_reset_needed, bool update_pdptrs)
11919 {
11920 	int idx;
11921 	struct desc_ptr dt;
11922 
11923 	if (!kvm_is_valid_sregs(vcpu, sregs))
11924 		return -EINVAL;
11925 
11926 	if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
11927 		return -EINVAL;
11928 
11929 	if (vcpu->arch.guest_state_protected)
11930 		return 0;
11931 
11932 	dt.size = sregs->idt.limit;
11933 	dt.address = sregs->idt.base;
11934 	kvm_x86_call(set_idt)(vcpu, &dt);
11935 	dt.size = sregs->gdt.limit;
11936 	dt.address = sregs->gdt.base;
11937 	kvm_x86_call(set_gdt)(vcpu, &dt);
11938 
11939 	vcpu->arch.cr2 = sregs->cr2;
11940 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11941 	vcpu->arch.cr3 = sregs->cr3;
11942 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11943 	kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
11944 
11945 	kvm_set_cr8(vcpu, sregs->cr8);
11946 
11947 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11948 	kvm_x86_call(set_efer)(vcpu, sregs->efer);
11949 
11950 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11951 	kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
11952 
11953 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11954 	kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
11955 
11956 	if (update_pdptrs) {
11957 		idx = srcu_read_lock(&vcpu->kvm->srcu);
11958 		if (is_pae_paging(vcpu)) {
11959 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11960 			*mmu_reset_needed = 1;
11961 		}
11962 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
11963 	}
11964 
11965 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11966 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11967 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11968 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11969 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11970 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11971 
11972 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11973 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11974 
11975 	update_cr8_intercept(vcpu);
11976 
11977 	/* Older userspace won't unhalt the vcpu on reset. */
11978 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11979 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
11980 	    !is_protmode(vcpu))
11981 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11982 
11983 	return 0;
11984 }
11985 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11986 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11987 {
11988 	int pending_vec, max_bits;
11989 	int mmu_reset_needed = 0;
11990 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11991 
11992 	if (ret)
11993 		return ret;
11994 
11995 	if (mmu_reset_needed) {
11996 		kvm_mmu_reset_context(vcpu);
11997 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
11998 	}
11999 
12000 	max_bits = KVM_NR_INTERRUPTS;
12001 	pending_vec = find_first_bit(
12002 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
12003 
12004 	if (pending_vec < max_bits) {
12005 		kvm_queue_interrupt(vcpu, pending_vec, false);
12006 		pr_debug("Set back pending irq %d\n", pending_vec);
12007 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12008 	}
12009 	return 0;
12010 }
12011 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12012 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12013 {
12014 	int mmu_reset_needed = 0;
12015 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12016 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12017 		!(sregs2->efer & EFER_LMA);
12018 	int i, ret;
12019 
12020 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12021 		return -EINVAL;
12022 
12023 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12024 		return -EINVAL;
12025 
12026 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12027 				 &mmu_reset_needed, !valid_pdptrs);
12028 	if (ret)
12029 		return ret;
12030 
12031 	if (valid_pdptrs) {
12032 		for (i = 0; i < 4 ; i++)
12033 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12034 
12035 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12036 		mmu_reset_needed = 1;
12037 		vcpu->arch.pdptrs_from_userspace = true;
12038 	}
12039 	if (mmu_reset_needed) {
12040 		kvm_mmu_reset_context(vcpu);
12041 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12042 	}
12043 	return 0;
12044 }
12045 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12046 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12047 				  struct kvm_sregs *sregs)
12048 {
12049 	int ret;
12050 
12051 	if (vcpu->kvm->arch.has_protected_state &&
12052 	    vcpu->arch.guest_state_protected)
12053 		return -EINVAL;
12054 
12055 	vcpu_load(vcpu);
12056 	ret = __set_sregs(vcpu, sregs);
12057 	vcpu_put(vcpu);
12058 	return ret;
12059 }
12060 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12061 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12062 {
12063 	bool set = false;
12064 	struct kvm_vcpu *vcpu;
12065 	unsigned long i;
12066 
12067 	if (!enable_apicv)
12068 		return;
12069 
12070 	down_write(&kvm->arch.apicv_update_lock);
12071 
12072 	kvm_for_each_vcpu(i, vcpu, kvm) {
12073 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12074 			set = true;
12075 			break;
12076 		}
12077 	}
12078 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12079 	up_write(&kvm->arch.apicv_update_lock);
12080 }
12081 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12082 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12083 					struct kvm_guest_debug *dbg)
12084 {
12085 	unsigned long rflags;
12086 	int i, r;
12087 
12088 	if (vcpu->arch.guest_state_protected)
12089 		return -EINVAL;
12090 
12091 	vcpu_load(vcpu);
12092 
12093 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12094 		r = -EBUSY;
12095 		if (kvm_is_exception_pending(vcpu))
12096 			goto out;
12097 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12098 			kvm_queue_exception(vcpu, DB_VECTOR);
12099 		else
12100 			kvm_queue_exception(vcpu, BP_VECTOR);
12101 	}
12102 
12103 	/*
12104 	 * Read rflags as long as potentially injected trace flags are still
12105 	 * filtered out.
12106 	 */
12107 	rflags = kvm_get_rflags(vcpu);
12108 
12109 	vcpu->guest_debug = dbg->control;
12110 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12111 		vcpu->guest_debug = 0;
12112 
12113 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12114 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
12115 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12116 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12117 	} else {
12118 		for (i = 0; i < KVM_NR_DB_REGS; i++)
12119 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12120 	}
12121 	kvm_update_dr7(vcpu);
12122 
12123 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12124 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12125 
12126 	/*
12127 	 * Trigger an rflags update that will inject or remove the trace
12128 	 * flags.
12129 	 */
12130 	kvm_set_rflags(vcpu, rflags);
12131 
12132 	kvm_x86_call(update_exception_bitmap)(vcpu);
12133 
12134 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12135 
12136 	r = 0;
12137 
12138 out:
12139 	vcpu_put(vcpu);
12140 	return r;
12141 }
12142 
12143 /*
12144  * Translate a guest virtual address to a guest physical address.
12145  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12146 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12147 				    struct kvm_translation *tr)
12148 {
12149 	unsigned long vaddr = tr->linear_address;
12150 	gpa_t gpa;
12151 	int idx;
12152 
12153 	vcpu_load(vcpu);
12154 
12155 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12156 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12157 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12158 	tr->physical_address = gpa;
12159 	tr->valid = gpa != INVALID_GPA;
12160 	tr->writeable = 1;
12161 	tr->usermode = 0;
12162 
12163 	vcpu_put(vcpu);
12164 	return 0;
12165 }
12166 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12167 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12168 {
12169 	struct fxregs_state *fxsave;
12170 
12171 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12172 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12173 
12174 	vcpu_load(vcpu);
12175 
12176 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12177 	memcpy(fpu->fpr, fxsave->st_space, 128);
12178 	fpu->fcw = fxsave->cwd;
12179 	fpu->fsw = fxsave->swd;
12180 	fpu->ftwx = fxsave->twd;
12181 	fpu->last_opcode = fxsave->fop;
12182 	fpu->last_ip = fxsave->rip;
12183 	fpu->last_dp = fxsave->rdp;
12184 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12185 
12186 	vcpu_put(vcpu);
12187 	return 0;
12188 }
12189 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12190 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12191 {
12192 	struct fxregs_state *fxsave;
12193 
12194 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12195 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12196 
12197 	vcpu_load(vcpu);
12198 
12199 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12200 
12201 	memcpy(fxsave->st_space, fpu->fpr, 128);
12202 	fxsave->cwd = fpu->fcw;
12203 	fxsave->swd = fpu->fsw;
12204 	fxsave->twd = fpu->ftwx;
12205 	fxsave->fop = fpu->last_opcode;
12206 	fxsave->rip = fpu->last_ip;
12207 	fxsave->rdp = fpu->last_dp;
12208 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12209 
12210 	vcpu_put(vcpu);
12211 	return 0;
12212 }
12213 
store_regs(struct kvm_vcpu * vcpu)12214 static void store_regs(struct kvm_vcpu *vcpu)
12215 {
12216 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12217 
12218 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12219 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
12220 
12221 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12222 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12223 
12224 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12225 		kvm_vcpu_ioctl_x86_get_vcpu_events(
12226 				vcpu, &vcpu->run->s.regs.events);
12227 }
12228 
sync_regs(struct kvm_vcpu * vcpu)12229 static int sync_regs(struct kvm_vcpu *vcpu)
12230 {
12231 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12232 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
12233 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12234 	}
12235 
12236 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12237 		struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12238 
12239 		if (__set_sregs(vcpu, &sregs))
12240 			return -EINVAL;
12241 
12242 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12243 	}
12244 
12245 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12246 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12247 
12248 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12249 			return -EINVAL;
12250 
12251 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12252 	}
12253 
12254 	return 0;
12255 }
12256 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12257 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12258 {
12259 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12260 		pr_warn_once("SMP vm created on host with unstable TSC; "
12261 			     "guest TSC will not be reliable\n");
12262 
12263 	if (!kvm->arch.max_vcpu_ids)
12264 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12265 
12266 	if (id >= kvm->arch.max_vcpu_ids)
12267 		return -EINVAL;
12268 
12269 	return kvm_x86_call(vcpu_precreate)(kvm);
12270 }
12271 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12272 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12273 {
12274 	struct page *page;
12275 	int r;
12276 
12277 	vcpu->arch.last_vmentry_cpu = -1;
12278 	vcpu->arch.regs_avail = ~0;
12279 	vcpu->arch.regs_dirty = ~0;
12280 
12281 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12282 
12283 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12284 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12285 	else
12286 		kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12287 
12288 	r = kvm_mmu_create(vcpu);
12289 	if (r < 0)
12290 		return r;
12291 
12292 	r = kvm_create_lapic(vcpu);
12293 	if (r < 0)
12294 		goto fail_mmu_destroy;
12295 
12296 	r = -ENOMEM;
12297 
12298 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12299 	if (!page)
12300 		goto fail_free_lapic;
12301 	vcpu->arch.pio_data = page_address(page);
12302 
12303 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12304 				       GFP_KERNEL_ACCOUNT);
12305 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12306 					    GFP_KERNEL_ACCOUNT);
12307 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12308 		goto fail_free_mce_banks;
12309 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12310 
12311 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12312 				GFP_KERNEL_ACCOUNT))
12313 		goto fail_free_mce_banks;
12314 
12315 	if (!alloc_emulate_ctxt(vcpu))
12316 		goto free_wbinvd_dirty_mask;
12317 
12318 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12319 		pr_err("failed to allocate vcpu's fpu\n");
12320 		goto free_emulate_ctxt;
12321 	}
12322 
12323 	kvm_async_pf_hash_reset(vcpu);
12324 
12325 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12326 		vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12327 		vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12328 		vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12329 	}
12330 	kvm_pmu_init(vcpu);
12331 
12332 	vcpu->arch.pending_external_vector = -1;
12333 	vcpu->arch.preempted_in_kernel = false;
12334 
12335 #if IS_ENABLED(CONFIG_HYPERV)
12336 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
12337 #endif
12338 
12339 	r = kvm_x86_call(vcpu_create)(vcpu);
12340 	if (r)
12341 		goto free_guest_fpu;
12342 
12343 	kvm_xen_init_vcpu(vcpu);
12344 	vcpu_load(vcpu);
12345 	kvm_vcpu_after_set_cpuid(vcpu);
12346 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12347 	kvm_vcpu_reset(vcpu, false);
12348 	kvm_init_mmu(vcpu);
12349 	vcpu_put(vcpu);
12350 	return 0;
12351 
12352 free_guest_fpu:
12353 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12354 free_emulate_ctxt:
12355 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12356 free_wbinvd_dirty_mask:
12357 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12358 fail_free_mce_banks:
12359 	kfree(vcpu->arch.mce_banks);
12360 	kfree(vcpu->arch.mci_ctl2_banks);
12361 	free_page((unsigned long)vcpu->arch.pio_data);
12362 fail_free_lapic:
12363 	kvm_free_lapic(vcpu);
12364 fail_mmu_destroy:
12365 	kvm_mmu_destroy(vcpu);
12366 	return r;
12367 }
12368 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12369 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12370 {
12371 	struct kvm *kvm = vcpu->kvm;
12372 
12373 	if (mutex_lock_killable(&vcpu->mutex))
12374 		return;
12375 	vcpu_load(vcpu);
12376 	kvm_synchronize_tsc(vcpu, NULL);
12377 	vcpu_put(vcpu);
12378 
12379 	/* poll control enabled by default */
12380 	vcpu->arch.msr_kvm_poll_control = 1;
12381 
12382 	mutex_unlock(&vcpu->mutex);
12383 
12384 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12385 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12386 						KVMCLOCK_SYNC_PERIOD);
12387 }
12388 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12389 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12390 {
12391 	int idx;
12392 
12393 	kvm_clear_async_pf_completion_queue(vcpu);
12394 	kvm_mmu_unload(vcpu);
12395 
12396 	kvmclock_reset(vcpu);
12397 
12398 	kvm_x86_call(vcpu_free)(vcpu);
12399 
12400 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12401 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12402 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12403 
12404 	kvm_xen_destroy_vcpu(vcpu);
12405 	kvm_hv_vcpu_uninit(vcpu);
12406 	kvm_pmu_destroy(vcpu);
12407 	kfree(vcpu->arch.mce_banks);
12408 	kfree(vcpu->arch.mci_ctl2_banks);
12409 	kvm_free_lapic(vcpu);
12410 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12411 	kvm_mmu_destroy(vcpu);
12412 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12413 	free_page((unsigned long)vcpu->arch.pio_data);
12414 	kvfree(vcpu->arch.cpuid_entries);
12415 }
12416 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12417 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12418 {
12419 	struct kvm_cpuid_entry2 *cpuid_0x1;
12420 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
12421 	unsigned long new_cr0;
12422 
12423 	/*
12424 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12425 	 * to handle side effects.  RESET emulation hits those flows and relies
12426 	 * on emulated/virtualized registers, including those that are loaded
12427 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
12428 	 * to detect improper or missing initialization.
12429 	 */
12430 	WARN_ON_ONCE(!init_event &&
12431 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12432 
12433 	/*
12434 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12435 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
12436 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12437 	 * bits), i.e. virtualization is disabled.
12438 	 */
12439 	if (is_guest_mode(vcpu))
12440 		kvm_leave_nested(vcpu);
12441 
12442 	kvm_lapic_reset(vcpu, init_event);
12443 
12444 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12445 	vcpu->arch.hflags = 0;
12446 
12447 	vcpu->arch.smi_pending = 0;
12448 	vcpu->arch.smi_count = 0;
12449 	atomic_set(&vcpu->arch.nmi_queued, 0);
12450 	vcpu->arch.nmi_pending = 0;
12451 	vcpu->arch.nmi_injected = false;
12452 	kvm_clear_interrupt_queue(vcpu);
12453 	kvm_clear_exception_queue(vcpu);
12454 
12455 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12456 	kvm_update_dr0123(vcpu);
12457 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12458 	vcpu->arch.dr7 = DR7_FIXED_1;
12459 	kvm_update_dr7(vcpu);
12460 
12461 	vcpu->arch.cr2 = 0;
12462 
12463 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12464 	vcpu->arch.apf.msr_en_val = 0;
12465 	vcpu->arch.apf.msr_int_val = 0;
12466 	vcpu->arch.st.msr_val = 0;
12467 
12468 	kvmclock_reset(vcpu);
12469 
12470 	kvm_clear_async_pf_completion_queue(vcpu);
12471 	kvm_async_pf_hash_reset(vcpu);
12472 	vcpu->arch.apf.halted = false;
12473 
12474 	if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12475 		struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12476 
12477 		/*
12478 		 * All paths that lead to INIT are required to load the guest's
12479 		 * FPU state (because most paths are buried in KVM_RUN).
12480 		 */
12481 		if (init_event)
12482 			kvm_put_guest_fpu(vcpu);
12483 
12484 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12485 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12486 
12487 		if (init_event)
12488 			kvm_load_guest_fpu(vcpu);
12489 	}
12490 
12491 	if (!init_event) {
12492 		vcpu->arch.smbase = 0x30000;
12493 
12494 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12495 
12496 		vcpu->arch.msr_misc_features_enables = 0;
12497 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12498 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12499 
12500 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12501 		__kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12502 	}
12503 
12504 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12505 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12506 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12507 
12508 	/*
12509 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12510 	 * if no CPUID match is found.  Note, it's impossible to get a match at
12511 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12512 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12513 	 * on RESET.  But, go through the motions in case that's ever remedied.
12514 	 */
12515 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12516 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12517 
12518 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
12519 
12520 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12521 	kvm_rip_write(vcpu, 0xfff0);
12522 
12523 	vcpu->arch.cr3 = 0;
12524 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12525 
12526 	/*
12527 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
12528 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12529 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
12530 	 */
12531 	new_cr0 = X86_CR0_ET;
12532 	if (init_event)
12533 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12534 	else
12535 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12536 
12537 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
12538 	kvm_x86_call(set_cr4)(vcpu, 0);
12539 	kvm_x86_call(set_efer)(vcpu, 0);
12540 	kvm_x86_call(update_exception_bitmap)(vcpu);
12541 
12542 	/*
12543 	 * On the standard CR0/CR4/EFER modification paths, there are several
12544 	 * complex conditions determining whether the MMU has to be reset and/or
12545 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
12546 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12547 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12548 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
12549 	 */
12550 	if (old_cr0 & X86_CR0_PG) {
12551 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12552 		kvm_mmu_reset_context(vcpu);
12553 	}
12554 
12555 	/*
12556 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
12557 	 * APM states the TLBs are untouched by INIT, but it also states that
12558 	 * the TLBs are flushed on "External initialization of the processor."
12559 	 * Flush the guest TLB regardless of vendor, there is no meaningful
12560 	 * benefit in relying on the guest to flush the TLB immediately after
12561 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
12562 	 * performance perspective.
12563 	 */
12564 	if (init_event)
12565 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12566 }
12567 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12568 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12569 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12570 {
12571 	struct kvm_segment cs;
12572 
12573 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12574 	cs.selector = vector << 8;
12575 	cs.base = vector << 12;
12576 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12577 	kvm_rip_write(vcpu, 0);
12578 }
12579 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12580 
kvm_arch_enable_virtualization(void)12581 void kvm_arch_enable_virtualization(void)
12582 {
12583 	cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12584 }
12585 
kvm_arch_disable_virtualization(void)12586 void kvm_arch_disable_virtualization(void)
12587 {
12588 	cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12589 }
12590 
kvm_arch_enable_virtualization_cpu(void)12591 int kvm_arch_enable_virtualization_cpu(void)
12592 {
12593 	struct kvm *kvm;
12594 	struct kvm_vcpu *vcpu;
12595 	unsigned long i;
12596 	int ret;
12597 	u64 local_tsc;
12598 	u64 max_tsc = 0;
12599 	bool stable, backwards_tsc = false;
12600 
12601 	kvm_user_return_msr_cpu_online();
12602 
12603 	ret = kvm_x86_check_processor_compatibility();
12604 	if (ret)
12605 		return ret;
12606 
12607 	ret = kvm_x86_call(enable_virtualization_cpu)();
12608 	if (ret != 0)
12609 		return ret;
12610 
12611 	local_tsc = rdtsc();
12612 	stable = !kvm_check_tsc_unstable();
12613 	list_for_each_entry(kvm, &vm_list, vm_list) {
12614 		kvm_for_each_vcpu(i, vcpu, kvm) {
12615 			if (!stable && vcpu->cpu == smp_processor_id())
12616 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12617 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12618 				backwards_tsc = true;
12619 				if (vcpu->arch.last_host_tsc > max_tsc)
12620 					max_tsc = vcpu->arch.last_host_tsc;
12621 			}
12622 		}
12623 	}
12624 
12625 	/*
12626 	 * Sometimes, even reliable TSCs go backwards.  This happens on
12627 	 * platforms that reset TSC during suspend or hibernate actions, but
12628 	 * maintain synchronization.  We must compensate.  Fortunately, we can
12629 	 * detect that condition here, which happens early in CPU bringup,
12630 	 * before any KVM threads can be running.  Unfortunately, we can't
12631 	 * bring the TSCs fully up to date with real time, as we aren't yet far
12632 	 * enough into CPU bringup that we know how much real time has actually
12633 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12634 	 * variables that haven't been updated yet.
12635 	 *
12636 	 * So we simply find the maximum observed TSC above, then record the
12637 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
12638 	 * the adjustment will be applied.  Note that we accumulate
12639 	 * adjustments, in case multiple suspend cycles happen before some VCPU
12640 	 * gets a chance to run again.  In the event that no KVM threads get a
12641 	 * chance to run, we will miss the entire elapsed period, as we'll have
12642 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12643 	 * loose cycle time.  This isn't too big a deal, since the loss will be
12644 	 * uniform across all VCPUs (not to mention the scenario is extremely
12645 	 * unlikely). It is possible that a second hibernate recovery happens
12646 	 * much faster than a first, causing the observed TSC here to be
12647 	 * smaller; this would require additional padding adjustment, which is
12648 	 * why we set last_host_tsc to the local tsc observed here.
12649 	 *
12650 	 * N.B. - this code below runs only on platforms with reliable TSC,
12651 	 * as that is the only way backwards_tsc is set above.  Also note
12652 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12653 	 * have the same delta_cyc adjustment applied if backwards_tsc
12654 	 * is detected.  Note further, this adjustment is only done once,
12655 	 * as we reset last_host_tsc on all VCPUs to stop this from being
12656 	 * called multiple times (one for each physical CPU bringup).
12657 	 *
12658 	 * Platforms with unreliable TSCs don't have to deal with this, they
12659 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
12660 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
12661 	 * guarantee that they stay in perfect synchronization.
12662 	 */
12663 	if (backwards_tsc) {
12664 		u64 delta_cyc = max_tsc - local_tsc;
12665 		list_for_each_entry(kvm, &vm_list, vm_list) {
12666 			kvm->arch.backwards_tsc_observed = true;
12667 			kvm_for_each_vcpu(i, vcpu, kvm) {
12668 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
12669 				vcpu->arch.last_host_tsc = local_tsc;
12670 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12671 			}
12672 
12673 			/*
12674 			 * We have to disable TSC offset matching.. if you were
12675 			 * booting a VM while issuing an S4 host suspend....
12676 			 * you may have some problem.  Solving this issue is
12677 			 * left as an exercise to the reader.
12678 			 */
12679 			kvm->arch.last_tsc_nsec = 0;
12680 			kvm->arch.last_tsc_write = 0;
12681 		}
12682 
12683 	}
12684 	return 0;
12685 }
12686 
kvm_arch_disable_virtualization_cpu(void)12687 void kvm_arch_disable_virtualization_cpu(void)
12688 {
12689 	kvm_x86_call(disable_virtualization_cpu)();
12690 	drop_user_return_notifiers();
12691 }
12692 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)12693 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12694 {
12695 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12696 }
12697 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)12698 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12699 {
12700 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12701 }
12702 
kvm_arch_free_vm(struct kvm * kvm)12703 void kvm_arch_free_vm(struct kvm *kvm)
12704 {
12705 #if IS_ENABLED(CONFIG_HYPERV)
12706 	kfree(kvm->arch.hv_pa_pg);
12707 #endif
12708 	__kvm_arch_free_vm(kvm);
12709 }
12710 
12711 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)12712 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12713 {
12714 	int ret;
12715 	unsigned long flags;
12716 
12717 	if (!kvm_is_vm_type_supported(type))
12718 		return -EINVAL;
12719 
12720 	kvm->arch.vm_type = type;
12721 	kvm->arch.has_private_mem =
12722 		(type == KVM_X86_SW_PROTECTED_VM);
12723 	/* Decided by the vendor code for other VM types.  */
12724 	kvm->arch.pre_fault_allowed =
12725 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
12726 
12727 	ret = kvm_page_track_init(kvm);
12728 	if (ret)
12729 		goto out;
12730 
12731 	kvm_mmu_init_vm(kvm);
12732 
12733 	ret = kvm_x86_call(vm_init)(kvm);
12734 	if (ret)
12735 		goto out_uninit_mmu;
12736 
12737 	INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12738 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12739 
12740 	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12741 	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12742 	/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12743 	set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12744 		&kvm->arch.irq_sources_bitmap);
12745 
12746 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12747 	mutex_init(&kvm->arch.apic_map_lock);
12748 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12749 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12750 
12751 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12752 	pvclock_update_vm_gtod_copy(kvm);
12753 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12754 
12755 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12756 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
12757 	kvm->arch.guest_can_read_msr_platform_info = true;
12758 	kvm->arch.enable_pmu = enable_pmu;
12759 
12760 #if IS_ENABLED(CONFIG_HYPERV)
12761 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12762 	kvm->arch.hv_root_tdp = INVALID_PAGE;
12763 #endif
12764 
12765 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12766 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12767 
12768 	kvm_apicv_init(kvm);
12769 	kvm_hv_init_vm(kvm);
12770 	kvm_xen_init_vm(kvm);
12771 
12772 	if (ignore_msrs && !report_ignored_msrs) {
12773 		pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
12774 			     "a supported configuration.  Lying to the guest about the existence of MSRs\n"
12775 			     "may cause the guest operating system to hang or produce errors.  If a guest\n"
12776 			     "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
12777 	}
12778 
12779 	once_init(&kvm->arch.nx_once);
12780 	return 0;
12781 
12782 out_uninit_mmu:
12783 	kvm_mmu_uninit_vm(kvm);
12784 	kvm_page_track_cleanup(kvm);
12785 out:
12786 	return ret;
12787 }
12788 
12789 /**
12790  * __x86_set_memory_region: Setup KVM internal memory slot
12791  *
12792  * @kvm: the kvm pointer to the VM.
12793  * @id: the slot ID to setup.
12794  * @gpa: the GPA to install the slot (unused when @size == 0).
12795  * @size: the size of the slot. Set to zero to uninstall a slot.
12796  *
12797  * This function helps to setup a KVM internal memory slot.  Specify
12798  * @size > 0 to install a new slot, while @size == 0 to uninstall a
12799  * slot.  The return code can be one of the following:
12800  *
12801  *   HVA:           on success (uninstall will return a bogus HVA)
12802  *   -errno:        on error
12803  *
12804  * The caller should always use IS_ERR() to check the return value
12805  * before use.  Note, the KVM internal memory slots are guaranteed to
12806  * remain valid and unchanged until the VM is destroyed, i.e., the
12807  * GPA->HVA translation will not change.  However, the HVA is a user
12808  * address, i.e. its accessibility is not guaranteed, and must be
12809  * accessed via __copy_{to,from}_user().
12810  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)12811 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12812 				      u32 size)
12813 {
12814 	int i, r;
12815 	unsigned long hva, old_npages;
12816 	struct kvm_memslots *slots = kvm_memslots(kvm);
12817 	struct kvm_memory_slot *slot;
12818 
12819 	lockdep_assert_held(&kvm->slots_lock);
12820 
12821 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12822 		return ERR_PTR_USR(-EINVAL);
12823 
12824 	slot = id_to_memslot(slots, id);
12825 	if (size) {
12826 		if (slot && slot->npages)
12827 			return ERR_PTR_USR(-EEXIST);
12828 
12829 		/*
12830 		 * MAP_SHARED to prevent internal slot pages from being moved
12831 		 * by fork()/COW.
12832 		 */
12833 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12834 			      MAP_SHARED | MAP_ANONYMOUS, 0);
12835 		if (IS_ERR_VALUE(hva))
12836 			return (void __user *)hva;
12837 	} else {
12838 		if (!slot || !slot->npages)
12839 			return NULL;
12840 
12841 		old_npages = slot->npages;
12842 		hva = slot->userspace_addr;
12843 	}
12844 
12845 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
12846 		struct kvm_userspace_memory_region2 m;
12847 
12848 		m.slot = id | (i << 16);
12849 		m.flags = 0;
12850 		m.guest_phys_addr = gpa;
12851 		m.userspace_addr = hva;
12852 		m.memory_size = size;
12853 		r = kvm_set_internal_memslot(kvm, &m);
12854 		if (r < 0)
12855 			return ERR_PTR_USR(r);
12856 	}
12857 
12858 	if (!size)
12859 		vm_munmap(hva, old_npages * PAGE_SIZE);
12860 
12861 	return (void __user *)hva;
12862 }
12863 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12864 
kvm_arch_pre_destroy_vm(struct kvm * kvm)12865 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12866 {
12867 	/*
12868 	 * Stop all background workers and kthreads before destroying vCPUs, as
12869 	 * iterating over vCPUs in a different task while vCPUs are being freed
12870 	 * is unsafe, i.e. will lead to use-after-free.  The PIT also needs to
12871 	 * be stopped before IRQ routing is freed.
12872 	 */
12873 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12874 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12875 
12876 	kvm_free_pit(kvm);
12877 
12878 	kvm_mmu_pre_destroy_vm(kvm);
12879 }
12880 
kvm_arch_destroy_vm(struct kvm * kvm)12881 void kvm_arch_destroy_vm(struct kvm *kvm)
12882 {
12883 	if (current->mm == kvm->mm) {
12884 		/*
12885 		 * Free memory regions allocated on behalf of userspace,
12886 		 * unless the memory map has changed due to process exit
12887 		 * or fd copying.
12888 		 */
12889 		mutex_lock(&kvm->slots_lock);
12890 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12891 					0, 0);
12892 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12893 					0, 0);
12894 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12895 		mutex_unlock(&kvm->slots_lock);
12896 	}
12897 	kvm_destroy_vcpus(kvm);
12898 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12899 	kvm_pic_destroy(kvm);
12900 	kvm_ioapic_destroy(kvm);
12901 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12902 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12903 	kvm_mmu_uninit_vm(kvm);
12904 	kvm_page_track_cleanup(kvm);
12905 	kvm_xen_destroy_vm(kvm);
12906 	kvm_hv_destroy_vm(kvm);
12907 	kvm_x86_call(vm_destroy)(kvm);
12908 }
12909 
memslot_rmap_free(struct kvm_memory_slot * slot)12910 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12911 {
12912 	int i;
12913 
12914 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12915 		vfree(slot->arch.rmap[i]);
12916 		slot->arch.rmap[i] = NULL;
12917 	}
12918 }
12919 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12920 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12921 {
12922 	int i;
12923 
12924 	memslot_rmap_free(slot);
12925 
12926 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12927 		vfree(slot->arch.lpage_info[i - 1]);
12928 		slot->arch.lpage_info[i - 1] = NULL;
12929 	}
12930 
12931 	kvm_page_track_free_memslot(slot);
12932 }
12933 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)12934 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12935 {
12936 	const int sz = sizeof(*slot->arch.rmap[0]);
12937 	int i;
12938 
12939 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12940 		int level = i + 1;
12941 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12942 
12943 		if (slot->arch.rmap[i])
12944 			continue;
12945 
12946 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12947 		if (!slot->arch.rmap[i]) {
12948 			memslot_rmap_free(slot);
12949 			return -ENOMEM;
12950 		}
12951 	}
12952 
12953 	return 0;
12954 }
12955 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)12956 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12957 				      struct kvm_memory_slot *slot)
12958 {
12959 	unsigned long npages = slot->npages;
12960 	int i, r;
12961 
12962 	/*
12963 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
12964 	 * old arrays will be freed by kvm_set_memory_region() if installing
12965 	 * the new memslot is successful.
12966 	 */
12967 	memset(&slot->arch, 0, sizeof(slot->arch));
12968 
12969 	if (kvm_memslots_have_rmaps(kvm)) {
12970 		r = memslot_rmap_alloc(slot, npages);
12971 		if (r)
12972 			return r;
12973 	}
12974 
12975 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12976 		struct kvm_lpage_info *linfo;
12977 		unsigned long ugfn;
12978 		int lpages;
12979 		int level = i + 1;
12980 
12981 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12982 
12983 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
12984 		if (!linfo)
12985 			goto out_free;
12986 
12987 		slot->arch.lpage_info[i - 1] = linfo;
12988 
12989 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
12990 			linfo[0].disallow_lpage = 1;
12991 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
12992 			linfo[lpages - 1].disallow_lpage = 1;
12993 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
12994 		/*
12995 		 * If the gfn and userspace address are not aligned wrt each
12996 		 * other, disable large page support for this slot.
12997 		 */
12998 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
12999 			unsigned long j;
13000 
13001 			for (j = 0; j < lpages; ++j)
13002 				linfo[j].disallow_lpage = 1;
13003 		}
13004 	}
13005 
13006 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13007 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13008 #endif
13009 
13010 	if (kvm_page_track_create_memslot(kvm, slot, npages))
13011 		goto out_free;
13012 
13013 	return 0;
13014 
13015 out_free:
13016 	memslot_rmap_free(slot);
13017 
13018 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13019 		vfree(slot->arch.lpage_info[i - 1]);
13020 		slot->arch.lpage_info[i - 1] = NULL;
13021 	}
13022 	return -ENOMEM;
13023 }
13024 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13025 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13026 {
13027 	struct kvm_vcpu *vcpu;
13028 	unsigned long i;
13029 
13030 	/*
13031 	 * memslots->generation has been incremented.
13032 	 * mmio generation may have reached its maximum value.
13033 	 */
13034 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13035 
13036 	/* Force re-initialization of steal_time cache */
13037 	kvm_for_each_vcpu(i, vcpu, kvm)
13038 		kvm_vcpu_kick(vcpu);
13039 }
13040 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13041 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13042 				   const struct kvm_memory_slot *old,
13043 				   struct kvm_memory_slot *new,
13044 				   enum kvm_mr_change change)
13045 {
13046 	/*
13047 	 * KVM doesn't support moving memslots when there are external page
13048 	 * trackers attached to the VM, i.e. if KVMGT is in use.
13049 	 */
13050 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13051 		return -EINVAL;
13052 
13053 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13054 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13055 			return -EINVAL;
13056 
13057 		if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13058 			return -EINVAL;
13059 
13060 		return kvm_alloc_memslot_metadata(kvm, new);
13061 	}
13062 
13063 	if (change == KVM_MR_FLAGS_ONLY)
13064 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
13065 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13066 		return -EIO;
13067 
13068 	return 0;
13069 }
13070 
13071 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13072 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13073 {
13074 	int nr_slots;
13075 
13076 	if (!kvm_x86_ops.cpu_dirty_log_size)
13077 		return;
13078 
13079 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13080 	if ((enable && nr_slots == 1) || !nr_slots)
13081 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13082 }
13083 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13084 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13085 				     struct kvm_memory_slot *old,
13086 				     const struct kvm_memory_slot *new,
13087 				     enum kvm_mr_change change)
13088 {
13089 	u32 old_flags = old ? old->flags : 0;
13090 	u32 new_flags = new ? new->flags : 0;
13091 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13092 
13093 	/*
13094 	 * Update CPU dirty logging if dirty logging is being toggled.  This
13095 	 * applies to all operations.
13096 	 */
13097 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13098 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13099 
13100 	/*
13101 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
13102 	 * made writable) or CREATE/MOVE/DELETE of a slot.
13103 	 *
13104 	 * For a memslot with dirty logging disabled:
13105 	 * CREATE:      No dirty mappings will already exist.
13106 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13107 	 *		kvm_arch_flush_shadow_memslot()
13108 	 *
13109 	 * For a memslot with dirty logging enabled:
13110 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
13111 	 *		and no dirty bits to clear.
13112 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13113 	 *		kvm_arch_flush_shadow_memslot().
13114 	 */
13115 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13116 		return;
13117 
13118 	/*
13119 	 * READONLY and non-flags changes were filtered out above, and the only
13120 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13121 	 * logging isn't being toggled on or off.
13122 	 */
13123 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13124 		return;
13125 
13126 	if (!log_dirty_pages) {
13127 		/*
13128 		 * Recover huge page mappings in the slot now that dirty logging
13129 		 * is disabled, i.e. now that KVM does not have to track guest
13130 		 * writes at 4KiB granularity.
13131 		 *
13132 		 * Dirty logging might be disabled by userspace if an ongoing VM
13133 		 * live migration is cancelled and the VM must continue running
13134 		 * on the source.
13135 		 */
13136 		kvm_mmu_recover_huge_pages(kvm, new);
13137 	} else {
13138 		/*
13139 		 * Initially-all-set does not require write protecting any page,
13140 		 * because they're all assumed to be dirty.
13141 		 */
13142 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13143 			return;
13144 
13145 		if (READ_ONCE(eager_page_split))
13146 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13147 
13148 		if (kvm_x86_ops.cpu_dirty_log_size) {
13149 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13150 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13151 		} else {
13152 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13153 		}
13154 
13155 		/*
13156 		 * Unconditionally flush the TLBs after enabling dirty logging.
13157 		 * A flush is almost always going to be necessary (see below),
13158 		 * and unconditionally flushing allows the helpers to omit
13159 		 * the subtly complex checks when removing write access.
13160 		 *
13161 		 * Do the flush outside of mmu_lock to reduce the amount of
13162 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
13163 		 * safe as KVM only needs to guarantee the slot is fully
13164 		 * write-protected before returning to userspace, i.e. before
13165 		 * userspace can consume the dirty status.
13166 		 *
13167 		 * Flushing outside of mmu_lock requires KVM to be careful when
13168 		 * making decisions based on writable status of an SPTE, e.g. a
13169 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13170 		 *
13171 		 * Specifically, KVM also write-protects guest page tables to
13172 		 * monitor changes when using shadow paging, and must guarantee
13173 		 * no CPUs can write to those page before mmu_lock is dropped.
13174 		 * Because CPUs may have stale TLB entries at this point, a
13175 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13176 		 *
13177 		 * KVM also allows making SPTES writable outside of mmu_lock,
13178 		 * e.g. to allow dirty logging without taking mmu_lock.
13179 		 *
13180 		 * To handle these scenarios, KVM uses a separate software-only
13181 		 * bit (MMU-writable) to track if a SPTE is !writable due to
13182 		 * a guest page table being write-protected (KVM clears the
13183 		 * MMU-writable flag when write-protecting for shadow paging).
13184 		 *
13185 		 * The use of MMU-writable is also the primary motivation for
13186 		 * the unconditional flush.  Because KVM must guarantee that a
13187 		 * CPU doesn't contain stale, writable TLB entries for a
13188 		 * !MMU-writable SPTE, KVM must flush if it encounters any
13189 		 * MMU-writable SPTE regardless of whether the actual hardware
13190 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
13191 		 * to flush, while unconditionally flushing allows the "remove
13192 		 * write access" helpers to ignore MMU-writable entirely.
13193 		 *
13194 		 * See is_writable_pte() for more details (the case involving
13195 		 * access-tracked SPTEs is particularly relevant).
13196 		 */
13197 		kvm_flush_remote_tlbs_memslot(kvm, new);
13198 	}
13199 }
13200 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13201 void kvm_arch_commit_memory_region(struct kvm *kvm,
13202 				struct kvm_memory_slot *old,
13203 				const struct kvm_memory_slot *new,
13204 				enum kvm_mr_change change)
13205 {
13206 	if (change == KVM_MR_DELETE)
13207 		kvm_page_track_delete_slot(kvm, old);
13208 
13209 	if (!kvm->arch.n_requested_mmu_pages &&
13210 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13211 		unsigned long nr_mmu_pages;
13212 
13213 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13214 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13215 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13216 	}
13217 
13218 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
13219 
13220 	/* Free the arrays associated with the old memslot. */
13221 	if (change == KVM_MR_MOVE)
13222 		kvm_arch_free_memslot(kvm, old);
13223 }
13224 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13225 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13226 {
13227 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13228 
13229 	if (vcpu->arch.guest_state_protected)
13230 		return true;
13231 
13232 	return kvm_x86_call(get_cpl)(vcpu) == 0;
13233 }
13234 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13235 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13236 {
13237 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13238 
13239 	if (vcpu->arch.guest_state_protected)
13240 		return 0;
13241 
13242 	return kvm_rip_read(vcpu);
13243 }
13244 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13245 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13246 {
13247 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13248 }
13249 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13250 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13251 {
13252 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
13253 }
13254 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13255 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13256 {
13257 	/* Can't read the RIP when guest state is protected, just return 0 */
13258 	if (vcpu->arch.guest_state_protected)
13259 		return 0;
13260 
13261 	if (is_64_bit_mode(vcpu))
13262 		return kvm_rip_read(vcpu);
13263 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13264 		     kvm_rip_read(vcpu));
13265 }
13266 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13267 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13268 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13269 {
13270 	return kvm_get_linear_rip(vcpu) == linear_rip;
13271 }
13272 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13273 
kvm_get_rflags(struct kvm_vcpu * vcpu)13274 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13275 {
13276 	unsigned long rflags;
13277 
13278 	rflags = kvm_x86_call(get_rflags)(vcpu);
13279 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13280 		rflags &= ~X86_EFLAGS_TF;
13281 	return rflags;
13282 }
13283 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13284 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13285 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13286 {
13287 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13288 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13289 		rflags |= X86_EFLAGS_TF;
13290 	kvm_x86_call(set_rflags)(vcpu, rflags);
13291 }
13292 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13293 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13294 {
13295 	__kvm_set_rflags(vcpu, rflags);
13296 	kvm_make_request(KVM_REQ_EVENT, vcpu);
13297 }
13298 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13299 
kvm_async_pf_hash_fn(gfn_t gfn)13300 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13301 {
13302 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13303 
13304 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13305 }
13306 
kvm_async_pf_next_probe(u32 key)13307 static inline u32 kvm_async_pf_next_probe(u32 key)
13308 {
13309 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13310 }
13311 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13312 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13313 {
13314 	u32 key = kvm_async_pf_hash_fn(gfn);
13315 
13316 	while (vcpu->arch.apf.gfns[key] != ~0)
13317 		key = kvm_async_pf_next_probe(key);
13318 
13319 	vcpu->arch.apf.gfns[key] = gfn;
13320 }
13321 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13322 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13323 {
13324 	int i;
13325 	u32 key = kvm_async_pf_hash_fn(gfn);
13326 
13327 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
13328 		     (vcpu->arch.apf.gfns[key] != gfn &&
13329 		      vcpu->arch.apf.gfns[key] != ~0); i++)
13330 		key = kvm_async_pf_next_probe(key);
13331 
13332 	return key;
13333 }
13334 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13335 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13336 {
13337 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13338 }
13339 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13340 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13341 {
13342 	u32 i, j, k;
13343 
13344 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13345 
13346 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13347 		return;
13348 
13349 	while (true) {
13350 		vcpu->arch.apf.gfns[i] = ~0;
13351 		do {
13352 			j = kvm_async_pf_next_probe(j);
13353 			if (vcpu->arch.apf.gfns[j] == ~0)
13354 				return;
13355 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13356 			/*
13357 			 * k lies cyclically in ]i,j]
13358 			 * |    i.k.j |
13359 			 * |....j i.k.| or  |.k..j i...|
13360 			 */
13361 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13362 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13363 		i = j;
13364 	}
13365 }
13366 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13367 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13368 {
13369 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13370 
13371 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13372 				      sizeof(reason));
13373 }
13374 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13375 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13376 {
13377 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13378 
13379 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13380 					     &token, offset, sizeof(token));
13381 }
13382 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13383 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13384 {
13385 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13386 	u32 val;
13387 
13388 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13389 					 &val, offset, sizeof(val)))
13390 		return false;
13391 
13392 	return !val;
13393 }
13394 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13395 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13396 {
13397 
13398 	if (!kvm_pv_async_pf_enabled(vcpu))
13399 		return false;
13400 
13401 	if (!vcpu->arch.apf.send_always &&
13402 	    (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13403 		return false;
13404 
13405 	if (is_guest_mode(vcpu)) {
13406 		/*
13407 		 * L1 needs to opt into the special #PF vmexits that are
13408 		 * used to deliver async page faults.
13409 		 */
13410 		return vcpu->arch.apf.delivery_as_pf_vmexit;
13411 	} else {
13412 		/*
13413 		 * Play it safe in case the guest temporarily disables paging.
13414 		 * The real mode IDT in particular is unlikely to have a #PF
13415 		 * exception setup.
13416 		 */
13417 		return is_paging(vcpu);
13418 	}
13419 }
13420 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13421 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13422 {
13423 	if (unlikely(!lapic_in_kernel(vcpu) ||
13424 		     kvm_event_needs_reinjection(vcpu) ||
13425 		     kvm_is_exception_pending(vcpu)))
13426 		return false;
13427 
13428 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13429 		return false;
13430 
13431 	/*
13432 	 * If interrupts are off we cannot even use an artificial
13433 	 * halt state.
13434 	 */
13435 	return kvm_arch_interrupt_allowed(vcpu);
13436 }
13437 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13438 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13439 				     struct kvm_async_pf *work)
13440 {
13441 	struct x86_exception fault;
13442 
13443 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13444 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13445 
13446 	if (kvm_can_deliver_async_pf(vcpu) &&
13447 	    !apf_put_user_notpresent(vcpu)) {
13448 		fault.vector = PF_VECTOR;
13449 		fault.error_code_valid = true;
13450 		fault.error_code = 0;
13451 		fault.nested_page_fault = false;
13452 		fault.address = work->arch.token;
13453 		fault.async_page_fault = true;
13454 		kvm_inject_page_fault(vcpu, &fault);
13455 		return true;
13456 	} else {
13457 		/*
13458 		 * It is not possible to deliver a paravirtualized asynchronous
13459 		 * page fault, but putting the guest in an artificial halt state
13460 		 * can be beneficial nevertheless: if an interrupt arrives, we
13461 		 * can deliver it timely and perhaps the guest will schedule
13462 		 * another process.  When the instruction that triggered a page
13463 		 * fault is retried, hopefully the page will be ready in the host.
13464 		 */
13465 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13466 		return false;
13467 	}
13468 }
13469 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13470 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13471 				 struct kvm_async_pf *work)
13472 {
13473 	struct kvm_lapic_irq irq = {
13474 		.delivery_mode = APIC_DM_FIXED,
13475 		.vector = vcpu->arch.apf.vec
13476 	};
13477 
13478 	if (work->wakeup_all)
13479 		work->arch.token = ~0; /* broadcast wakeup */
13480 	else
13481 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13482 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13483 
13484 	if ((work->wakeup_all || work->notpresent_injected) &&
13485 	    kvm_pv_async_pf_enabled(vcpu) &&
13486 	    !apf_put_user_ready(vcpu, work->arch.token)) {
13487 		vcpu->arch.apf.pageready_pending = true;
13488 		kvm_apic_set_irq(vcpu, &irq, NULL);
13489 	}
13490 
13491 	vcpu->arch.apf.halted = false;
13492 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13493 }
13494 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13495 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13496 {
13497 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
13498 	if (!vcpu->arch.apf.pageready_pending)
13499 		kvm_vcpu_kick(vcpu);
13500 }
13501 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13502 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13503 {
13504 	if (!kvm_pv_async_pf_enabled(vcpu))
13505 		return true;
13506 	else
13507 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13508 }
13509 
kvm_arch_start_assignment(struct kvm * kvm)13510 void kvm_arch_start_assignment(struct kvm *kvm)
13511 {
13512 	if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13513 		kvm_x86_call(pi_start_assignment)(kvm);
13514 }
13515 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13516 
kvm_arch_end_assignment(struct kvm * kvm)13517 void kvm_arch_end_assignment(struct kvm *kvm)
13518 {
13519 	atomic_dec(&kvm->arch.assigned_device_count);
13520 }
13521 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13522 
kvm_arch_has_assigned_device(struct kvm * kvm)13523 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13524 {
13525 	return raw_atomic_read(&kvm->arch.assigned_device_count);
13526 }
13527 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13528 
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13529 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13530 {
13531 	/*
13532 	 * Non-coherent DMA assignment and de-assignment may affect whether or
13533 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13534 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
13535 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
13536 	 * with the correct "ignore guest PAT" setting are created.
13537 	 */
13538 	if (kvm_mmu_may_ignore_guest_pat())
13539 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13540 }
13541 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13542 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13543 {
13544 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13545 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13546 }
13547 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13548 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13549 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13550 {
13551 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13552 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13553 }
13554 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13555 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13556 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13557 {
13558 	return atomic_read(&kvm->arch.noncoherent_dma_count);
13559 }
13560 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13561 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13562 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13563 				      struct irq_bypass_producer *prod)
13564 {
13565 	struct kvm_kernel_irqfd *irqfd =
13566 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13567 	struct kvm *kvm = irqfd->kvm;
13568 	int ret;
13569 
13570 	kvm_arch_start_assignment(irqfd->kvm);
13571 
13572 	spin_lock_irq(&kvm->irqfds.lock);
13573 	irqfd->producer = prod;
13574 
13575 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13576 					   prod->irq, irqfd->gsi, 1);
13577 	if (ret)
13578 		kvm_arch_end_assignment(irqfd->kvm);
13579 
13580 	spin_unlock_irq(&kvm->irqfds.lock);
13581 
13582 
13583 	return ret;
13584 }
13585 
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13586 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13587 				      struct irq_bypass_producer *prod)
13588 {
13589 	int ret;
13590 	struct kvm_kernel_irqfd *irqfd =
13591 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13592 	struct kvm *kvm = irqfd->kvm;
13593 
13594 	WARN_ON(irqfd->producer != prod);
13595 
13596 	/*
13597 	 * When producer of consumer is unregistered, we change back to
13598 	 * remapped mode, so we can re-use the current implementation
13599 	 * when the irq is masked/disabled or the consumer side (KVM
13600 	 * int this case doesn't want to receive the interrupts.
13601 	*/
13602 	spin_lock_irq(&kvm->irqfds.lock);
13603 	irqfd->producer = NULL;
13604 
13605 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13606 					   prod->irq, irqfd->gsi, 0);
13607 	if (ret)
13608 		printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13609 		       " fails: %d\n", irqfd->consumer.token, ret);
13610 
13611 	spin_unlock_irq(&kvm->irqfds.lock);
13612 
13613 
13614 	kvm_arch_end_assignment(irqfd->kvm);
13615 }
13616 
kvm_arch_update_irqfd_routing(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)13617 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13618 				   uint32_t guest_irq, bool set)
13619 {
13620 	return kvm_x86_call(pi_update_irte)(kvm, host_irq, guest_irq, set);
13621 }
13622 
kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)13623 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13624 				  struct kvm_kernel_irq_routing_entry *new)
13625 {
13626 	if (old->type != KVM_IRQ_ROUTING_MSI ||
13627 	    new->type != KVM_IRQ_ROUTING_MSI)
13628 		return true;
13629 
13630 	return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13631 }
13632 
kvm_vector_hashing_enabled(void)13633 bool kvm_vector_hashing_enabled(void)
13634 {
13635 	return vector_hashing;
13636 }
13637 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13638 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13639 {
13640 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13641 }
13642 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13643 
13644 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13645 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13646 {
13647 	return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13648 }
13649 #endif
13650 
13651 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13652 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13653 {
13654 	kvm_x86_call(gmem_invalidate)(start, end);
13655 }
13656 #endif
13657 
kvm_spec_ctrl_test_value(u64 value)13658 int kvm_spec_ctrl_test_value(u64 value)
13659 {
13660 	/*
13661 	 * test that setting IA32_SPEC_CTRL to given value
13662 	 * is allowed by the host processor
13663 	 */
13664 
13665 	u64 saved_value;
13666 	unsigned long flags;
13667 	int ret = 0;
13668 
13669 	local_irq_save(flags);
13670 
13671 	if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13672 		ret = 1;
13673 	else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13674 		ret = 1;
13675 	else
13676 		wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13677 
13678 	local_irq_restore(flags);
13679 
13680 	return ret;
13681 }
13682 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13683 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)13684 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13685 {
13686 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13687 	struct x86_exception fault;
13688 	u64 access = error_code &
13689 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13690 
13691 	if (!(error_code & PFERR_PRESENT_MASK) ||
13692 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13693 		/*
13694 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13695 		 * tables probably do not match the TLB.  Just proceed
13696 		 * with the error code that the processor gave.
13697 		 */
13698 		fault.vector = PF_VECTOR;
13699 		fault.error_code_valid = true;
13700 		fault.error_code = error_code;
13701 		fault.nested_page_fault = false;
13702 		fault.address = gva;
13703 		fault.async_page_fault = false;
13704 	}
13705 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13706 }
13707 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13708 
13709 /*
13710  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13711  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13712  * indicates whether exit to userspace is needed.
13713  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)13714 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13715 			      struct x86_exception *e)
13716 {
13717 	if (r == X86EMUL_PROPAGATE_FAULT) {
13718 		if (KVM_BUG_ON(!e, vcpu->kvm))
13719 			return -EIO;
13720 
13721 		kvm_inject_emulated_page_fault(vcpu, e);
13722 		return 1;
13723 	}
13724 
13725 	/*
13726 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13727 	 * while handling a VMX instruction KVM could've handled the request
13728 	 * correctly by exiting to userspace and performing I/O but there
13729 	 * doesn't seem to be a real use-case behind such requests, just return
13730 	 * KVM_EXIT_INTERNAL_ERROR for now.
13731 	 */
13732 	kvm_prepare_emulation_failure_exit(vcpu);
13733 
13734 	return 0;
13735 }
13736 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13737 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)13738 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13739 {
13740 	bool pcid_enabled;
13741 	struct x86_exception e;
13742 	struct {
13743 		u64 pcid;
13744 		u64 gla;
13745 	} operand;
13746 	int r;
13747 
13748 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13749 	if (r != X86EMUL_CONTINUE)
13750 		return kvm_handle_memory_failure(vcpu, r, &e);
13751 
13752 	if (operand.pcid >> 12 != 0) {
13753 		kvm_inject_gp(vcpu, 0);
13754 		return 1;
13755 	}
13756 
13757 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
13758 
13759 	switch (type) {
13760 	case INVPCID_TYPE_INDIV_ADDR:
13761 		/*
13762 		 * LAM doesn't apply to addresses that are inputs to TLB
13763 		 * invalidation.
13764 		 */
13765 		if ((!pcid_enabled && (operand.pcid != 0)) ||
13766 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
13767 			kvm_inject_gp(vcpu, 0);
13768 			return 1;
13769 		}
13770 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13771 		return kvm_skip_emulated_instruction(vcpu);
13772 
13773 	case INVPCID_TYPE_SINGLE_CTXT:
13774 		if (!pcid_enabled && (operand.pcid != 0)) {
13775 			kvm_inject_gp(vcpu, 0);
13776 			return 1;
13777 		}
13778 
13779 		kvm_invalidate_pcid(vcpu, operand.pcid);
13780 		return kvm_skip_emulated_instruction(vcpu);
13781 
13782 	case INVPCID_TYPE_ALL_NON_GLOBAL:
13783 		/*
13784 		 * Currently, KVM doesn't mark global entries in the shadow
13785 		 * page tables, so a non-global flush just degenerates to a
13786 		 * global flush. If needed, we could optimize this later by
13787 		 * keeping track of global entries in shadow page tables.
13788 		 */
13789 
13790 		fallthrough;
13791 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
13792 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13793 		return kvm_skip_emulated_instruction(vcpu);
13794 
13795 	default:
13796 		kvm_inject_gp(vcpu, 0);
13797 		return 1;
13798 	}
13799 }
13800 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13801 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)13802 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13803 {
13804 	struct kvm_run *run = vcpu->run;
13805 	struct kvm_mmio_fragment *frag;
13806 	unsigned int len;
13807 
13808 	BUG_ON(!vcpu->mmio_needed);
13809 
13810 	/* Complete previous fragment */
13811 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13812 	len = min(8u, frag->len);
13813 	if (!vcpu->mmio_is_write)
13814 		memcpy(frag->data, run->mmio.data, len);
13815 
13816 	if (frag->len <= 8) {
13817 		/* Switch to the next fragment. */
13818 		frag++;
13819 		vcpu->mmio_cur_fragment++;
13820 	} else {
13821 		/* Go forward to the next mmio piece. */
13822 		frag->data += len;
13823 		frag->gpa += len;
13824 		frag->len -= len;
13825 	}
13826 
13827 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13828 		vcpu->mmio_needed = 0;
13829 
13830 		// VMG change, at this point, we're always done
13831 		// RIP has already been advanced
13832 		return 1;
13833 	}
13834 
13835 	// More MMIO is needed
13836 	run->mmio.phys_addr = frag->gpa;
13837 	run->mmio.len = min(8u, frag->len);
13838 	run->mmio.is_write = vcpu->mmio_is_write;
13839 	if (run->mmio.is_write)
13840 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13841 	run->exit_reason = KVM_EXIT_MMIO;
13842 
13843 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13844 
13845 	return 0;
13846 }
13847 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13848 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13849 			  void *data)
13850 {
13851 	int handled;
13852 	struct kvm_mmio_fragment *frag;
13853 
13854 	if (!data)
13855 		return -EINVAL;
13856 
13857 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13858 	if (handled == bytes)
13859 		return 1;
13860 
13861 	bytes -= handled;
13862 	gpa += handled;
13863 	data += handled;
13864 
13865 	/*TODO: Check if need to increment number of frags */
13866 	frag = vcpu->mmio_fragments;
13867 	vcpu->mmio_nr_fragments = 1;
13868 	frag->len = bytes;
13869 	frag->gpa = gpa;
13870 	frag->data = data;
13871 
13872 	vcpu->mmio_needed = 1;
13873 	vcpu->mmio_cur_fragment = 0;
13874 
13875 	vcpu->run->mmio.phys_addr = gpa;
13876 	vcpu->run->mmio.len = min(8u, frag->len);
13877 	vcpu->run->mmio.is_write = 1;
13878 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13879 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13880 
13881 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13882 
13883 	return 0;
13884 }
13885 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13886 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13887 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13888 			 void *data)
13889 {
13890 	int handled;
13891 	struct kvm_mmio_fragment *frag;
13892 
13893 	if (!data)
13894 		return -EINVAL;
13895 
13896 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13897 	if (handled == bytes)
13898 		return 1;
13899 
13900 	bytes -= handled;
13901 	gpa += handled;
13902 	data += handled;
13903 
13904 	/*TODO: Check if need to increment number of frags */
13905 	frag = vcpu->mmio_fragments;
13906 	vcpu->mmio_nr_fragments = 1;
13907 	frag->len = bytes;
13908 	frag->gpa = gpa;
13909 	frag->data = data;
13910 
13911 	vcpu->mmio_needed = 1;
13912 	vcpu->mmio_cur_fragment = 0;
13913 
13914 	vcpu->run->mmio.phys_addr = gpa;
13915 	vcpu->run->mmio.len = min(8u, frag->len);
13916 	vcpu->run->mmio.is_write = 0;
13917 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13918 
13919 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13920 
13921 	return 0;
13922 }
13923 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13924 
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)13925 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13926 {
13927 	vcpu->arch.sev_pio_count -= count;
13928 	vcpu->arch.sev_pio_data += count * size;
13929 }
13930 
13931 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13932 			   unsigned int port);
13933 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)13934 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13935 {
13936 	int size = vcpu->arch.pio.size;
13937 	int port = vcpu->arch.pio.port;
13938 
13939 	vcpu->arch.pio.count = 0;
13940 	if (vcpu->arch.sev_pio_count)
13941 		return kvm_sev_es_outs(vcpu, size, port);
13942 	return 1;
13943 }
13944 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13945 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13946 			   unsigned int port)
13947 {
13948 	for (;;) {
13949 		unsigned int count =
13950 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13951 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13952 
13953 		/* memcpy done already by emulator_pio_out.  */
13954 		advance_sev_es_emulated_pio(vcpu, count, size);
13955 		if (!ret)
13956 			break;
13957 
13958 		/* Emulation done by the kernel.  */
13959 		if (!vcpu->arch.sev_pio_count)
13960 			return 1;
13961 	}
13962 
13963 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13964 	return 0;
13965 }
13966 
13967 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13968 			  unsigned int port);
13969 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)13970 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13971 {
13972 	unsigned count = vcpu->arch.pio.count;
13973 	int size = vcpu->arch.pio.size;
13974 	int port = vcpu->arch.pio.port;
13975 
13976 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
13977 	advance_sev_es_emulated_pio(vcpu, count, size);
13978 	if (vcpu->arch.sev_pio_count)
13979 		return kvm_sev_es_ins(vcpu, size, port);
13980 	return 1;
13981 }
13982 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13983 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13984 			  unsigned int port)
13985 {
13986 	for (;;) {
13987 		unsigned int count =
13988 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13989 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
13990 			break;
13991 
13992 		/* Emulation done by the kernel.  */
13993 		advance_sev_es_emulated_pio(vcpu, count, size);
13994 		if (!vcpu->arch.sev_pio_count)
13995 			return 1;
13996 	}
13997 
13998 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
13999 	return 0;
14000 }
14001 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14002 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14003 			 unsigned int port, void *data,  unsigned int count,
14004 			 int in)
14005 {
14006 	vcpu->arch.sev_pio_data = data;
14007 	vcpu->arch.sev_pio_count = count;
14008 	return in ? kvm_sev_es_ins(vcpu, size, port)
14009 		  : kvm_sev_es_outs(vcpu, size, port);
14010 }
14011 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
14012 
14013 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14014 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14015 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14016 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14017 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14018 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14019 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14020 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14021 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14022 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14023 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14024 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14025 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14026 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14027 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14028 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14029 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14030 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14031 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
14032 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14033 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14034 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14035 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14036 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14037 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14038 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14039 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14040 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14041 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14042 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14043 
kvm_x86_init(void)14044 static int __init kvm_x86_init(void)
14045 {
14046 	kvm_init_xstate_sizes();
14047 
14048 	kvm_mmu_x86_module_init();
14049 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14050 	return 0;
14051 }
14052 module_init(kvm_x86_init);
14053 
kvm_x86_exit(void)14054 static void __exit kvm_x86_exit(void)
14055 {
14056 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14057 }
14058 module_exit(kvm_x86_exit);
14059