• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
123 
124 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
125 
126 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
127 
128 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
129                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
130 
131 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
132 static void process_nmi(struct kvm_vcpu *vcpu);
133 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
134 static void store_regs(struct kvm_vcpu *vcpu);
135 static int sync_regs(struct kvm_vcpu *vcpu);
136 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
137 
138 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
139 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
140 
141 static DEFINE_MUTEX(vendor_module_lock);
142 struct kvm_x86_ops kvm_x86_ops __read_mostly;
143 
144 #define KVM_X86_OP(func)					     \
145 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
146 				*(((struct kvm_x86_ops *)0)->func));
147 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
148 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
149 #include <asm/kvm-x86-ops.h>
150 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
151 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
152 
153 static bool __read_mostly ignore_msrs = 0;
154 module_param(ignore_msrs, bool, 0644);
155 
156 bool __read_mostly report_ignored_msrs = true;
157 module_param(report_ignored_msrs, bool, 0644);
158 EXPORT_SYMBOL_GPL(report_ignored_msrs);
159 
160 unsigned int min_timer_period_us = 200;
161 module_param(min_timer_period_us, uint, 0644);
162 
163 static bool __read_mostly kvmclock_periodic_sync = true;
164 module_param(kvmclock_periodic_sync, bool, 0444);
165 
166 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
167 static u32 __read_mostly tsc_tolerance_ppm = 250;
168 module_param(tsc_tolerance_ppm, uint, 0644);
169 
170 static bool __read_mostly vector_hashing = true;
171 module_param(vector_hashing, bool, 0444);
172 
173 bool __read_mostly enable_vmware_backdoor = false;
174 module_param(enable_vmware_backdoor, bool, 0444);
175 EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
176 
177 /*
178  * Flags to manipulate forced emulation behavior (any non-zero value will
179  * enable forced emulation).
180  */
181 #define KVM_FEP_CLEAR_RFLAGS_RF	BIT(1)
182 static int __read_mostly force_emulation_prefix;
183 module_param(force_emulation_prefix, int, 0644);
184 
185 int __read_mostly pi_inject_timer = -1;
186 module_param(pi_inject_timer, bint, 0644);
187 
188 /* Enable/disable PMU virtualization */
189 bool __read_mostly enable_pmu = true;
190 EXPORT_SYMBOL_GPL(enable_pmu);
191 module_param(enable_pmu, bool, 0444);
192 
193 bool __read_mostly eager_page_split = true;
194 module_param(eager_page_split, bool, 0644);
195 
196 /* Enable/disable SMT_RSB bug mitigation */
197 static bool __read_mostly mitigate_smt_rsb;
198 module_param(mitigate_smt_rsb, bool, 0444);
199 
200 /*
201  * Restoring the host value for MSRs that are only consumed when running in
202  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
203  * returns to userspace, i.e. the kernel can run with the guest's value.
204  */
205 #define KVM_MAX_NR_USER_RETURN_MSRS 16
206 
207 struct kvm_user_return_msrs {
208 	struct user_return_notifier urn;
209 	bool registered;
210 	struct kvm_user_return_msr_values {
211 		u64 host;
212 		u64 curr;
213 	} values[KVM_MAX_NR_USER_RETURN_MSRS];
214 };
215 
216 u32 __read_mostly kvm_nr_uret_msrs;
217 EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
218 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
219 static struct kvm_user_return_msrs __percpu *user_return_msrs;
220 
221 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
222 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
223 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
224 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
225 
226 bool __read_mostly allow_smaller_maxphyaddr = 0;
227 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
228 
229 bool __read_mostly enable_apicv = true;
230 EXPORT_SYMBOL_GPL(enable_apicv);
231 
232 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
233 	KVM_GENERIC_VM_STATS(),
234 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
235 	STATS_DESC_COUNTER(VM, mmu_pte_write),
236 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
237 	STATS_DESC_COUNTER(VM, mmu_flooded),
238 	STATS_DESC_COUNTER(VM, mmu_recycled),
239 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
240 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
241 	STATS_DESC_ICOUNTER(VM, pages_4k),
242 	STATS_DESC_ICOUNTER(VM, pages_2m),
243 	STATS_DESC_ICOUNTER(VM, pages_1g),
244 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
245 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
246 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
247 };
248 
249 const struct kvm_stats_header kvm_vm_stats_header = {
250 	.name_size = KVM_STATS_NAME_SIZE,
251 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
252 	.id_offset = sizeof(struct kvm_stats_header),
253 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
254 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
255 		       sizeof(kvm_vm_stats_desc),
256 };
257 
258 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
259 	KVM_GENERIC_VCPU_STATS(),
260 	STATS_DESC_COUNTER(VCPU, pf_taken),
261 	STATS_DESC_COUNTER(VCPU, pf_fixed),
262 	STATS_DESC_COUNTER(VCPU, pf_emulate),
263 	STATS_DESC_COUNTER(VCPU, pf_spurious),
264 	STATS_DESC_COUNTER(VCPU, pf_fast),
265 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
266 	STATS_DESC_COUNTER(VCPU, pf_guest),
267 	STATS_DESC_COUNTER(VCPU, tlb_flush),
268 	STATS_DESC_COUNTER(VCPU, invlpg),
269 	STATS_DESC_COUNTER(VCPU, exits),
270 	STATS_DESC_COUNTER(VCPU, io_exits),
271 	STATS_DESC_COUNTER(VCPU, mmio_exits),
272 	STATS_DESC_COUNTER(VCPU, signal_exits),
273 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
274 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
275 	STATS_DESC_COUNTER(VCPU, l1d_flush),
276 	STATS_DESC_COUNTER(VCPU, halt_exits),
277 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
278 	STATS_DESC_COUNTER(VCPU, irq_exits),
279 	STATS_DESC_COUNTER(VCPU, host_state_reload),
280 	STATS_DESC_COUNTER(VCPU, fpu_reload),
281 	STATS_DESC_COUNTER(VCPU, insn_emulation),
282 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
283 	STATS_DESC_COUNTER(VCPU, hypercalls),
284 	STATS_DESC_COUNTER(VCPU, irq_injections),
285 	STATS_DESC_COUNTER(VCPU, nmi_injections),
286 	STATS_DESC_COUNTER(VCPU, req_event),
287 	STATS_DESC_COUNTER(VCPU, nested_run),
288 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
289 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
290 	STATS_DESC_COUNTER(VCPU, preemption_reported),
291 	STATS_DESC_COUNTER(VCPU, preemption_other),
292 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
293 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
294 };
295 
296 const struct kvm_stats_header kvm_vcpu_stats_header = {
297 	.name_size = KVM_STATS_NAME_SIZE,
298 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
299 	.id_offset = sizeof(struct kvm_stats_header),
300 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
301 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
302 		       sizeof(kvm_vcpu_stats_desc),
303 };
304 
305 static struct kmem_cache *x86_emulator_cache;
306 
307 /*
308  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
309  * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
310  * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.  msrs_to_save holds MSRs that
311  * require host support, i.e. should be probed via RDMSR.  emulated_msrs holds
312  * MSRs that KVM emulates without strictly requiring host support.
313  * msr_based_features holds MSRs that enumerate features, i.e. are effectively
314  * CPUID leafs.  Note, msr_based_features isn't mutually exclusive with
315  * msrs_to_save and emulated_msrs.
316  */
317 
318 static const u32 msrs_to_save_base[] = {
319 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
320 	MSR_STAR,
321 #ifdef CONFIG_X86_64
322 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
323 #endif
324 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
325 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
326 	MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
327 	MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
328 	MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
329 	MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
330 	MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
331 	MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
332 	MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
333 	MSR_IA32_UMWAIT_CONTROL,
334 
335 	MSR_IA32_XFD, MSR_IA32_XFD_ERR,
336 };
337 
338 static const u32 msrs_to_save_pmu[] = {
339 	MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
340 	MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
341 	MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
342 	MSR_CORE_PERF_GLOBAL_CTRL,
343 	MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
344 
345 	/* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
346 	MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
347 	MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
348 	MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
349 	MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
350 	MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
351 	MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
352 	MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
353 	MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
354 
355 	MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
356 	MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
357 
358 	/* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
359 	MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
360 	MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
361 	MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
362 	MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
363 
364 	MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
365 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
366 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
367 };
368 
369 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
370 			ARRAY_SIZE(msrs_to_save_pmu)];
371 static unsigned num_msrs_to_save;
372 
373 static const u32 emulated_msrs_all[] = {
374 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
375 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
376 
377 #ifdef CONFIG_KVM_HYPERV
378 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
379 	HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
380 	HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
381 	HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
382 	HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
383 	HV_X64_MSR_RESET,
384 	HV_X64_MSR_VP_INDEX,
385 	HV_X64_MSR_VP_RUNTIME,
386 	HV_X64_MSR_SCONTROL,
387 	HV_X64_MSR_STIMER0_CONFIG,
388 	HV_X64_MSR_VP_ASSIST_PAGE,
389 	HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
390 	HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
391 	HV_X64_MSR_SYNDBG_OPTIONS,
392 	HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
393 	HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
394 	HV_X64_MSR_SYNDBG_PENDING_BUFFER,
395 #endif
396 
397 	MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
398 	MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
399 
400 	MSR_IA32_TSC_ADJUST,
401 	MSR_IA32_TSC_DEADLINE,
402 	MSR_IA32_ARCH_CAPABILITIES,
403 	MSR_IA32_PERF_CAPABILITIES,
404 	MSR_IA32_MISC_ENABLE,
405 	MSR_IA32_MCG_STATUS,
406 	MSR_IA32_MCG_CTL,
407 	MSR_IA32_MCG_EXT_CTL,
408 	MSR_IA32_SMBASE,
409 	MSR_SMI_COUNT,
410 	MSR_PLATFORM_INFO,
411 	MSR_MISC_FEATURES_ENABLES,
412 	MSR_AMD64_VIRT_SPEC_CTRL,
413 	MSR_AMD64_TSC_RATIO,
414 	MSR_IA32_POWER_CTL,
415 	MSR_IA32_UCODE_REV,
416 
417 	/*
418 	 * KVM always supports the "true" VMX control MSRs, even if the host
419 	 * does not.  The VMX MSRs as a whole are considered "emulated" as KVM
420 	 * doesn't strictly require them to exist in the host (ignoring that
421 	 * KVM would refuse to load in the first place if the core set of MSRs
422 	 * aren't supported).
423 	 */
424 	MSR_IA32_VMX_BASIC,
425 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
426 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
427 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
428 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
429 	MSR_IA32_VMX_MISC,
430 	MSR_IA32_VMX_CR0_FIXED0,
431 	MSR_IA32_VMX_CR4_FIXED0,
432 	MSR_IA32_VMX_VMCS_ENUM,
433 	MSR_IA32_VMX_PROCBASED_CTLS2,
434 	MSR_IA32_VMX_EPT_VPID_CAP,
435 	MSR_IA32_VMX_VMFUNC,
436 
437 	MSR_K7_HWCR,
438 	MSR_KVM_POLL_CONTROL,
439 };
440 
441 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
442 static unsigned num_emulated_msrs;
443 
444 /*
445  * List of MSRs that control the existence of MSR-based features, i.e. MSRs
446  * that are effectively CPUID leafs.  VMX MSRs are also included in the set of
447  * feature MSRs, but are handled separately to allow expedited lookups.
448  */
449 static const u32 msr_based_features_all_except_vmx[] = {
450 	MSR_AMD64_DE_CFG,
451 	MSR_IA32_UCODE_REV,
452 	MSR_IA32_ARCH_CAPABILITIES,
453 	MSR_IA32_PERF_CAPABILITIES,
454 };
455 
456 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
457 			      (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
458 static unsigned int num_msr_based_features;
459 
460 /*
461  * All feature MSRs except uCode revID, which tracks the currently loaded uCode
462  * patch, are immutable once the vCPU model is defined.
463  */
kvm_is_immutable_feature_msr(u32 msr)464 static bool kvm_is_immutable_feature_msr(u32 msr)
465 {
466 	int i;
467 
468 	if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
469 		return true;
470 
471 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
472 		if (msr == msr_based_features_all_except_vmx[i])
473 			return msr != MSR_IA32_UCODE_REV;
474 	}
475 
476 	return false;
477 }
478 
kvm_is_advertised_msr(u32 msr_index)479 static bool kvm_is_advertised_msr(u32 msr_index)
480 {
481 	unsigned int i;
482 
483 	for (i = 0; i < num_msrs_to_save; i++) {
484 		if (msrs_to_save[i] == msr_index)
485 			return true;
486 	}
487 
488 	for (i = 0; i < num_emulated_msrs; i++) {
489 		if (emulated_msrs[i] == msr_index)
490 			return true;
491 	}
492 
493 	return false;
494 }
495 
496 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
497 			    bool host_initiated);
498 
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)499 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
500 					     u64 *data, bool host_initiated,
501 					     enum kvm_msr_access rw,
502 					     msr_access_t msr_access_fn)
503 {
504 	const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
505 	int ret;
506 
507 	BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
508 
509 	/*
510 	 * Zero the data on read failures to avoid leaking stack data to the
511 	 * guest and/or userspace, e.g. if the failure is ignored below.
512 	 */
513 	ret = msr_access_fn(vcpu, msr, data, host_initiated);
514 	if (ret && rw == MSR_TYPE_R)
515 		*data = 0;
516 
517 	if (ret != KVM_MSR_RET_UNSUPPORTED)
518 		return ret;
519 
520 	/*
521 	 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
522 	 * advertises to userspace, even if an MSR isn't fully supported.
523 	 * Simply check that @data is '0', which covers both the write '0' case
524 	 * and all reads (in which case @data is zeroed on failure; see above).
525 	 */
526 	if (host_initiated && !*data && kvm_is_advertised_msr(msr))
527 		return 0;
528 
529 	if (!ignore_msrs) {
530 		kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
531 				      op, msr, *data);
532 		return ret;
533 	}
534 
535 	if (report_ignored_msrs)
536 		kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
537 
538 	return 0;
539 }
540 
kvm_alloc_emulator_cache(void)541 static struct kmem_cache *kvm_alloc_emulator_cache(void)
542 {
543 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
544 	unsigned int size = sizeof(struct x86_emulate_ctxt);
545 
546 	return kmem_cache_create_usercopy("x86_emulator", size,
547 					  __alignof__(struct x86_emulate_ctxt),
548 					  SLAB_ACCOUNT, useroffset,
549 					  size - useroffset, NULL);
550 }
551 
552 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
553 
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)554 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
555 {
556 	int i;
557 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
558 		vcpu->arch.apf.gfns[i] = ~0;
559 }
560 
kvm_on_user_return(struct user_return_notifier * urn)561 static void kvm_on_user_return(struct user_return_notifier *urn)
562 {
563 	unsigned slot;
564 	struct kvm_user_return_msrs *msrs
565 		= container_of(urn, struct kvm_user_return_msrs, urn);
566 	struct kvm_user_return_msr_values *values;
567 	unsigned long flags;
568 
569 	/*
570 	 * Disabling irqs at this point since the following code could be
571 	 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
572 	 */
573 	local_irq_save(flags);
574 	if (msrs->registered) {
575 		msrs->registered = false;
576 		user_return_notifier_unregister(urn);
577 	}
578 	local_irq_restore(flags);
579 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
580 		values = &msrs->values[slot];
581 		if (values->host != values->curr) {
582 			wrmsrl(kvm_uret_msrs_list[slot], values->host);
583 			values->curr = values->host;
584 		}
585 	}
586 }
587 
kvm_probe_user_return_msr(u32 msr)588 static int kvm_probe_user_return_msr(u32 msr)
589 {
590 	u64 val;
591 	int ret;
592 
593 	preempt_disable();
594 	ret = rdmsrl_safe(msr, &val);
595 	if (ret)
596 		goto out;
597 	ret = wrmsrl_safe(msr, val);
598 out:
599 	preempt_enable();
600 	return ret;
601 }
602 
kvm_add_user_return_msr(u32 msr)603 int kvm_add_user_return_msr(u32 msr)
604 {
605 	BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
606 
607 	if (kvm_probe_user_return_msr(msr))
608 		return -1;
609 
610 	kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
611 	return kvm_nr_uret_msrs++;
612 }
613 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
614 
kvm_find_user_return_msr(u32 msr)615 int kvm_find_user_return_msr(u32 msr)
616 {
617 	int i;
618 
619 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
620 		if (kvm_uret_msrs_list[i] == msr)
621 			return i;
622 	}
623 	return -1;
624 }
625 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
626 
kvm_user_return_msr_cpu_online(void)627 static void kvm_user_return_msr_cpu_online(void)
628 {
629 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
630 	u64 value;
631 	int i;
632 
633 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
634 		rdmsrl_safe(kvm_uret_msrs_list[i], &value);
635 		msrs->values[i].host = value;
636 		msrs->values[i].curr = value;
637 	}
638 }
639 
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)640 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
641 {
642 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
643 	int err;
644 
645 	value = (value & mask) | (msrs->values[slot].host & ~mask);
646 	if (value == msrs->values[slot].curr)
647 		return 0;
648 	err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
649 	if (err)
650 		return 1;
651 
652 	msrs->values[slot].curr = value;
653 	if (!msrs->registered) {
654 		msrs->urn.on_user_return = kvm_on_user_return;
655 		user_return_notifier_register(&msrs->urn);
656 		msrs->registered = true;
657 	}
658 	return 0;
659 }
660 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
661 
drop_user_return_notifiers(void)662 static void drop_user_return_notifiers(void)
663 {
664 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
665 
666 	if (msrs->registered)
667 		kvm_on_user_return(&msrs->urn);
668 }
669 
kvm_set_apic_base(struct kvm_vcpu * vcpu,struct msr_data * msr_info)670 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
671 {
672 	enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
673 	enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
674 	u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
675 		(guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
676 
677 	if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
678 		return 1;
679 	if (!msr_info->host_initiated) {
680 		if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
681 			return 1;
682 		if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
683 			return 1;
684 	}
685 
686 	kvm_lapic_set_base(vcpu, msr_info->data);
687 	kvm_recalculate_apic_map(vcpu->kvm);
688 	return 0;
689 }
690 
691 /*
692  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
693  *
694  * Hardware virtualization extension instructions may fault if a reboot turns
695  * off virtualization while processes are running.  Usually after catching the
696  * fault we just panic; during reboot instead the instruction is ignored.
697  */
kvm_spurious_fault(void)698 noinstr void kvm_spurious_fault(void)
699 {
700 	/* Fault while not rebooting.  We want the trace. */
701 	BUG_ON(!kvm_rebooting);
702 }
703 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
704 
705 #define EXCPT_BENIGN		0
706 #define EXCPT_CONTRIBUTORY	1
707 #define EXCPT_PF		2
708 
exception_class(int vector)709 static int exception_class(int vector)
710 {
711 	switch (vector) {
712 	case PF_VECTOR:
713 		return EXCPT_PF;
714 	case DE_VECTOR:
715 	case TS_VECTOR:
716 	case NP_VECTOR:
717 	case SS_VECTOR:
718 	case GP_VECTOR:
719 		return EXCPT_CONTRIBUTORY;
720 	default:
721 		break;
722 	}
723 	return EXCPT_BENIGN;
724 }
725 
726 #define EXCPT_FAULT		0
727 #define EXCPT_TRAP		1
728 #define EXCPT_ABORT		2
729 #define EXCPT_INTERRUPT		3
730 #define EXCPT_DB		4
731 
exception_type(int vector)732 static int exception_type(int vector)
733 {
734 	unsigned int mask;
735 
736 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
737 		return EXCPT_INTERRUPT;
738 
739 	mask = 1 << vector;
740 
741 	/*
742 	 * #DBs can be trap-like or fault-like, the caller must check other CPU
743 	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
744 	 */
745 	if (mask & (1 << DB_VECTOR))
746 		return EXCPT_DB;
747 
748 	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
749 		return EXCPT_TRAP;
750 
751 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
752 		return EXCPT_ABORT;
753 
754 	/* Reserved exceptions will result in fault */
755 	return EXCPT_FAULT;
756 }
757 
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)758 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
759 				   struct kvm_queued_exception *ex)
760 {
761 	if (!ex->has_payload)
762 		return;
763 
764 	switch (ex->vector) {
765 	case DB_VECTOR:
766 		/*
767 		 * "Certain debug exceptions may clear bit 0-3.  The
768 		 * remaining contents of the DR6 register are never
769 		 * cleared by the processor".
770 		 */
771 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
772 		/*
773 		 * In order to reflect the #DB exception payload in guest
774 		 * dr6, three components need to be considered: active low
775 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
776 		 * DR6_BS and DR6_BT)
777 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
778 		 * In the target guest dr6:
779 		 * FIXED_1 bits should always be set.
780 		 * Active low bits should be cleared if 1-setting in payload.
781 		 * Active high bits should be set if 1-setting in payload.
782 		 *
783 		 * Note, the payload is compatible with the pending debug
784 		 * exceptions/exit qualification under VMX, that active_low bits
785 		 * are active high in payload.
786 		 * So they need to be flipped for DR6.
787 		 */
788 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
789 		vcpu->arch.dr6 |= ex->payload;
790 		vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
791 
792 		/*
793 		 * The #DB payload is defined as compatible with the 'pending
794 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
795 		 * defined in the 'pending debug exceptions' field (enabled
796 		 * breakpoint), it is reserved and must be zero in DR6.
797 		 */
798 		vcpu->arch.dr6 &= ~BIT(12);
799 		break;
800 	case PF_VECTOR:
801 		vcpu->arch.cr2 = ex->payload;
802 		break;
803 	}
804 
805 	ex->has_payload = false;
806 	ex->payload = 0;
807 }
808 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
809 
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)810 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
811 				       bool has_error_code, u32 error_code,
812 				       bool has_payload, unsigned long payload)
813 {
814 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
815 
816 	ex->vector = vector;
817 	ex->injected = false;
818 	ex->pending = true;
819 	ex->has_error_code = has_error_code;
820 	ex->error_code = error_code;
821 	ex->has_payload = has_payload;
822 	ex->payload = payload;
823 }
824 
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload,bool reinject)825 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
826 		unsigned nr, bool has_error, u32 error_code,
827 	        bool has_payload, unsigned long payload, bool reinject)
828 {
829 	u32 prev_nr;
830 	int class1, class2;
831 
832 	kvm_make_request(KVM_REQ_EVENT, vcpu);
833 
834 	/*
835 	 * If the exception is destined for L2 and isn't being reinjected,
836 	 * morph it to a VM-Exit if L1 wants to intercept the exception.  A
837 	 * previously injected exception is not checked because it was checked
838 	 * when it was original queued, and re-checking is incorrect if _L1_
839 	 * injected the exception, in which case it's exempt from interception.
840 	 */
841 	if (!reinject && is_guest_mode(vcpu) &&
842 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
843 		kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
844 					   has_payload, payload);
845 		return;
846 	}
847 
848 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
849 	queue:
850 		if (reinject) {
851 			/*
852 			 * On VM-Entry, an exception can be pending if and only
853 			 * if event injection was blocked by nested_run_pending.
854 			 * In that case, however, vcpu_enter_guest() requests an
855 			 * immediate exit, and the guest shouldn't proceed far
856 			 * enough to need reinjection.
857 			 */
858 			WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
859 			vcpu->arch.exception.injected = true;
860 			if (WARN_ON_ONCE(has_payload)) {
861 				/*
862 				 * A reinjected event has already
863 				 * delivered its payload.
864 				 */
865 				has_payload = false;
866 				payload = 0;
867 			}
868 		} else {
869 			vcpu->arch.exception.pending = true;
870 			vcpu->arch.exception.injected = false;
871 		}
872 		vcpu->arch.exception.has_error_code = has_error;
873 		vcpu->arch.exception.vector = nr;
874 		vcpu->arch.exception.error_code = error_code;
875 		vcpu->arch.exception.has_payload = has_payload;
876 		vcpu->arch.exception.payload = payload;
877 		if (!is_guest_mode(vcpu))
878 			kvm_deliver_exception_payload(vcpu,
879 						      &vcpu->arch.exception);
880 		return;
881 	}
882 
883 	/* to check exception */
884 	prev_nr = vcpu->arch.exception.vector;
885 	if (prev_nr == DF_VECTOR) {
886 		/* triple fault -> shutdown */
887 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
888 		return;
889 	}
890 	class1 = exception_class(prev_nr);
891 	class2 = exception_class(nr);
892 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
893 	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
894 		/*
895 		 * Synthesize #DF.  Clear the previously injected or pending
896 		 * exception so as not to incorrectly trigger shutdown.
897 		 */
898 		vcpu->arch.exception.injected = false;
899 		vcpu->arch.exception.pending = false;
900 
901 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
902 	} else {
903 		/* replace previous exception with a new one in a hope
904 		   that instruction re-execution will regenerate lost
905 		   exception */
906 		goto queue;
907 	}
908 }
909 
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)910 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
911 {
912 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
913 }
914 EXPORT_SYMBOL_GPL(kvm_queue_exception);
915 
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned nr)916 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
917 {
918 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
919 }
920 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
921 
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)922 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
923 			   unsigned long payload)
924 {
925 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
926 }
927 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
928 
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)929 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
930 				    u32 error_code, unsigned long payload)
931 {
932 	kvm_multiple_exception(vcpu, nr, true, error_code,
933 			       true, payload, false);
934 }
935 
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)936 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
937 {
938 	if (err)
939 		kvm_inject_gp(vcpu, 0);
940 	else
941 		return kvm_skip_emulated_instruction(vcpu);
942 
943 	return 1;
944 }
945 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
946 
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)947 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
948 {
949 	if (err) {
950 		kvm_inject_gp(vcpu, 0);
951 		return 1;
952 	}
953 
954 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
955 				       EMULTYPE_COMPLETE_USER_EXIT);
956 }
957 
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)958 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
959 {
960 	++vcpu->stat.pf_guest;
961 
962 	/*
963 	 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
964 	 * whether or not L1 wants to intercept "regular" #PF.
965 	 */
966 	if (is_guest_mode(vcpu) && fault->async_page_fault)
967 		kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
968 					   true, fault->error_code,
969 					   true, fault->address);
970 	else
971 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
972 					fault->address);
973 }
974 
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)975 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
976 				    struct x86_exception *fault)
977 {
978 	struct kvm_mmu *fault_mmu;
979 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
980 
981 	fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
982 					       vcpu->arch.walk_mmu;
983 
984 	/*
985 	 * Invalidate the TLB entry for the faulting address, if it exists,
986 	 * else the access will fault indefinitely (and to emulate hardware).
987 	 */
988 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
989 	    !(fault->error_code & PFERR_RSVD_MASK))
990 		kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
991 					KVM_MMU_ROOT_CURRENT);
992 
993 	fault_mmu->inject_page_fault(vcpu, fault);
994 }
995 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
996 
kvm_inject_nmi(struct kvm_vcpu * vcpu)997 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
998 {
999 	atomic_inc(&vcpu->arch.nmi_queued);
1000 	kvm_make_request(KVM_REQ_NMI, vcpu);
1001 }
1002 
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1003 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1004 {
1005 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
1006 }
1007 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
1008 
kvm_requeue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1009 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1010 {
1011 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
1012 }
1013 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
1014 
1015 /*
1016  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
1017  * a #GP and return false.
1018  */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1019 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1020 {
1021 	if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1022 		return true;
1023 	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1024 	return false;
1025 }
1026 
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1027 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1028 {
1029 	if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1030 		return true;
1031 
1032 	kvm_queue_exception(vcpu, UD_VECTOR);
1033 	return false;
1034 }
1035 EXPORT_SYMBOL_GPL(kvm_require_dr);
1036 
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1037 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1038 {
1039 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1040 }
1041 
1042 /*
1043  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
1044  */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1045 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1046 {
1047 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1048 	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1049 	gpa_t real_gpa;
1050 	int i;
1051 	int ret;
1052 	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1053 
1054 	/*
1055 	 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1056 	 * to an L1 GPA.
1057 	 */
1058 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1059 				     PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1060 	if (real_gpa == INVALID_GPA)
1061 		return 0;
1062 
1063 	/* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1064 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1065 				       cr3 & GENMASK(11, 5), sizeof(pdpte));
1066 	if (ret < 0)
1067 		return 0;
1068 
1069 	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1070 		if ((pdpte[i] & PT_PRESENT_MASK) &&
1071 		    (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1072 			return 0;
1073 		}
1074 	}
1075 
1076 	/*
1077 	 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1078 	 * Shadow page roots need to be reconstructed instead.
1079 	 */
1080 	if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1081 		kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1082 
1083 	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1084 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1085 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1086 	vcpu->arch.pdptrs_from_userspace = false;
1087 
1088 	return 1;
1089 }
1090 EXPORT_SYMBOL_GPL(load_pdptrs);
1091 
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1092 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1093 {
1094 #ifdef CONFIG_X86_64
1095 	if (cr0 & 0xffffffff00000000UL)
1096 		return false;
1097 #endif
1098 
1099 	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1100 		return false;
1101 
1102 	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1103 		return false;
1104 
1105 	return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1106 }
1107 
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1108 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1109 {
1110 	/*
1111 	 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1112 	 * indirect shadow MMUs.  If paging is disabled, no updates are needed
1113 	 * as there are no permission bits to emulate.  If TDP is enabled, the
1114 	 * MMU's metadata needs to be updated, e.g. so that emulating guest
1115 	 * translations does the right thing, but there's no need to unload the
1116 	 * root as CR0.WP doesn't affect SPTEs.
1117 	 */
1118 	if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1119 		if (!(cr0 & X86_CR0_PG))
1120 			return;
1121 
1122 		if (tdp_enabled) {
1123 			kvm_init_mmu(vcpu);
1124 			return;
1125 		}
1126 	}
1127 
1128 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1129 		kvm_clear_async_pf_completion_queue(vcpu);
1130 		kvm_async_pf_hash_reset(vcpu);
1131 
1132 		/*
1133 		 * Clearing CR0.PG is defined to flush the TLB from the guest's
1134 		 * perspective.
1135 		 */
1136 		if (!(cr0 & X86_CR0_PG))
1137 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1138 	}
1139 
1140 	if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1141 		kvm_mmu_reset_context(vcpu);
1142 }
1143 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
1144 
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1145 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1146 {
1147 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
1148 
1149 	if (!kvm_is_valid_cr0(vcpu, cr0))
1150 		return 1;
1151 
1152 	cr0 |= X86_CR0_ET;
1153 
1154 	/* Write to CR0 reserved bits are ignored, even on Intel. */
1155 	cr0 &= ~CR0_RESERVED_BITS;
1156 
1157 #ifdef CONFIG_X86_64
1158 	if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1159 	    (cr0 & X86_CR0_PG)) {
1160 		int cs_db, cs_l;
1161 
1162 		if (!is_pae(vcpu))
1163 			return 1;
1164 		kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1165 		if (cs_l)
1166 			return 1;
1167 	}
1168 #endif
1169 	if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1170 	    is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1171 	    !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1172 		return 1;
1173 
1174 	if (!(cr0 & X86_CR0_PG) &&
1175 	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1176 		return 1;
1177 
1178 	kvm_x86_call(set_cr0)(vcpu, cr0);
1179 
1180 	kvm_post_set_cr0(vcpu, old_cr0, cr0);
1181 
1182 	return 0;
1183 }
1184 EXPORT_SYMBOL_GPL(kvm_set_cr0);
1185 
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1186 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1187 {
1188 	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1189 }
1190 EXPORT_SYMBOL_GPL(kvm_lmsw);
1191 
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)1192 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1193 {
1194 	if (vcpu->arch.guest_state_protected)
1195 		return;
1196 
1197 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1198 
1199 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1200 			xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1201 
1202 		if (guest_can_use(vcpu, X86_FEATURE_XSAVES) &&
1203 		    vcpu->arch.ia32_xss != kvm_host.xss)
1204 			wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1205 	}
1206 
1207 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1208 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
1209 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1210 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1211 		write_pkru(vcpu->arch.pkru);
1212 }
1213 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
1214 
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1215 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1216 {
1217 	if (vcpu->arch.guest_state_protected)
1218 		return;
1219 
1220 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1221 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1222 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1223 		vcpu->arch.pkru = rdpkru();
1224 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1225 			write_pkru(vcpu->arch.host_pkru);
1226 	}
1227 
1228 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1229 
1230 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1231 			xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1232 
1233 		if (guest_can_use(vcpu, X86_FEATURE_XSAVES) &&
1234 		    vcpu->arch.ia32_xss != kvm_host.xss)
1235 			wrmsrl(MSR_IA32_XSS, kvm_host.xss);
1236 	}
1237 
1238 }
1239 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1240 
1241 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1242 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1243 {
1244 	return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1245 }
1246 #endif
1247 
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1248 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1249 {
1250 	u64 xcr0 = xcr;
1251 	u64 old_xcr0 = vcpu->arch.xcr0;
1252 	u64 valid_bits;
1253 
1254 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
1255 	if (index != XCR_XFEATURE_ENABLED_MASK)
1256 		return 1;
1257 	if (!(xcr0 & XFEATURE_MASK_FP))
1258 		return 1;
1259 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1260 		return 1;
1261 
1262 	/*
1263 	 * Do not allow the guest to set bits that we do not support
1264 	 * saving.  However, xcr0 bit 0 is always set, even if the
1265 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1266 	 */
1267 	valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1268 	if (xcr0 & ~valid_bits)
1269 		return 1;
1270 
1271 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1272 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1273 		return 1;
1274 
1275 	if (xcr0 & XFEATURE_MASK_AVX512) {
1276 		if (!(xcr0 & XFEATURE_MASK_YMM))
1277 			return 1;
1278 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1279 			return 1;
1280 	}
1281 
1282 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
1283 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1284 		return 1;
1285 
1286 	vcpu->arch.xcr0 = xcr0;
1287 
1288 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1289 		kvm_update_cpuid_runtime(vcpu);
1290 	return 0;
1291 }
1292 
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1293 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1294 {
1295 	/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1296 	if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1297 	    __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1298 		kvm_inject_gp(vcpu, 0);
1299 		return 1;
1300 	}
1301 
1302 	return kvm_skip_emulated_instruction(vcpu);
1303 }
1304 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1305 
__kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1306 bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1307 {
1308 	if (cr4 & cr4_reserved_bits)
1309 		return false;
1310 
1311 	if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
1312 		return false;
1313 
1314 	return true;
1315 }
1316 EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
1317 
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1318 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1319 {
1320 	return __kvm_is_valid_cr4(vcpu, cr4) &&
1321 	       kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1322 }
1323 
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1324 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1325 {
1326 	if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1327 		kvm_mmu_reset_context(vcpu);
1328 
1329 	/*
1330 	 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1331 	 * according to the SDM; however, stale prev_roots could be reused
1332 	 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1333 	 * free them all.  This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1334 	 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1335 	 * so fall through.
1336 	 */
1337 	if (!tdp_enabled &&
1338 	    (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1339 		kvm_mmu_unload(vcpu);
1340 
1341 	/*
1342 	 * The TLB has to be flushed for all PCIDs if any of the following
1343 	 * (architecturally required) changes happen:
1344 	 * - CR4.PCIDE is changed from 1 to 0
1345 	 * - CR4.PGE is toggled
1346 	 *
1347 	 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1348 	 */
1349 	if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1350 	    (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1351 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1352 
1353 	/*
1354 	 * The TLB has to be flushed for the current PCID if any of the
1355 	 * following (architecturally required) changes happen:
1356 	 * - CR4.SMEP is changed from 0 to 1
1357 	 * - CR4.PAE is toggled
1358 	 */
1359 	else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1360 		 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1361 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1362 
1363 }
1364 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1365 
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1366 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1367 {
1368 	unsigned long old_cr4 = kvm_read_cr4(vcpu);
1369 
1370 	if (!kvm_is_valid_cr4(vcpu, cr4))
1371 		return 1;
1372 
1373 	if (is_long_mode(vcpu)) {
1374 		if (!(cr4 & X86_CR4_PAE))
1375 			return 1;
1376 		if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1377 			return 1;
1378 	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1379 		   && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1380 		   && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1381 		return 1;
1382 
1383 	if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1384 		/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1385 		if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1386 			return 1;
1387 	}
1388 
1389 	kvm_x86_call(set_cr4)(vcpu, cr4);
1390 
1391 	kvm_post_set_cr4(vcpu, old_cr4, cr4);
1392 
1393 	return 0;
1394 }
1395 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1396 
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1397 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1398 {
1399 	struct kvm_mmu *mmu = vcpu->arch.mmu;
1400 	unsigned long roots_to_free = 0;
1401 	int i;
1402 
1403 	/*
1404 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1405 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
1406 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
1407 	 * the invalidation, but the guest's TLB entries need to be flushed as
1408 	 * the CPU may have cached entries in its TLB for the target PCID.
1409 	 */
1410 	if (unlikely(tdp_enabled)) {
1411 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1412 		return;
1413 	}
1414 
1415 	/*
1416 	 * If neither the current CR3 nor any of the prev_roots use the given
1417 	 * PCID, then nothing needs to be done here because a resync will
1418 	 * happen anyway before switching to any other CR3.
1419 	 */
1420 	if (kvm_get_active_pcid(vcpu) == pcid) {
1421 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1422 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1423 	}
1424 
1425 	/*
1426 	 * If PCID is disabled, there is no need to free prev_roots even if the
1427 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1428 	 * with PCIDE=0.
1429 	 */
1430 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1431 		return;
1432 
1433 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1434 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1435 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1436 
1437 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1438 }
1439 
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1440 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1441 {
1442 	bool skip_tlb_flush = false;
1443 	unsigned long pcid = 0;
1444 #ifdef CONFIG_X86_64
1445 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1446 		skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1447 		cr3 &= ~X86_CR3_PCID_NOFLUSH;
1448 		pcid = cr3 & X86_CR3_PCID_MASK;
1449 	}
1450 #endif
1451 
1452 	/* PDPTRs are always reloaded for PAE paging. */
1453 	if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1454 		goto handle_tlb_flush;
1455 
1456 	/*
1457 	 * Do not condition the GPA check on long mode, this helper is used to
1458 	 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1459 	 * the current vCPU mode is accurate.
1460 	 */
1461 	if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1462 		return 1;
1463 
1464 	if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1465 		return 1;
1466 
1467 	if (cr3 != kvm_read_cr3(vcpu))
1468 		kvm_mmu_new_pgd(vcpu, cr3);
1469 
1470 	vcpu->arch.cr3 = cr3;
1471 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1472 	/* Do not call post_set_cr3, we do not get here for confidential guests.  */
1473 
1474 handle_tlb_flush:
1475 	/*
1476 	 * A load of CR3 that flushes the TLB flushes only the current PCID,
1477 	 * even if PCID is disabled, in which case PCID=0 is flushed.  It's a
1478 	 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1479 	 * and it's impossible to use a non-zero PCID when PCID is disabled,
1480 	 * i.e. only PCID=0 can be relevant.
1481 	 */
1482 	if (!skip_tlb_flush)
1483 		kvm_invalidate_pcid(vcpu, pcid);
1484 
1485 	return 0;
1486 }
1487 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1488 
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1489 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1490 {
1491 	if (cr8 & CR8_RESERVED_BITS)
1492 		return 1;
1493 	if (lapic_in_kernel(vcpu))
1494 		kvm_lapic_set_tpr(vcpu, cr8);
1495 	else
1496 		vcpu->arch.cr8 = cr8;
1497 	return 0;
1498 }
1499 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1500 
kvm_get_cr8(struct kvm_vcpu * vcpu)1501 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1502 {
1503 	if (lapic_in_kernel(vcpu))
1504 		return kvm_lapic_get_cr8(vcpu);
1505 	else
1506 		return vcpu->arch.cr8;
1507 }
1508 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1509 
kvm_update_dr0123(struct kvm_vcpu * vcpu)1510 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1511 {
1512 	int i;
1513 
1514 	if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1515 		for (i = 0; i < KVM_NR_DB_REGS; i++)
1516 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1517 	}
1518 }
1519 
kvm_update_dr7(struct kvm_vcpu * vcpu)1520 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1521 {
1522 	unsigned long dr7;
1523 
1524 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1525 		dr7 = vcpu->arch.guest_debug_dr7;
1526 	else
1527 		dr7 = vcpu->arch.dr7;
1528 	kvm_x86_call(set_dr7)(vcpu, dr7);
1529 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1530 	if (dr7 & DR7_BP_EN_MASK)
1531 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1532 }
1533 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1534 
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1535 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1536 {
1537 	u64 fixed = DR6_FIXED_1;
1538 
1539 	if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1540 		fixed |= DR6_RTM;
1541 
1542 	if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1543 		fixed |= DR6_BUS_LOCK;
1544 	return fixed;
1545 }
1546 
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1547 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1548 {
1549 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1550 
1551 	switch (dr) {
1552 	case 0 ... 3:
1553 		vcpu->arch.db[array_index_nospec(dr, size)] = val;
1554 		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1555 			vcpu->arch.eff_db[dr] = val;
1556 		break;
1557 	case 4:
1558 	case 6:
1559 		if (!kvm_dr6_valid(val))
1560 			return 1; /* #GP */
1561 		vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1562 		break;
1563 	case 5:
1564 	default: /* 7 */
1565 		if (!kvm_dr7_valid(val))
1566 			return 1; /* #GP */
1567 		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1568 		kvm_update_dr7(vcpu);
1569 		break;
1570 	}
1571 
1572 	return 0;
1573 }
1574 EXPORT_SYMBOL_GPL(kvm_set_dr);
1575 
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1576 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1577 {
1578 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1579 
1580 	switch (dr) {
1581 	case 0 ... 3:
1582 		return vcpu->arch.db[array_index_nospec(dr, size)];
1583 	case 4:
1584 	case 6:
1585 		return vcpu->arch.dr6;
1586 	case 5:
1587 	default: /* 7 */
1588 		return vcpu->arch.dr7;
1589 	}
1590 }
1591 EXPORT_SYMBOL_GPL(kvm_get_dr);
1592 
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1593 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1594 {
1595 	u32 ecx = kvm_rcx_read(vcpu);
1596 	u64 data;
1597 
1598 	if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1599 		kvm_inject_gp(vcpu, 0);
1600 		return 1;
1601 	}
1602 
1603 	kvm_rax_write(vcpu, (u32)data);
1604 	kvm_rdx_write(vcpu, data >> 32);
1605 	return kvm_skip_emulated_instruction(vcpu);
1606 }
1607 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1608 
1609 /*
1610  * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1611  * does not yet virtualize. These include:
1612  *   10 - MISC_PACKAGE_CTRLS
1613  *   11 - ENERGY_FILTERING_CTL
1614  *   12 - DOITM
1615  *   18 - FB_CLEAR_CTRL
1616  *   21 - XAPIC_DISABLE_STATUS
1617  *   23 - OVERCLOCKING_STATUS
1618  */
1619 
1620 #define KVM_SUPPORTED_ARCH_CAP \
1621 	(ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1622 	 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1623 	 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1624 	 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1625 	 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1626 	 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1627 
kvm_get_arch_capabilities(void)1628 static u64 kvm_get_arch_capabilities(void)
1629 {
1630 	u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1631 
1632 	/*
1633 	 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1634 	 * the nested hypervisor runs with NX huge pages.  If it is not,
1635 	 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1636 	 * L1 guests, so it need not worry about its own (L2) guests.
1637 	 */
1638 	data |= ARCH_CAP_PSCHANGE_MC_NO;
1639 
1640 	/*
1641 	 * If we're doing cache flushes (either "always" or "cond")
1642 	 * we will do one whenever the guest does a vmlaunch/vmresume.
1643 	 * If an outer hypervisor is doing the cache flush for us
1644 	 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1645 	 * capability to the guest too, and if EPT is disabled we're not
1646 	 * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1647 	 * require a nested hypervisor to do a flush of its own.
1648 	 */
1649 	if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1650 		data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1651 
1652 	if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1653 		data |= ARCH_CAP_RDCL_NO;
1654 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1655 		data |= ARCH_CAP_SSB_NO;
1656 	if (!boot_cpu_has_bug(X86_BUG_MDS))
1657 		data |= ARCH_CAP_MDS_NO;
1658 	if (!boot_cpu_has_bug(X86_BUG_RFDS))
1659 		data |= ARCH_CAP_RFDS_NO;
1660 	if (!boot_cpu_has_bug(X86_BUG_ITS))
1661 		data |= ARCH_CAP_ITS_NO;
1662 
1663 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1664 		/*
1665 		 * If RTM=0 because the kernel has disabled TSX, the host might
1666 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1667 		 * and therefore knows that there cannot be TAA) but keep
1668 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1669 		 * and we want to allow migrating those guests to tsx=off hosts.
1670 		 */
1671 		data &= ~ARCH_CAP_TAA_NO;
1672 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1673 		data |= ARCH_CAP_TAA_NO;
1674 	} else {
1675 		/*
1676 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1677 		 * host so the guest can choose between disabling TSX or
1678 		 * using VERW to clear CPU buffers.
1679 		 */
1680 	}
1681 
1682 	if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1683 		data |= ARCH_CAP_GDS_NO;
1684 
1685 	return data;
1686 }
1687 
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1688 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1689 			       bool host_initiated)
1690 {
1691 	WARN_ON_ONCE(!host_initiated);
1692 
1693 	switch (index) {
1694 	case MSR_IA32_ARCH_CAPABILITIES:
1695 		*data = kvm_get_arch_capabilities();
1696 		break;
1697 	case MSR_IA32_PERF_CAPABILITIES:
1698 		*data = kvm_caps.supported_perf_cap;
1699 		break;
1700 	case MSR_IA32_UCODE_REV:
1701 		rdmsrl_safe(index, data);
1702 		break;
1703 	default:
1704 		return kvm_x86_call(get_feature_msr)(index, data);
1705 	}
1706 	return 0;
1707 }
1708 
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1709 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1710 {
1711 	return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1712 				 kvm_get_feature_msr);
1713 }
1714 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1715 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1716 {
1717 	if (efer & EFER_AUTOIBRS && !guest_cpuid_has(vcpu, X86_FEATURE_AUTOIBRS))
1718 		return false;
1719 
1720 	if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1721 		return false;
1722 
1723 	if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1724 		return false;
1725 
1726 	if (efer & (EFER_LME | EFER_LMA) &&
1727 	    !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1728 		return false;
1729 
1730 	if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1731 		return false;
1732 
1733 	return true;
1734 
1735 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1736 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1737 {
1738 	if (efer & efer_reserved_bits)
1739 		return false;
1740 
1741 	return __kvm_valid_efer(vcpu, efer);
1742 }
1743 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1744 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1745 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1746 {
1747 	u64 old_efer = vcpu->arch.efer;
1748 	u64 efer = msr_info->data;
1749 	int r;
1750 
1751 	if (efer & efer_reserved_bits)
1752 		return 1;
1753 
1754 	if (!msr_info->host_initiated) {
1755 		if (!__kvm_valid_efer(vcpu, efer))
1756 			return 1;
1757 
1758 		if (is_paging(vcpu) &&
1759 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1760 			return 1;
1761 	}
1762 
1763 	efer &= ~EFER_LMA;
1764 	efer |= vcpu->arch.efer & EFER_LMA;
1765 
1766 	r = kvm_x86_call(set_efer)(vcpu, efer);
1767 	if (r) {
1768 		WARN_ON(r > 0);
1769 		return r;
1770 	}
1771 
1772 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1773 		kvm_mmu_reset_context(vcpu);
1774 
1775 	if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1776 	    (efer & EFER_SVME))
1777 		kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1778 
1779 	return 0;
1780 }
1781 
kvm_enable_efer_bits(u64 mask)1782 void kvm_enable_efer_bits(u64 mask)
1783 {
1784        efer_reserved_bits &= ~mask;
1785 }
1786 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1787 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1788 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1789 {
1790 	struct kvm_x86_msr_filter *msr_filter;
1791 	struct msr_bitmap_range *ranges;
1792 	struct kvm *kvm = vcpu->kvm;
1793 	bool allowed;
1794 	int idx;
1795 	u32 i;
1796 
1797 	/* x2APIC MSRs do not support filtering. */
1798 	if (index >= 0x800 && index <= 0x8ff)
1799 		return true;
1800 
1801 	idx = srcu_read_lock(&kvm->srcu);
1802 
1803 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1804 	if (!msr_filter) {
1805 		allowed = true;
1806 		goto out;
1807 	}
1808 
1809 	allowed = msr_filter->default_allow;
1810 	ranges = msr_filter->ranges;
1811 
1812 	for (i = 0; i < msr_filter->count; i++) {
1813 		u32 start = ranges[i].base;
1814 		u32 end = start + ranges[i].nmsrs;
1815 		u32 flags = ranges[i].flags;
1816 		unsigned long *bitmap = ranges[i].bitmap;
1817 
1818 		if ((index >= start) && (index < end) && (flags & type)) {
1819 			allowed = test_bit(index - start, bitmap);
1820 			break;
1821 		}
1822 	}
1823 
1824 out:
1825 	srcu_read_unlock(&kvm->srcu, idx);
1826 
1827 	return allowed;
1828 }
1829 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1830 
1831 /*
1832  * Write @data into the MSR specified by @index.  Select MSR specific fault
1833  * checks are bypassed if @host_initiated is %true.
1834  * Returns 0 on success, non-0 otherwise.
1835  * Assumes vcpu_load() was already called.
1836  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1837 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1838 			 bool host_initiated)
1839 {
1840 	struct msr_data msr;
1841 
1842 	switch (index) {
1843 	case MSR_FS_BASE:
1844 	case MSR_GS_BASE:
1845 	case MSR_KERNEL_GS_BASE:
1846 	case MSR_CSTAR:
1847 	case MSR_LSTAR:
1848 		if (is_noncanonical_msr_address(data, vcpu))
1849 			return 1;
1850 		break;
1851 	case MSR_IA32_SYSENTER_EIP:
1852 	case MSR_IA32_SYSENTER_ESP:
1853 		/*
1854 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1855 		 * non-canonical address is written on Intel but not on
1856 		 * AMD (which ignores the top 32-bits, because it does
1857 		 * not implement 64-bit SYSENTER).
1858 		 *
1859 		 * 64-bit code should hence be able to write a non-canonical
1860 		 * value on AMD.  Making the address canonical ensures that
1861 		 * vmentry does not fail on Intel after writing a non-canonical
1862 		 * value, and that something deterministic happens if the guest
1863 		 * invokes 64-bit SYSENTER.
1864 		 */
1865 		data = __canonical_address(data, max_host_virt_addr_bits());
1866 		break;
1867 	case MSR_TSC_AUX:
1868 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1869 			return 1;
1870 
1871 		if (!host_initiated &&
1872 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1873 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1874 			return 1;
1875 
1876 		/*
1877 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1878 		 * incomplete and conflicting architectural behavior.  Current
1879 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1880 		 * reserved and always read as zeros.  Enforce Intel's reserved
1881 		 * bits check if the guest CPU is Intel compatible, otherwise
1882 		 * clear the bits.  This ensures cross-vendor migration will
1883 		 * provide consistent behavior for the guest.
1884 		 */
1885 		if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1886 			return 1;
1887 
1888 		data = (u32)data;
1889 		break;
1890 	}
1891 
1892 	msr.data = data;
1893 	msr.index = index;
1894 	msr.host_initiated = host_initiated;
1895 
1896 	return kvm_x86_call(set_msr)(vcpu, &msr);
1897 }
1898 
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1899 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1900 			bool host_initiated)
1901 {
1902 	return __kvm_set_msr(vcpu, index, *data, host_initiated);
1903 }
1904 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1905 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1906 				     u32 index, u64 data, bool host_initiated)
1907 {
1908 	return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1909 				 _kvm_set_msr);
1910 }
1911 
1912 /*
1913  * Read the MSR specified by @index into @data.  Select MSR specific fault
1914  * checks are bypassed if @host_initiated is %true.
1915  * Returns 0 on success, non-0 otherwise.
1916  * Assumes vcpu_load() was already called.
1917  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1918 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1919 		  bool host_initiated)
1920 {
1921 	struct msr_data msr;
1922 	int ret;
1923 
1924 	switch (index) {
1925 	case MSR_TSC_AUX:
1926 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1927 			return 1;
1928 
1929 		if (!host_initiated &&
1930 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1931 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1932 			return 1;
1933 		break;
1934 	}
1935 
1936 	msr.index = index;
1937 	msr.host_initiated = host_initiated;
1938 
1939 	ret = kvm_x86_call(get_msr)(vcpu, &msr);
1940 	if (!ret)
1941 		*data = msr.data;
1942 	return ret;
1943 }
1944 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1945 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1946 				     u32 index, u64 *data, bool host_initiated)
1947 {
1948 	return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
1949 				 __kvm_get_msr);
1950 }
1951 
kvm_get_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 * data)1952 int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1953 {
1954 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1955 		return KVM_MSR_RET_FILTERED;
1956 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1957 }
1958 EXPORT_SYMBOL_GPL(kvm_get_msr_with_filter);
1959 
kvm_set_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 data)1960 int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1961 {
1962 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1963 		return KVM_MSR_RET_FILTERED;
1964 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1965 }
1966 EXPORT_SYMBOL_GPL(kvm_set_msr_with_filter);
1967 
kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data)1968 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1969 {
1970 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
1971 }
1972 EXPORT_SYMBOL_GPL(kvm_get_msr);
1973 
kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data)1974 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1975 {
1976 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
1977 }
1978 EXPORT_SYMBOL_GPL(kvm_set_msr);
1979 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)1980 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1981 {
1982 	if (!vcpu->run->msr.error) {
1983 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1984 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1985 	}
1986 }
1987 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)1988 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1989 {
1990 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1991 }
1992 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)1993 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1994 {
1995 	complete_userspace_rdmsr(vcpu);
1996 	return complete_emulated_msr_access(vcpu);
1997 }
1998 
complete_fast_msr_access(struct kvm_vcpu * vcpu)1999 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2000 {
2001 	return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2002 }
2003 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2004 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2005 {
2006 	complete_userspace_rdmsr(vcpu);
2007 	return complete_fast_msr_access(vcpu);
2008 }
2009 
kvm_msr_reason(int r)2010 static u64 kvm_msr_reason(int r)
2011 {
2012 	switch (r) {
2013 	case KVM_MSR_RET_UNSUPPORTED:
2014 		return KVM_MSR_EXIT_REASON_UNKNOWN;
2015 	case KVM_MSR_RET_FILTERED:
2016 		return KVM_MSR_EXIT_REASON_FILTER;
2017 	default:
2018 		return KVM_MSR_EXIT_REASON_INVAL;
2019 	}
2020 }
2021 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2022 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2023 			      u32 exit_reason, u64 data,
2024 			      int (*completion)(struct kvm_vcpu *vcpu),
2025 			      int r)
2026 {
2027 	u64 msr_reason = kvm_msr_reason(r);
2028 
2029 	/* Check if the user wanted to know about this MSR fault */
2030 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2031 		return 0;
2032 
2033 	vcpu->run->exit_reason = exit_reason;
2034 	vcpu->run->msr.error = 0;
2035 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2036 	vcpu->run->msr.reason = msr_reason;
2037 	vcpu->run->msr.index = index;
2038 	vcpu->run->msr.data = data;
2039 	vcpu->arch.complete_userspace_io = completion;
2040 
2041 	return 1;
2042 }
2043 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2044 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2045 {
2046 	u32 ecx = kvm_rcx_read(vcpu);
2047 	u64 data;
2048 	int r;
2049 
2050 	r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2051 
2052 	if (!r) {
2053 		trace_kvm_msr_read(ecx, data);
2054 
2055 		kvm_rax_write(vcpu, data & -1u);
2056 		kvm_rdx_write(vcpu, (data >> 32) & -1u);
2057 	} else {
2058 		/* MSR read failed? See if we should ask user space */
2059 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2060 				       complete_fast_rdmsr, r))
2061 			return 0;
2062 		trace_kvm_msr_read_ex(ecx);
2063 	}
2064 
2065 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2066 }
2067 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2068 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2069 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2070 {
2071 	u32 ecx = kvm_rcx_read(vcpu);
2072 	u64 data = kvm_read_edx_eax(vcpu);
2073 	int r;
2074 
2075 	r = kvm_set_msr_with_filter(vcpu, ecx, data);
2076 
2077 	if (!r) {
2078 		trace_kvm_msr_write(ecx, data);
2079 	} else {
2080 		/* MSR write failed? See if we should ask user space */
2081 		if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2082 				       complete_fast_msr_access, r))
2083 			return 0;
2084 		/* Signal all other negative errors to userspace */
2085 		if (r < 0)
2086 			return r;
2087 		trace_kvm_msr_write_ex(ecx, data);
2088 	}
2089 
2090 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2091 }
2092 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2093 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2094 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2095 {
2096 	return kvm_skip_emulated_instruction(vcpu);
2097 }
2098 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2099 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2100 {
2101 	/* Treat an INVD instruction as a NOP and just skip it. */
2102 	return kvm_emulate_as_nop(vcpu);
2103 }
2104 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2105 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2106 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2107 {
2108 	kvm_queue_exception(vcpu, UD_VECTOR);
2109 	return 1;
2110 }
2111 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2112 
2113 
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2114 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2115 {
2116 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS) &&
2117 	    !guest_cpuid_has(vcpu, X86_FEATURE_MWAIT))
2118 		return kvm_handle_invalid_op(vcpu);
2119 
2120 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
2121 	return kvm_emulate_as_nop(vcpu);
2122 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2123 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2124 {
2125 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2126 }
2127 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2128 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2129 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2130 {
2131 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2132 }
2133 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2134 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2135 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2136 {
2137 	xfer_to_guest_mode_prepare();
2138 	return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
2139 		xfer_to_guest_mode_work_pending();
2140 }
2141 
2142 /*
2143  * The fast path for frequent and performance sensitive wrmsr emulation,
2144  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2145  * the latency of virtual IPI by avoiding the expensive bits of transitioning
2146  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2147  * other cases which must be called after interrupts are enabled on the host.
2148  */
handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu * vcpu,u64 data)2149 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2150 {
2151 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2152 		return 1;
2153 
2154 	if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2155 	    ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2156 	    ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2157 	    ((u32)(data >> 32) != X2APIC_BROADCAST))
2158 		return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2159 
2160 	return 1;
2161 }
2162 
handle_fastpath_set_tscdeadline(struct kvm_vcpu * vcpu,u64 data)2163 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2164 {
2165 	if (!kvm_can_use_hv_timer(vcpu))
2166 		return 1;
2167 
2168 	kvm_set_lapic_tscdeadline_msr(vcpu, data);
2169 	return 0;
2170 }
2171 
handle_fastpath_set_msr_irqoff(struct kvm_vcpu * vcpu)2172 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2173 {
2174 	u32 msr = kvm_rcx_read(vcpu);
2175 	u64 data;
2176 	fastpath_t ret;
2177 	bool handled;
2178 
2179 	kvm_vcpu_srcu_read_lock(vcpu);
2180 
2181 	switch (msr) {
2182 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2183 		data = kvm_read_edx_eax(vcpu);
2184 		handled = !handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
2185 		break;
2186 	case MSR_IA32_TSC_DEADLINE:
2187 		data = kvm_read_edx_eax(vcpu);
2188 		handled = !handle_fastpath_set_tscdeadline(vcpu, data);
2189 		break;
2190 	default:
2191 		handled = false;
2192 		break;
2193 	}
2194 
2195 	if (handled) {
2196 		if (!kvm_skip_emulated_instruction(vcpu))
2197 			ret = EXIT_FASTPATH_EXIT_USERSPACE;
2198 		else
2199 			ret = EXIT_FASTPATH_REENTER_GUEST;
2200 		trace_kvm_msr_write(msr, data);
2201 	} else {
2202 		ret = EXIT_FASTPATH_NONE;
2203 	}
2204 
2205 	kvm_vcpu_srcu_read_unlock(vcpu);
2206 
2207 	return ret;
2208 }
2209 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2210 
2211 /*
2212  * Adapt set_msr() to msr_io()'s calling convention
2213  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2214 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2215 {
2216 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2217 }
2218 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2219 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2220 {
2221 	u64 val;
2222 
2223 	/*
2224 	 * Disallow writes to immutable feature MSRs after KVM_RUN.  KVM does
2225 	 * not support modifying the guest vCPU model on the fly, e.g. changing
2226 	 * the nVMX capabilities while L2 is running is nonsensical.  Allow
2227 	 * writes of the same value, e.g. to allow userspace to blindly stuff
2228 	 * all MSRs when emulating RESET.
2229 	 */
2230 	if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2231 	    (do_get_msr(vcpu, index, &val) || *data != val))
2232 		return -EINVAL;
2233 
2234 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2235 }
2236 
2237 #ifdef CONFIG_X86_64
2238 struct pvclock_clock {
2239 	int vclock_mode;
2240 	u64 cycle_last;
2241 	u64 mask;
2242 	u32 mult;
2243 	u32 shift;
2244 	u64 base_cycles;
2245 	u64 offset;
2246 };
2247 
2248 struct pvclock_gtod_data {
2249 	seqcount_t	seq;
2250 
2251 	struct pvclock_clock clock; /* extract of a clocksource struct */
2252 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2253 
2254 	ktime_t		offs_boot;
2255 	u64		wall_time_sec;
2256 };
2257 
2258 static struct pvclock_gtod_data pvclock_gtod_data;
2259 
update_pvclock_gtod(struct timekeeper * tk)2260 static void update_pvclock_gtod(struct timekeeper *tk)
2261 {
2262 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2263 
2264 	write_seqcount_begin(&vdata->seq);
2265 
2266 	/* copy pvclock gtod data */
2267 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2268 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2269 	vdata->clock.mask		= tk->tkr_mono.mask;
2270 	vdata->clock.mult		= tk->tkr_mono.mult;
2271 	vdata->clock.shift		= tk->tkr_mono.shift;
2272 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2273 	vdata->clock.offset		= tk->tkr_mono.base;
2274 
2275 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2276 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2277 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2278 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2279 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2280 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2281 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2282 
2283 	vdata->wall_time_sec            = tk->xtime_sec;
2284 
2285 	vdata->offs_boot		= tk->offs_boot;
2286 
2287 	write_seqcount_end(&vdata->seq);
2288 }
2289 
get_kvmclock_base_ns(void)2290 static s64 get_kvmclock_base_ns(void)
2291 {
2292 	/* Count up from boot time, but with the frequency of the raw clock.  */
2293 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2294 }
2295 #else
get_kvmclock_base_ns(void)2296 static s64 get_kvmclock_base_ns(void)
2297 {
2298 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2299 	return ktime_get_boottime_ns();
2300 }
2301 #endif
2302 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2303 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2304 {
2305 	int version;
2306 	int r;
2307 	struct pvclock_wall_clock wc;
2308 	u32 wc_sec_hi;
2309 	u64 wall_nsec;
2310 
2311 	if (!wall_clock)
2312 		return;
2313 
2314 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2315 	if (r)
2316 		return;
2317 
2318 	if (version & 1)
2319 		++version;  /* first time write, random junk */
2320 
2321 	++version;
2322 
2323 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2324 		return;
2325 
2326 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
2327 
2328 	wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2329 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2330 	wc.version = version;
2331 
2332 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2333 
2334 	if (sec_hi_ofs) {
2335 		wc_sec_hi = wall_nsec >> 32;
2336 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2337 				&wc_sec_hi, sizeof(wc_sec_hi));
2338 	}
2339 
2340 	version++;
2341 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2342 }
2343 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2344 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2345 				  bool old_msr, bool host_initiated)
2346 {
2347 	struct kvm_arch *ka = &vcpu->kvm->arch;
2348 
2349 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2350 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2351 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2352 
2353 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2354 	}
2355 
2356 	vcpu->arch.time = system_time;
2357 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2358 
2359 	/* we verify if the enable bit is set... */
2360 	if (system_time & 1)
2361 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2362 				 sizeof(struct pvclock_vcpu_time_info));
2363 	else
2364 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
2365 
2366 	return;
2367 }
2368 
div_frac(uint32_t dividend,uint32_t divisor)2369 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2370 {
2371 	do_shl32_div32(dividend, divisor);
2372 	return dividend;
2373 }
2374 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2375 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2376 			       s8 *pshift, u32 *pmultiplier)
2377 {
2378 	uint64_t scaled64;
2379 	int32_t  shift = 0;
2380 	uint64_t tps64;
2381 	uint32_t tps32;
2382 
2383 	tps64 = base_hz;
2384 	scaled64 = scaled_hz;
2385 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2386 		tps64 >>= 1;
2387 		shift--;
2388 	}
2389 
2390 	tps32 = (uint32_t)tps64;
2391 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2392 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2393 			scaled64 >>= 1;
2394 		else
2395 			tps32 <<= 1;
2396 		shift++;
2397 	}
2398 
2399 	*pshift = shift;
2400 	*pmultiplier = div_frac(scaled64, tps32);
2401 }
2402 
2403 #ifdef CONFIG_X86_64
2404 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2405 #endif
2406 
2407 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2408 static unsigned long max_tsc_khz;
2409 
adjust_tsc_khz(u32 khz,s32 ppm)2410 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2411 {
2412 	u64 v = (u64)khz * (1000000 + ppm);
2413 	do_div(v, 1000000);
2414 	return v;
2415 }
2416 
2417 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2418 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2419 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2420 {
2421 	u64 ratio;
2422 
2423 	/* Guest TSC same frequency as host TSC? */
2424 	if (!scale) {
2425 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2426 		return 0;
2427 	}
2428 
2429 	/* TSC scaling supported? */
2430 	if (!kvm_caps.has_tsc_control) {
2431 		if (user_tsc_khz > tsc_khz) {
2432 			vcpu->arch.tsc_catchup = 1;
2433 			vcpu->arch.tsc_always_catchup = 1;
2434 			return 0;
2435 		} else {
2436 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2437 			return -1;
2438 		}
2439 	}
2440 
2441 	/* TSC scaling required  - calculate ratio */
2442 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2443 				user_tsc_khz, tsc_khz);
2444 
2445 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2446 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2447 			            user_tsc_khz);
2448 		return -1;
2449 	}
2450 
2451 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2452 	return 0;
2453 }
2454 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2455 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2456 {
2457 	u32 thresh_lo, thresh_hi;
2458 	int use_scaling = 0;
2459 
2460 	/* tsc_khz can be zero if TSC calibration fails */
2461 	if (user_tsc_khz == 0) {
2462 		/* set tsc_scaling_ratio to a safe value */
2463 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2464 		return -1;
2465 	}
2466 
2467 	/* Compute a scale to convert nanoseconds in TSC cycles */
2468 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2469 			   &vcpu->arch.virtual_tsc_shift,
2470 			   &vcpu->arch.virtual_tsc_mult);
2471 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2472 
2473 	/*
2474 	 * Compute the variation in TSC rate which is acceptable
2475 	 * within the range of tolerance and decide if the
2476 	 * rate being applied is within that bounds of the hardware
2477 	 * rate.  If so, no scaling or compensation need be done.
2478 	 */
2479 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2480 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2481 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2482 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2483 			 user_tsc_khz, thresh_lo, thresh_hi);
2484 		use_scaling = 1;
2485 	}
2486 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2487 }
2488 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2489 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2490 {
2491 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2492 				      vcpu->arch.virtual_tsc_mult,
2493 				      vcpu->arch.virtual_tsc_shift);
2494 	tsc += vcpu->arch.this_tsc_write;
2495 	return tsc;
2496 }
2497 
2498 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2499 static inline bool gtod_is_based_on_tsc(int mode)
2500 {
2501 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2502 }
2503 #endif
2504 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2505 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2506 {
2507 #ifdef CONFIG_X86_64
2508 	struct kvm_arch *ka = &vcpu->kvm->arch;
2509 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2510 
2511 	/*
2512 	 * To use the masterclock, the host clocksource must be based on TSC
2513 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
2514 	 * vCPUs doesn't include the reference vCPU, hence "+1".
2515 	 */
2516 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2517 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
2518 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2519 
2520 	/*
2521 	 * Request a masterclock update if the masterclock needs to be toggled
2522 	 * on/off, or when starting a new generation and the masterclock is
2523 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2524 	 * taken _after_ the new generation is created).
2525 	 */
2526 	if ((ka->use_master_clock && new_generation) ||
2527 	    (ka->use_master_clock != use_master_clock))
2528 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2529 
2530 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2531 			    atomic_read(&vcpu->kvm->online_vcpus),
2532 		            ka->use_master_clock, gtod->clock.vclock_mode);
2533 #endif
2534 }
2535 
2536 /*
2537  * Multiply tsc by a fixed point number represented by ratio.
2538  *
2539  * The most significant 64-N bits (mult) of ratio represent the
2540  * integral part of the fixed point number; the remaining N bits
2541  * (frac) represent the fractional part, ie. ratio represents a fixed
2542  * point number (mult + frac * 2^(-N)).
2543  *
2544  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2545  */
__scale_tsc(u64 ratio,u64 tsc)2546 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2547 {
2548 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2549 }
2550 
kvm_scale_tsc(u64 tsc,u64 ratio)2551 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2552 {
2553 	u64 _tsc = tsc;
2554 
2555 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
2556 		_tsc = __scale_tsc(ratio, tsc);
2557 
2558 	return _tsc;
2559 }
2560 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2561 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2562 {
2563 	u64 tsc;
2564 
2565 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2566 
2567 	return target_tsc - tsc;
2568 }
2569 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2570 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2571 {
2572 	return vcpu->arch.l1_tsc_offset +
2573 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2574 }
2575 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2576 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2577 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2578 {
2579 	u64 nested_offset;
2580 
2581 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2582 		nested_offset = l1_offset;
2583 	else
2584 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2585 						kvm_caps.tsc_scaling_ratio_frac_bits);
2586 
2587 	nested_offset += l2_offset;
2588 	return nested_offset;
2589 }
2590 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2591 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2592 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2593 {
2594 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2595 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2596 				       kvm_caps.tsc_scaling_ratio_frac_bits);
2597 
2598 	return l1_multiplier;
2599 }
2600 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2601 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2602 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2603 {
2604 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2605 				   vcpu->arch.l1_tsc_offset,
2606 				   l1_offset);
2607 
2608 	vcpu->arch.l1_tsc_offset = l1_offset;
2609 
2610 	/*
2611 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2612 	 * according to the spec this should set L1's TSC (as opposed to
2613 	 * setting L1's offset for L2).
2614 	 */
2615 	if (is_guest_mode(vcpu))
2616 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2617 			l1_offset,
2618 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
2619 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2620 	else
2621 		vcpu->arch.tsc_offset = l1_offset;
2622 
2623 	kvm_x86_call(write_tsc_offset)(vcpu);
2624 }
2625 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2626 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2627 {
2628 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2629 
2630 	/* Userspace is changing the multiplier while L2 is active */
2631 	if (is_guest_mode(vcpu))
2632 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2633 			l1_multiplier,
2634 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2635 	else
2636 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2637 
2638 	if (kvm_caps.has_tsc_control)
2639 		kvm_x86_call(write_tsc_multiplier)(vcpu);
2640 }
2641 
kvm_check_tsc_unstable(void)2642 static inline bool kvm_check_tsc_unstable(void)
2643 {
2644 #ifdef CONFIG_X86_64
2645 	/*
2646 	 * TSC is marked unstable when we're running on Hyper-V,
2647 	 * 'TSC page' clocksource is good.
2648 	 */
2649 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2650 		return false;
2651 #endif
2652 	return check_tsc_unstable();
2653 }
2654 
2655 /*
2656  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2657  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2658  * participates in.
2659  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched)2660 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2661 				  u64 ns, bool matched)
2662 {
2663 	struct kvm *kvm = vcpu->kvm;
2664 
2665 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2666 
2667 	/*
2668 	 * We also track th most recent recorded KHZ, write and time to
2669 	 * allow the matching interval to be extended at each write.
2670 	 */
2671 	kvm->arch.last_tsc_nsec = ns;
2672 	kvm->arch.last_tsc_write = tsc;
2673 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2674 	kvm->arch.last_tsc_offset = offset;
2675 
2676 	vcpu->arch.last_guest_tsc = tsc;
2677 
2678 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2679 
2680 	if (!matched) {
2681 		/*
2682 		 * We split periods of matched TSC writes into generations.
2683 		 * For each generation, we track the original measured
2684 		 * nanosecond time, offset, and write, so if TSCs are in
2685 		 * sync, we can match exact offset, and if not, we can match
2686 		 * exact software computation in compute_guest_tsc()
2687 		 *
2688 		 * These values are tracked in kvm->arch.cur_xxx variables.
2689 		 */
2690 		kvm->arch.cur_tsc_generation++;
2691 		kvm->arch.cur_tsc_nsec = ns;
2692 		kvm->arch.cur_tsc_write = tsc;
2693 		kvm->arch.cur_tsc_offset = offset;
2694 		kvm->arch.nr_vcpus_matched_tsc = 0;
2695 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2696 		kvm->arch.nr_vcpus_matched_tsc++;
2697 	}
2698 
2699 	/* Keep track of which generation this VCPU has synchronized to */
2700 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2701 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2702 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2703 
2704 	kvm_track_tsc_matching(vcpu, !matched);
2705 }
2706 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2707 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2708 {
2709 	u64 data = user_value ? *user_value : 0;
2710 	struct kvm *kvm = vcpu->kvm;
2711 	u64 offset, ns, elapsed;
2712 	unsigned long flags;
2713 	bool matched = false;
2714 	bool synchronizing = false;
2715 
2716 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2717 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2718 	ns = get_kvmclock_base_ns();
2719 	elapsed = ns - kvm->arch.last_tsc_nsec;
2720 
2721 	if (vcpu->arch.virtual_tsc_khz) {
2722 		if (data == 0) {
2723 			/*
2724 			 * Force synchronization when creating a vCPU, or when
2725 			 * userspace explicitly writes a zero value.
2726 			 */
2727 			synchronizing = true;
2728 		} else if (kvm->arch.user_set_tsc) {
2729 			u64 tsc_exp = kvm->arch.last_tsc_write +
2730 						nsec_to_cycles(vcpu, elapsed);
2731 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2732 			/*
2733 			 * Here lies UAPI baggage: when a user-initiated TSC write has
2734 			 * a small delta (1 second) of virtual cycle time against the
2735 			 * previously set vCPU, we assume that they were intended to be
2736 			 * in sync and the delta was only due to the racy nature of the
2737 			 * legacy API.
2738 			 *
2739 			 * This trick falls down when restoring a guest which genuinely
2740 			 * has been running for less time than the 1 second of imprecision
2741 			 * which we allow for in the legacy API. In this case, the first
2742 			 * value written by userspace (on any vCPU) should not be subject
2743 			 * to this 'correction' to make it sync up with values that only
2744 			 * come from the kernel's default vCPU creation. Make the 1-second
2745 			 * slop hack only trigger if the user_set_tsc flag is already set.
2746 			 */
2747 			synchronizing = data < tsc_exp + tsc_hz &&
2748 					data + tsc_hz > tsc_exp;
2749 		}
2750 	}
2751 
2752 	if (user_value)
2753 		kvm->arch.user_set_tsc = true;
2754 
2755 	/*
2756 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2757 	 * TSC, we add elapsed time in this computation.  We could let the
2758 	 * compensation code attempt to catch up if we fall behind, but
2759 	 * it's better to try to match offsets from the beginning.
2760          */
2761 	if (synchronizing &&
2762 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2763 		if (!kvm_check_tsc_unstable()) {
2764 			offset = kvm->arch.cur_tsc_offset;
2765 		} else {
2766 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2767 			data += delta;
2768 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2769 		}
2770 		matched = true;
2771 	}
2772 
2773 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
2774 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2775 }
2776 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2777 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2778 					   s64 adjustment)
2779 {
2780 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2781 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2782 }
2783 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2784 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2785 {
2786 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2787 		WARN_ON(adjustment < 0);
2788 	adjustment = kvm_scale_tsc((u64) adjustment,
2789 				   vcpu->arch.l1_tsc_scaling_ratio);
2790 	adjust_tsc_offset_guest(vcpu, adjustment);
2791 }
2792 
2793 #ifdef CONFIG_X86_64
2794 
read_tsc(void)2795 static u64 read_tsc(void)
2796 {
2797 	u64 ret = (u64)rdtsc_ordered();
2798 	u64 last = pvclock_gtod_data.clock.cycle_last;
2799 
2800 	if (likely(ret >= last))
2801 		return ret;
2802 
2803 	/*
2804 	 * GCC likes to generate cmov here, but this branch is extremely
2805 	 * predictable (it's just a function of time and the likely is
2806 	 * very likely) and there's a data dependence, so force GCC
2807 	 * to generate a branch instead.  I don't barrier() because
2808 	 * we don't actually need a barrier, and if this function
2809 	 * ever gets inlined it will generate worse code.
2810 	 */
2811 	asm volatile ("");
2812 	return last;
2813 }
2814 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2815 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2816 			  int *mode)
2817 {
2818 	u64 tsc_pg_val;
2819 	long v;
2820 
2821 	switch (clock->vclock_mode) {
2822 	case VDSO_CLOCKMODE_HVCLOCK:
2823 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2824 					 tsc_timestamp, &tsc_pg_val)) {
2825 			/* TSC page valid */
2826 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2827 			v = (tsc_pg_val - clock->cycle_last) &
2828 				clock->mask;
2829 		} else {
2830 			/* TSC page invalid */
2831 			*mode = VDSO_CLOCKMODE_NONE;
2832 		}
2833 		break;
2834 	case VDSO_CLOCKMODE_TSC:
2835 		*mode = VDSO_CLOCKMODE_TSC;
2836 		*tsc_timestamp = read_tsc();
2837 		v = (*tsc_timestamp - clock->cycle_last) &
2838 			clock->mask;
2839 		break;
2840 	default:
2841 		*mode = VDSO_CLOCKMODE_NONE;
2842 	}
2843 
2844 	if (*mode == VDSO_CLOCKMODE_NONE)
2845 		*tsc_timestamp = v = 0;
2846 
2847 	return v * clock->mult;
2848 }
2849 
2850 /*
2851  * As with get_kvmclock_base_ns(), this counts from boot time, at the
2852  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2853  */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2854 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2855 {
2856 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2857 	unsigned long seq;
2858 	int mode;
2859 	u64 ns;
2860 
2861 	do {
2862 		seq = read_seqcount_begin(&gtod->seq);
2863 		ns = gtod->raw_clock.base_cycles;
2864 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2865 		ns >>= gtod->raw_clock.shift;
2866 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2867 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2868 	*t = ns;
2869 
2870 	return mode;
2871 }
2872 
2873 /*
2874  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2875  * no boot time offset.
2876  */
do_monotonic(s64 * t,u64 * tsc_timestamp)2877 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2878 {
2879 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2880 	unsigned long seq;
2881 	int mode;
2882 	u64 ns;
2883 
2884 	do {
2885 		seq = read_seqcount_begin(&gtod->seq);
2886 		ns = gtod->clock.base_cycles;
2887 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2888 		ns >>= gtod->clock.shift;
2889 		ns += ktime_to_ns(gtod->clock.offset);
2890 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2891 	*t = ns;
2892 
2893 	return mode;
2894 }
2895 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2896 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2897 {
2898 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2899 	unsigned long seq;
2900 	int mode;
2901 	u64 ns;
2902 
2903 	do {
2904 		seq = read_seqcount_begin(&gtod->seq);
2905 		ts->tv_sec = gtod->wall_time_sec;
2906 		ns = gtod->clock.base_cycles;
2907 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2908 		ns >>= gtod->clock.shift;
2909 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2910 
2911 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2912 	ts->tv_nsec = ns;
2913 
2914 	return mode;
2915 }
2916 
2917 /*
2918  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2919  * reports the TSC value from which it do so. Returns true if host is
2920  * using TSC based clocksource.
2921  */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2922 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2923 {
2924 	/* checked again under seqlock below */
2925 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2926 		return false;
2927 
2928 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2929 						     tsc_timestamp));
2930 }
2931 
2932 /*
2933  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2934  * so. Returns true if host is using TSC based clocksource.
2935  */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2936 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, 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_monotonic(kernel_ns,
2943 						 tsc_timestamp));
2944 }
2945 
2946 /*
2947  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2948  * so. Returns true if host is using TSC based clocksource.
2949  *
2950  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2951  * for that.
2952  */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)2953 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2954 					   u64 *tsc_timestamp)
2955 {
2956 	/* checked again under seqlock below */
2957 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2958 		return false;
2959 
2960 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2961 }
2962 #endif
2963 
2964 /*
2965  *
2966  * Assuming a stable TSC across physical CPUS, and a stable TSC
2967  * across virtual CPUs, the following condition is possible.
2968  * Each numbered line represents an event visible to both
2969  * CPUs at the next numbered event.
2970  *
2971  * "timespecX" represents host monotonic time. "tscX" represents
2972  * RDTSC value.
2973  *
2974  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
2975  *
2976  * 1.  read timespec0,tsc0
2977  * 2.					| timespec1 = timespec0 + N
2978  * 					| tsc1 = tsc0 + M
2979  * 3. transition to guest		| transition to guest
2980  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2981  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
2982  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2983  *
2984  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2985  *
2986  * 	- ret0 < ret1
2987  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2988  *		...
2989  *	- 0 < N - M => M < N
2990  *
2991  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2992  * always the case (the difference between two distinct xtime instances
2993  * might be smaller then the difference between corresponding TSC reads,
2994  * when updating guest vcpus pvclock areas).
2995  *
2996  * To avoid that problem, do not allow visibility of distinct
2997  * system_timestamp/tsc_timestamp values simultaneously: use a master
2998  * copy of host monotonic time values. Update that master copy
2999  * in lockstep.
3000  *
3001  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3002  *
3003  */
3004 
pvclock_update_vm_gtod_copy(struct kvm * kvm)3005 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3006 {
3007 #ifdef CONFIG_X86_64
3008 	struct kvm_arch *ka = &kvm->arch;
3009 	int vclock_mode;
3010 	bool host_tsc_clocksource, vcpus_matched;
3011 
3012 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
3013 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3014 			atomic_read(&kvm->online_vcpus));
3015 
3016 	/*
3017 	 * If the host uses TSC clock, then passthrough TSC as stable
3018 	 * to the guest.
3019 	 */
3020 	host_tsc_clocksource = kvm_get_time_and_clockread(
3021 					&ka->master_kernel_ns,
3022 					&ka->master_cycle_now);
3023 
3024 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3025 				&& !ka->backwards_tsc_observed
3026 				&& !ka->boot_vcpu_runs_old_kvmclock;
3027 
3028 	if (ka->use_master_clock)
3029 		atomic_set(&kvm_guest_has_master_clock, 1);
3030 
3031 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3032 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3033 					vcpus_matched);
3034 #endif
3035 }
3036 
kvm_make_mclock_inprogress_request(struct kvm * kvm)3037 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3038 {
3039 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3040 }
3041 
__kvm_start_pvclock_update(struct kvm * kvm)3042 static void __kvm_start_pvclock_update(struct kvm *kvm)
3043 {
3044 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3045 	write_seqcount_begin(&kvm->arch.pvclock_sc);
3046 }
3047 
kvm_start_pvclock_update(struct kvm * kvm)3048 static void kvm_start_pvclock_update(struct kvm *kvm)
3049 {
3050 	kvm_make_mclock_inprogress_request(kvm);
3051 
3052 	/* no guest entries from this point */
3053 	__kvm_start_pvclock_update(kvm);
3054 }
3055 
kvm_end_pvclock_update(struct kvm * kvm)3056 static void kvm_end_pvclock_update(struct kvm *kvm)
3057 {
3058 	struct kvm_arch *ka = &kvm->arch;
3059 	struct kvm_vcpu *vcpu;
3060 	unsigned long i;
3061 
3062 	write_seqcount_end(&ka->pvclock_sc);
3063 	raw_spin_unlock_irq(&ka->tsc_write_lock);
3064 	kvm_for_each_vcpu(i, vcpu, kvm)
3065 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3066 
3067 	/* guest entries allowed */
3068 	kvm_for_each_vcpu(i, vcpu, kvm)
3069 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3070 }
3071 
kvm_update_masterclock(struct kvm * kvm)3072 static void kvm_update_masterclock(struct kvm *kvm)
3073 {
3074 	kvm_hv_request_tsc_page_update(kvm);
3075 	kvm_start_pvclock_update(kvm);
3076 	pvclock_update_vm_gtod_copy(kvm);
3077 	kvm_end_pvclock_update(kvm);
3078 }
3079 
3080 /*
3081  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3082  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
3083  * can change during boot even if the TSC is constant, as it's possible for KVM
3084  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
3085  * notification when calibration completes, but practically speaking calibration
3086  * will complete before userspace is alive enough to create VMs.
3087  */
get_cpu_tsc_khz(void)3088 static unsigned long get_cpu_tsc_khz(void)
3089 {
3090 	if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3091 		return tsc_khz;
3092 	else
3093 		return __this_cpu_read(cpu_tsc_khz);
3094 }
3095 
3096 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3097 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3098 {
3099 	struct kvm_arch *ka = &kvm->arch;
3100 	struct pvclock_vcpu_time_info hv_clock;
3101 
3102 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
3103 	get_cpu();
3104 
3105 	data->flags = 0;
3106 	if (ka->use_master_clock &&
3107 	    (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3108 #ifdef CONFIG_X86_64
3109 		struct timespec64 ts;
3110 
3111 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3112 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3113 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3114 		} else
3115 #endif
3116 		data->host_tsc = rdtsc();
3117 
3118 		data->flags |= KVM_CLOCK_TSC_STABLE;
3119 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3120 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3121 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3122 				   &hv_clock.tsc_shift,
3123 				   &hv_clock.tsc_to_system_mul);
3124 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3125 	} else {
3126 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3127 	}
3128 
3129 	put_cpu();
3130 }
3131 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3132 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3133 {
3134 	struct kvm_arch *ka = &kvm->arch;
3135 	unsigned seq;
3136 
3137 	do {
3138 		seq = read_seqcount_begin(&ka->pvclock_sc);
3139 		__get_kvmclock(kvm, data);
3140 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3141 }
3142 
get_kvmclock_ns(struct kvm * kvm)3143 u64 get_kvmclock_ns(struct kvm *kvm)
3144 {
3145 	struct kvm_clock_data data;
3146 
3147 	get_kvmclock(kvm, &data);
3148 	return data.clock;
3149 }
3150 
kvm_setup_guest_pvclock(struct kvm_vcpu * v,struct gfn_to_pfn_cache * gpc,unsigned int offset,bool force_tsc_unstable)3151 static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
3152 				    struct gfn_to_pfn_cache *gpc,
3153 				    unsigned int offset,
3154 				    bool force_tsc_unstable)
3155 {
3156 	struct kvm_vcpu_arch *vcpu = &v->arch;
3157 	struct pvclock_vcpu_time_info *guest_hv_clock;
3158 	unsigned long flags;
3159 
3160 	read_lock_irqsave(&gpc->lock, flags);
3161 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3162 		read_unlock_irqrestore(&gpc->lock, flags);
3163 
3164 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3165 			return;
3166 
3167 		read_lock_irqsave(&gpc->lock, flags);
3168 	}
3169 
3170 	guest_hv_clock = (void *)(gpc->khva + offset);
3171 
3172 	/*
3173 	 * This VCPU is paused, but it's legal for a guest to read another
3174 	 * VCPU's kvmclock, so we really have to follow the specification where
3175 	 * it says that version is odd if data is being modified, and even after
3176 	 * it is consistent.
3177 	 */
3178 
3179 	guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
3180 	smp_wmb();
3181 
3182 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3183 	vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3184 
3185 	if (vcpu->pvclock_set_guest_stopped_request) {
3186 		vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3187 		vcpu->pvclock_set_guest_stopped_request = false;
3188 	}
3189 
3190 	memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
3191 
3192 	if (force_tsc_unstable)
3193 		guest_hv_clock->flags &= ~PVCLOCK_TSC_STABLE_BIT;
3194 
3195 	smp_wmb();
3196 
3197 	guest_hv_clock->version = ++vcpu->hv_clock.version;
3198 
3199 	kvm_gpc_mark_dirty_in_slot(gpc);
3200 	read_unlock_irqrestore(&gpc->lock, flags);
3201 
3202 	trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
3203 }
3204 
kvm_guest_time_update(struct kvm_vcpu * v)3205 static int kvm_guest_time_update(struct kvm_vcpu *v)
3206 {
3207 	unsigned long flags, tgt_tsc_khz;
3208 	unsigned seq;
3209 	struct kvm_vcpu_arch *vcpu = &v->arch;
3210 	struct kvm_arch *ka = &v->kvm->arch;
3211 	s64 kernel_ns;
3212 	u64 tsc_timestamp, host_tsc;
3213 	u8 pvclock_flags;
3214 	bool use_master_clock;
3215 #ifdef CONFIG_KVM_XEN
3216 	/*
3217 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3218 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3219 	 * This default behaviour led to bugs in some guest kernels which cause
3220 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3221 	 */
3222 	bool xen_pvclock_tsc_unstable =
3223 		ka->xen_hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE;
3224 #endif
3225 
3226 	kernel_ns = 0;
3227 	host_tsc = 0;
3228 
3229 	/*
3230 	 * If the host uses TSC clock, then passthrough TSC as stable
3231 	 * to the guest.
3232 	 */
3233 	do {
3234 		seq = read_seqcount_begin(&ka->pvclock_sc);
3235 		use_master_clock = ka->use_master_clock;
3236 		if (use_master_clock) {
3237 			host_tsc = ka->master_cycle_now;
3238 			kernel_ns = ka->master_kernel_ns;
3239 		}
3240 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3241 
3242 	/* Keep irq disabled to prevent changes to the clock */
3243 	local_irq_save(flags);
3244 	tgt_tsc_khz = get_cpu_tsc_khz();
3245 	if (unlikely(tgt_tsc_khz == 0)) {
3246 		local_irq_restore(flags);
3247 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3248 		return 1;
3249 	}
3250 	if (!use_master_clock) {
3251 		host_tsc = rdtsc();
3252 		kernel_ns = get_kvmclock_base_ns();
3253 	}
3254 
3255 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3256 
3257 	/*
3258 	 * We may have to catch up the TSC to match elapsed wall clock
3259 	 * time for two reasons, even if kvmclock is used.
3260 	 *   1) CPU could have been running below the maximum TSC rate
3261 	 *   2) Broken TSC compensation resets the base at each VCPU
3262 	 *      entry to avoid unknown leaps of TSC even when running
3263 	 *      again on the same CPU.  This may cause apparent elapsed
3264 	 *      time to disappear, and the guest to stand still or run
3265 	 *	very slowly.
3266 	 */
3267 	if (vcpu->tsc_catchup) {
3268 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3269 		if (tsc > tsc_timestamp) {
3270 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3271 			tsc_timestamp = tsc;
3272 		}
3273 	}
3274 
3275 	local_irq_restore(flags);
3276 
3277 	/* With all the info we got, fill in the values */
3278 
3279 	if (kvm_caps.has_tsc_control)
3280 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3281 					    v->arch.l1_tsc_scaling_ratio);
3282 
3283 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3284 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3285 				   &vcpu->hv_clock.tsc_shift,
3286 				   &vcpu->hv_clock.tsc_to_system_mul);
3287 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3288 		kvm_xen_update_tsc_info(v);
3289 	}
3290 
3291 	vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
3292 	vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3293 	vcpu->last_guest_tsc = tsc_timestamp;
3294 
3295 	/* If the host uses TSC clocksource, then it is stable */
3296 	pvclock_flags = 0;
3297 	if (use_master_clock)
3298 		pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3299 
3300 	vcpu->hv_clock.flags = pvclock_flags;
3301 
3302 	if (vcpu->pv_time.active)
3303 		kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0, false);
3304 #ifdef CONFIG_KVM_XEN
3305 	if (vcpu->xen.vcpu_info_cache.active)
3306 		kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
3307 					offsetof(struct compat_vcpu_info, time),
3308 					xen_pvclock_tsc_unstable);
3309 	if (vcpu->xen.vcpu_time_info_cache.active)
3310 		kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0,
3311 					xen_pvclock_tsc_unstable);
3312 #endif
3313 	kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
3314 	return 0;
3315 }
3316 
3317 /*
3318  * The pvclock_wall_clock ABI tells the guest the wall clock time at
3319  * which it started (i.e. its epoch, when its kvmclock was zero).
3320  *
3321  * In fact those clocks are subtly different; wall clock frequency is
3322  * adjusted by NTP and has leap seconds, while the kvmclock is a
3323  * simple function of the TSC without any such adjustment.
3324  *
3325  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3326  * that and kvmclock, but even that would be subject to change over
3327  * time.
3328  *
3329  * Attempt to calculate the epoch at a given moment using the *same*
3330  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3331  * wallclock and kvmclock times, and subtracting one from the other.
3332  *
3333  * Fall back to using their values at slightly different moments by
3334  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3335  */
kvm_get_wall_clock_epoch(struct kvm * kvm)3336 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3337 {
3338 #ifdef CONFIG_X86_64
3339 	struct pvclock_vcpu_time_info hv_clock;
3340 	struct kvm_arch *ka = &kvm->arch;
3341 	unsigned long seq, local_tsc_khz;
3342 	struct timespec64 ts;
3343 	uint64_t host_tsc;
3344 
3345 	do {
3346 		seq = read_seqcount_begin(&ka->pvclock_sc);
3347 
3348 		local_tsc_khz = 0;
3349 		if (!ka->use_master_clock)
3350 			break;
3351 
3352 		/*
3353 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
3354 		 * on the same CPU.
3355 		 */
3356 		get_cpu();
3357 
3358 		local_tsc_khz = get_cpu_tsc_khz();
3359 
3360 		if (local_tsc_khz &&
3361 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3362 			local_tsc_khz = 0; /* Fall back to old method */
3363 
3364 		put_cpu();
3365 
3366 		/*
3367 		 * These values must be snapshotted within the seqcount loop.
3368 		 * After that, it's just mathematics which can happen on any
3369 		 * CPU at any time.
3370 		 */
3371 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3372 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3373 
3374 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3375 
3376 	/*
3377 	 * If the conditions were right, and obtaining the wallclock+TSC was
3378 	 * successful, calculate the KVM clock at the corresponding time and
3379 	 * subtract one from the other to get the guest's epoch in nanoseconds
3380 	 * since 1970-01-01.
3381 	 */
3382 	if (local_tsc_khz) {
3383 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3384 				   &hv_clock.tsc_shift,
3385 				   &hv_clock.tsc_to_system_mul);
3386 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3387 			__pvclock_read_cycles(&hv_clock, host_tsc);
3388 	}
3389 #endif
3390 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3391 }
3392 
3393 /*
3394  * kvmclock updates which are isolated to a given vcpu, such as
3395  * vcpu->cpu migration, should not allow system_timestamp from
3396  * the rest of the vcpus to remain static. Otherwise ntp frequency
3397  * correction applies to one vcpu's system_timestamp but not
3398  * the others.
3399  *
3400  * So in those cases, request a kvmclock update for all vcpus.
3401  * We need to rate-limit these requests though, as they can
3402  * considerably slow guests that have a large number of vcpus.
3403  * The time for a remote vcpu to update its kvmclock is bound
3404  * by the delay we use to rate-limit the updates.
3405  */
3406 
3407 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3408 
kvmclock_update_fn(struct work_struct * work)3409 static void kvmclock_update_fn(struct work_struct *work)
3410 {
3411 	unsigned long i;
3412 	struct delayed_work *dwork = to_delayed_work(work);
3413 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3414 					   kvmclock_update_work);
3415 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3416 	struct kvm_vcpu *vcpu;
3417 
3418 	kvm_for_each_vcpu(i, vcpu, kvm) {
3419 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3420 		kvm_vcpu_kick(vcpu);
3421 	}
3422 }
3423 
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3424 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3425 {
3426 	struct kvm *kvm = v->kvm;
3427 
3428 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3429 	schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3430 					KVMCLOCK_UPDATE_DELAY);
3431 }
3432 
3433 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3434 
kvmclock_sync_fn(struct work_struct * work)3435 static void kvmclock_sync_fn(struct work_struct *work)
3436 {
3437 	struct delayed_work *dwork = to_delayed_work(work);
3438 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3439 					   kvmclock_sync_work);
3440 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3441 
3442 	schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3443 	schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3444 					KVMCLOCK_SYNC_PERIOD);
3445 }
3446 
3447 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3448 static bool is_mci_control_msr(u32 msr)
3449 {
3450 	return (msr & 3) == 0;
3451 }
is_mci_status_msr(u32 msr)3452 static bool is_mci_status_msr(u32 msr)
3453 {
3454 	return (msr & 3) == 1;
3455 }
3456 
3457 /*
3458  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3459  */
can_set_mci_status(struct kvm_vcpu * vcpu)3460 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3461 {
3462 	/* McStatusWrEn enabled? */
3463 	if (guest_cpuid_is_amd_compatible(vcpu))
3464 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3465 
3466 	return false;
3467 }
3468 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3469 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3470 {
3471 	u64 mcg_cap = vcpu->arch.mcg_cap;
3472 	unsigned bank_num = mcg_cap & 0xff;
3473 	u32 msr = msr_info->index;
3474 	u64 data = msr_info->data;
3475 	u32 offset, last_msr;
3476 
3477 	switch (msr) {
3478 	case MSR_IA32_MCG_STATUS:
3479 		vcpu->arch.mcg_status = data;
3480 		break;
3481 	case MSR_IA32_MCG_CTL:
3482 		if (!(mcg_cap & MCG_CTL_P) &&
3483 		    (data || !msr_info->host_initiated))
3484 			return 1;
3485 		if (data != 0 && data != ~(u64)0)
3486 			return 1;
3487 		vcpu->arch.mcg_ctl = data;
3488 		break;
3489 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3490 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3491 		if (msr > last_msr)
3492 			return 1;
3493 
3494 		if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3495 			return 1;
3496 		/* An attempt to write a 1 to a reserved bit raises #GP */
3497 		if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3498 			return 1;
3499 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3500 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
3501 		vcpu->arch.mci_ctl2_banks[offset] = data;
3502 		break;
3503 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3504 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3505 		if (msr > last_msr)
3506 			return 1;
3507 
3508 		/*
3509 		 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3510 		 * values are architecturally undefined.  But, some Linux
3511 		 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3512 		 * issue on AMD K8s, allow bit 10 to be clear when setting all
3513 		 * other bits in order to avoid an uncaught #GP in the guest.
3514 		 *
3515 		 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3516 		 * single-bit ECC data errors.
3517 		 */
3518 		if (is_mci_control_msr(msr) &&
3519 		    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3520 			return 1;
3521 
3522 		/*
3523 		 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3524 		 * AMD-based CPUs allow non-zero values, but if and only if
3525 		 * HWCR[McStatusWrEn] is set.
3526 		 */
3527 		if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3528 		    data != 0 && !can_set_mci_status(vcpu))
3529 			return 1;
3530 
3531 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3532 					    last_msr + 1 - MSR_IA32_MC0_CTL);
3533 		vcpu->arch.mce_banks[offset] = data;
3534 		break;
3535 	default:
3536 		return 1;
3537 	}
3538 	return 0;
3539 }
3540 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3541 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3542 {
3543 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3544 
3545 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
3546 }
3547 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3548 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3549 {
3550 	gpa_t gpa = data & ~0x3f;
3551 
3552 	/* Bits 4:5 are reserved, Should be zero */
3553 	if (data & 0x30)
3554 		return 1;
3555 
3556 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3557 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3558 		return 1;
3559 
3560 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3561 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3562 		return 1;
3563 
3564 	if (!lapic_in_kernel(vcpu))
3565 		return data ? 1 : 0;
3566 
3567 	vcpu->arch.apf.msr_en_val = data;
3568 
3569 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3570 		kvm_clear_async_pf_completion_queue(vcpu);
3571 		kvm_async_pf_hash_reset(vcpu);
3572 		return 0;
3573 	}
3574 
3575 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3576 					sizeof(u64)))
3577 		return 1;
3578 
3579 	vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
3580 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3581 
3582 	kvm_async_pf_wakeup_all(vcpu);
3583 
3584 	return 0;
3585 }
3586 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3587 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3588 {
3589 	/* Bits 8-63 are reserved */
3590 	if (data >> 8)
3591 		return 1;
3592 
3593 	if (!lapic_in_kernel(vcpu))
3594 		return 1;
3595 
3596 	vcpu->arch.apf.msr_int_val = data;
3597 
3598 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3599 
3600 	return 0;
3601 }
3602 
kvmclock_reset(struct kvm_vcpu * vcpu)3603 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3604 {
3605 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
3606 	vcpu->arch.time = 0;
3607 }
3608 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3609 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3610 {
3611 	++vcpu->stat.tlb_flush;
3612 	kvm_x86_call(flush_tlb_all)(vcpu);
3613 
3614 	/* Flushing all ASIDs flushes the current ASID... */
3615 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3616 }
3617 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3618 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3619 {
3620 	++vcpu->stat.tlb_flush;
3621 
3622 	if (!tdp_enabled) {
3623 		/*
3624 		 * A TLB flush on behalf of the guest is equivalent to
3625 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3626 		 * a forced sync of the shadow page tables.  Ensure all the
3627 		 * roots are synced and the guest TLB in hardware is clean.
3628 		 */
3629 		kvm_mmu_sync_roots(vcpu);
3630 		kvm_mmu_sync_prev_roots(vcpu);
3631 	}
3632 
3633 	kvm_x86_call(flush_tlb_guest)(vcpu);
3634 
3635 	/*
3636 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3637 	 * grained flushing.
3638 	 */
3639 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
3640 }
3641 
3642 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3643 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3644 {
3645 	++vcpu->stat.tlb_flush;
3646 	kvm_x86_call(flush_tlb_current)(vcpu);
3647 }
3648 
3649 /*
3650  * Service "local" TLB flush requests, which are specific to the current MMU
3651  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3652  * TLB flushes that are targeted at an MMU context also need to be serviced
3653  * prior before nested VM-Enter/VM-Exit.
3654  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3655 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3656 {
3657 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3658 		kvm_vcpu_flush_tlb_current(vcpu);
3659 
3660 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3661 		kvm_vcpu_flush_tlb_guest(vcpu);
3662 }
3663 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3664 
record_steal_time(struct kvm_vcpu * vcpu)3665 static void record_steal_time(struct kvm_vcpu *vcpu)
3666 {
3667 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3668 	struct kvm_steal_time __user *st;
3669 	struct kvm_memslots *slots;
3670 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3671 	u64 steal;
3672 	u32 version;
3673 
3674 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3675 		kvm_xen_runstate_set_running(vcpu);
3676 		return;
3677 	}
3678 
3679 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3680 		return;
3681 
3682 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3683 		return;
3684 
3685 	slots = kvm_memslots(vcpu->kvm);
3686 
3687 	if (unlikely(slots->generation != ghc->generation ||
3688 		     gpa != ghc->gpa ||
3689 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3690 		/* We rely on the fact that it fits in a single page. */
3691 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3692 
3693 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3694 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3695 			return;
3696 	}
3697 
3698 	st = (struct kvm_steal_time __user *)ghc->hva;
3699 	/*
3700 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3701 	 * expensive IPIs.
3702 	 */
3703 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3704 		u8 st_preempted = 0;
3705 		int err = -EFAULT;
3706 
3707 		if (!user_access_begin(st, sizeof(*st)))
3708 			return;
3709 
3710 		asm volatile("1: xchgb %0, %2\n"
3711 			     "xor %1, %1\n"
3712 			     "2:\n"
3713 			     _ASM_EXTABLE_UA(1b, 2b)
3714 			     : "+q" (st_preempted),
3715 			       "+&r" (err),
3716 			       "+m" (st->preempted));
3717 		if (err)
3718 			goto out;
3719 
3720 		user_access_end();
3721 
3722 		vcpu->arch.st.preempted = 0;
3723 
3724 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3725 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3726 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3727 			kvm_vcpu_flush_tlb_guest(vcpu);
3728 
3729 		if (!user_access_begin(st, sizeof(*st)))
3730 			goto dirty;
3731 	} else {
3732 		if (!user_access_begin(st, sizeof(*st)))
3733 			return;
3734 
3735 		unsafe_put_user(0, &st->preempted, out);
3736 		vcpu->arch.st.preempted = 0;
3737 	}
3738 
3739 	unsafe_get_user(version, &st->version, out);
3740 	if (version & 1)
3741 		version += 1;  /* first time write, random junk */
3742 
3743 	version += 1;
3744 	unsafe_put_user(version, &st->version, out);
3745 
3746 	smp_wmb();
3747 
3748 	unsafe_get_user(steal, &st->steal, out);
3749 	steal += current->sched_info.run_delay -
3750 		vcpu->arch.st.last_steal;
3751 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3752 	unsafe_put_user(steal, &st->steal, out);
3753 
3754 	version += 1;
3755 	unsafe_put_user(version, &st->version, out);
3756 
3757  out:
3758 	user_access_end();
3759  dirty:
3760 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3761 }
3762 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3763 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3764 {
3765 	u32 msr = msr_info->index;
3766 	u64 data = msr_info->data;
3767 
3768 	if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
3769 		return kvm_xen_write_hypercall_page(vcpu, data);
3770 
3771 	switch (msr) {
3772 	case MSR_AMD64_NB_CFG:
3773 	case MSR_IA32_UCODE_WRITE:
3774 	case MSR_VM_HSAVE_PA:
3775 	case MSR_AMD64_PATCH_LOADER:
3776 	case MSR_AMD64_BU_CFG2:
3777 	case MSR_AMD64_DC_CFG:
3778 	case MSR_AMD64_TW_CFG:
3779 	case MSR_F15H_EX_CFG:
3780 		break;
3781 
3782 	case MSR_IA32_UCODE_REV:
3783 		if (msr_info->host_initiated)
3784 			vcpu->arch.microcode_version = data;
3785 		break;
3786 	case MSR_IA32_ARCH_CAPABILITIES:
3787 		if (!msr_info->host_initiated)
3788 			return 1;
3789 		vcpu->arch.arch_capabilities = data;
3790 		break;
3791 	case MSR_IA32_PERF_CAPABILITIES:
3792 		if (!msr_info->host_initiated)
3793 			return 1;
3794 		if (data & ~kvm_caps.supported_perf_cap)
3795 			return 1;
3796 
3797 		/*
3798 		 * Note, this is not just a performance optimization!  KVM
3799 		 * disallows changing feature MSRs after the vCPU has run; PMU
3800 		 * refresh will bug the VM if called after the vCPU has run.
3801 		 */
3802 		if (vcpu->arch.perf_capabilities == data)
3803 			break;
3804 
3805 		vcpu->arch.perf_capabilities = data;
3806 		kvm_pmu_refresh(vcpu);
3807 		break;
3808 	case MSR_IA32_PRED_CMD: {
3809 		u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3810 
3811 		if (!msr_info->host_initiated) {
3812 			if ((!guest_has_pred_cmd_msr(vcpu)))
3813 				return 1;
3814 
3815 			if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3816 			    !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
3817 				reserved_bits |= PRED_CMD_IBPB;
3818 
3819 			if (!guest_cpuid_has(vcpu, X86_FEATURE_SBPB))
3820 				reserved_bits |= PRED_CMD_SBPB;
3821 		}
3822 
3823 		if (!boot_cpu_has(X86_FEATURE_IBPB))
3824 			reserved_bits |= PRED_CMD_IBPB;
3825 
3826 		if (!boot_cpu_has(X86_FEATURE_SBPB))
3827 			reserved_bits |= PRED_CMD_SBPB;
3828 
3829 		if (data & reserved_bits)
3830 			return 1;
3831 
3832 		if (!data)
3833 			break;
3834 
3835 		wrmsrl(MSR_IA32_PRED_CMD, data);
3836 		break;
3837 	}
3838 	case MSR_IA32_FLUSH_CMD:
3839 		if (!msr_info->host_initiated &&
3840 		    !guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D))
3841 			return 1;
3842 
3843 		if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3844 			return 1;
3845 		if (!data)
3846 			break;
3847 
3848 		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3849 		break;
3850 	case MSR_EFER:
3851 		return set_efer(vcpu, msr_info);
3852 	case MSR_K7_HWCR:
3853 		data &= ~(u64)0x40;	/* ignore flush filter disable */
3854 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
3855 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
3856 
3857 		/*
3858 		 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3859 		 * through at least v6.6 whine if TscFreqSel is clear,
3860 		 * depending on F/M/S.
3861 		 */
3862 		if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
3863 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3864 			return 1;
3865 		}
3866 		vcpu->arch.msr_hwcr = data;
3867 		break;
3868 	case MSR_FAM10H_MMIO_CONF_BASE:
3869 		if (data != 0) {
3870 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3871 			return 1;
3872 		}
3873 		break;
3874 	case MSR_IA32_CR_PAT:
3875 		if (!kvm_pat_valid(data))
3876 			return 1;
3877 
3878 		vcpu->arch.pat = data;
3879 		break;
3880 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3881 	case MSR_MTRRdefType:
3882 		return kvm_mtrr_set_msr(vcpu, msr, data);
3883 	case MSR_IA32_APICBASE:
3884 		return kvm_set_apic_base(vcpu, msr_info);
3885 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3886 		return kvm_x2apic_msr_write(vcpu, msr, data);
3887 	case MSR_IA32_TSC_DEADLINE:
3888 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
3889 		break;
3890 	case MSR_IA32_TSC_ADJUST:
3891 		if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3892 			if (!msr_info->host_initiated) {
3893 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3894 				adjust_tsc_offset_guest(vcpu, adj);
3895 				/* Before back to guest, tsc_timestamp must be adjusted
3896 				 * as well, otherwise guest's percpu pvclock time could jump.
3897 				 */
3898 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3899 			}
3900 			vcpu->arch.ia32_tsc_adjust_msr = data;
3901 		}
3902 		break;
3903 	case MSR_IA32_MISC_ENABLE: {
3904 		u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3905 
3906 		if (!msr_info->host_initiated) {
3907 			/* RO bits */
3908 			if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3909 				return 1;
3910 
3911 			/* R bits, i.e. writes are ignored, but don't fault. */
3912 			data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3913 			data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3914 		}
3915 
3916 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3917 		    ((old_val ^ data)  & MSR_IA32_MISC_ENABLE_MWAIT)) {
3918 			if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3919 				return 1;
3920 			vcpu->arch.ia32_misc_enable_msr = data;
3921 			kvm_update_cpuid_runtime(vcpu);
3922 		} else {
3923 			vcpu->arch.ia32_misc_enable_msr = data;
3924 		}
3925 		break;
3926 	}
3927 	case MSR_IA32_SMBASE:
3928 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
3929 			return 1;
3930 		vcpu->arch.smbase = data;
3931 		break;
3932 	case MSR_IA32_POWER_CTL:
3933 		vcpu->arch.msr_ia32_power_ctl = data;
3934 		break;
3935 	case MSR_IA32_TSC:
3936 		if (msr_info->host_initiated) {
3937 			kvm_synchronize_tsc(vcpu, &data);
3938 		} else {
3939 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3940 			adjust_tsc_offset_guest(vcpu, adj);
3941 			vcpu->arch.ia32_tsc_adjust_msr += adj;
3942 		}
3943 		break;
3944 	case MSR_IA32_XSS:
3945 		if (!msr_info->host_initiated &&
3946 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3947 			return 1;
3948 		/*
3949 		 * KVM supports exposing PT to the guest, but does not support
3950 		 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3951 		 * XSAVES/XRSTORS to save/restore PT MSRs.
3952 		 */
3953 		if (data & ~kvm_caps.supported_xss)
3954 			return 1;
3955 		vcpu->arch.ia32_xss = data;
3956 		kvm_update_cpuid_runtime(vcpu);
3957 		break;
3958 	case MSR_SMI_COUNT:
3959 		if (!msr_info->host_initiated)
3960 			return 1;
3961 		vcpu->arch.smi_count = data;
3962 		break;
3963 	case MSR_KVM_WALL_CLOCK_NEW:
3964 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3965 			return 1;
3966 
3967 		vcpu->kvm->arch.wall_clock = data;
3968 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3969 		break;
3970 	case MSR_KVM_WALL_CLOCK:
3971 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3972 			return 1;
3973 
3974 		vcpu->kvm->arch.wall_clock = data;
3975 		kvm_write_wall_clock(vcpu->kvm, data, 0);
3976 		break;
3977 	case MSR_KVM_SYSTEM_TIME_NEW:
3978 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3979 			return 1;
3980 
3981 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3982 		break;
3983 	case MSR_KVM_SYSTEM_TIME:
3984 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3985 			return 1;
3986 
3987 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
3988 		break;
3989 	case MSR_KVM_ASYNC_PF_EN:
3990 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3991 			return 1;
3992 
3993 		if (kvm_pv_enable_async_pf(vcpu, data))
3994 			return 1;
3995 		break;
3996 	case MSR_KVM_ASYNC_PF_INT:
3997 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3998 			return 1;
3999 
4000 		if (kvm_pv_enable_async_pf_int(vcpu, data))
4001 			return 1;
4002 		break;
4003 	case MSR_KVM_ASYNC_PF_ACK:
4004 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4005 			return 1;
4006 		if (data & 0x1) {
4007 			vcpu->arch.apf.pageready_pending = false;
4008 			kvm_check_async_pf_completion(vcpu);
4009 		}
4010 		break;
4011 	case MSR_KVM_STEAL_TIME:
4012 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4013 			return 1;
4014 
4015 		if (unlikely(!sched_info_on()))
4016 			return 1;
4017 
4018 		if (data & KVM_STEAL_RESERVED_MASK)
4019 			return 1;
4020 
4021 		vcpu->arch.st.msr_val = data;
4022 
4023 		if (!(data & KVM_MSR_ENABLED))
4024 			break;
4025 
4026 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4027 
4028 		break;
4029 	case MSR_KVM_PV_EOI_EN:
4030 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4031 			return 1;
4032 
4033 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4034 			return 1;
4035 		break;
4036 
4037 	case MSR_KVM_POLL_CONTROL:
4038 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4039 			return 1;
4040 
4041 		/* only enable bit supported */
4042 		if (data & (-1ULL << 1))
4043 			return 1;
4044 
4045 		vcpu->arch.msr_kvm_poll_control = data;
4046 		break;
4047 
4048 	case MSR_IA32_MCG_CTL:
4049 	case MSR_IA32_MCG_STATUS:
4050 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4051 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4052 		return set_msr_mce(vcpu, msr_info);
4053 
4054 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4055 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4056 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4057 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4058 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4059 			return kvm_pmu_set_msr(vcpu, msr_info);
4060 
4061 		if (data)
4062 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4063 		break;
4064 	case MSR_K7_CLK_CTL:
4065 		/*
4066 		 * Ignore all writes to this no longer documented MSR.
4067 		 * Writes are only relevant for old K7 processors,
4068 		 * all pre-dating SVM, but a recommended workaround from
4069 		 * AMD for these chips. It is possible to specify the
4070 		 * affected processor models on the command line, hence
4071 		 * the need to ignore the workaround.
4072 		 */
4073 		break;
4074 #ifdef CONFIG_KVM_HYPERV
4075 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4076 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4077 	case HV_X64_MSR_SYNDBG_OPTIONS:
4078 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4079 	case HV_X64_MSR_CRASH_CTL:
4080 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4081 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4082 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4083 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4084 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4085 		return kvm_hv_set_msr_common(vcpu, msr, data,
4086 					     msr_info->host_initiated);
4087 #endif
4088 	case MSR_IA32_BBL_CR_CTL3:
4089 		/* Drop writes to this legacy MSR -- see rdmsr
4090 		 * counterpart for further detail.
4091 		 */
4092 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4093 		break;
4094 	case MSR_AMD64_OSVW_ID_LENGTH:
4095 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4096 			return 1;
4097 		vcpu->arch.osvw.length = data;
4098 		break;
4099 	case MSR_AMD64_OSVW_STATUS:
4100 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4101 			return 1;
4102 		vcpu->arch.osvw.status = data;
4103 		break;
4104 	case MSR_PLATFORM_INFO:
4105 		if (!msr_info->host_initiated ||
4106 		    (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
4107 		     cpuid_fault_enabled(vcpu)))
4108 			return 1;
4109 		vcpu->arch.msr_platform_info = data;
4110 		break;
4111 	case MSR_MISC_FEATURES_ENABLES:
4112 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4113 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4114 		     !supports_cpuid_fault(vcpu)))
4115 			return 1;
4116 		vcpu->arch.msr_misc_features_enables = data;
4117 		break;
4118 #ifdef CONFIG_X86_64
4119 	case MSR_IA32_XFD:
4120 		if (!msr_info->host_initiated &&
4121 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4122 			return 1;
4123 
4124 		if (data & ~kvm_guest_supported_xfd(vcpu))
4125 			return 1;
4126 
4127 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4128 		break;
4129 	case MSR_IA32_XFD_ERR:
4130 		if (!msr_info->host_initiated &&
4131 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4132 			return 1;
4133 
4134 		if (data & ~kvm_guest_supported_xfd(vcpu))
4135 			return 1;
4136 
4137 		vcpu->arch.guest_fpu.xfd_err = data;
4138 		break;
4139 #endif
4140 	default:
4141 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4142 			return kvm_pmu_set_msr(vcpu, msr_info);
4143 
4144 		return KVM_MSR_RET_UNSUPPORTED;
4145 	}
4146 	return 0;
4147 }
4148 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4149 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4150 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4151 {
4152 	u64 data;
4153 	u64 mcg_cap = vcpu->arch.mcg_cap;
4154 	unsigned bank_num = mcg_cap & 0xff;
4155 	u32 offset, last_msr;
4156 
4157 	switch (msr) {
4158 	case MSR_IA32_P5_MC_ADDR:
4159 	case MSR_IA32_P5_MC_TYPE:
4160 		data = 0;
4161 		break;
4162 	case MSR_IA32_MCG_CAP:
4163 		data = vcpu->arch.mcg_cap;
4164 		break;
4165 	case MSR_IA32_MCG_CTL:
4166 		if (!(mcg_cap & MCG_CTL_P) && !host)
4167 			return 1;
4168 		data = vcpu->arch.mcg_ctl;
4169 		break;
4170 	case MSR_IA32_MCG_STATUS:
4171 		data = vcpu->arch.mcg_status;
4172 		break;
4173 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4174 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4175 		if (msr > last_msr)
4176 			return 1;
4177 
4178 		if (!(mcg_cap & MCG_CMCI_P) && !host)
4179 			return 1;
4180 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4181 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
4182 		data = vcpu->arch.mci_ctl2_banks[offset];
4183 		break;
4184 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4185 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4186 		if (msr > last_msr)
4187 			return 1;
4188 
4189 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4190 					    last_msr + 1 - MSR_IA32_MC0_CTL);
4191 		data = vcpu->arch.mce_banks[offset];
4192 		break;
4193 	default:
4194 		return 1;
4195 	}
4196 	*pdata = data;
4197 	return 0;
4198 }
4199 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4200 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4201 {
4202 	switch (msr_info->index) {
4203 	case MSR_IA32_PLATFORM_ID:
4204 	case MSR_IA32_EBL_CR_POWERON:
4205 	case MSR_IA32_LASTBRANCHFROMIP:
4206 	case MSR_IA32_LASTBRANCHTOIP:
4207 	case MSR_IA32_LASTINTFROMIP:
4208 	case MSR_IA32_LASTINTTOIP:
4209 	case MSR_AMD64_SYSCFG:
4210 	case MSR_K8_TSEG_ADDR:
4211 	case MSR_K8_TSEG_MASK:
4212 	case MSR_VM_HSAVE_PA:
4213 	case MSR_K8_INT_PENDING_MSG:
4214 	case MSR_AMD64_NB_CFG:
4215 	case MSR_FAM10H_MMIO_CONF_BASE:
4216 	case MSR_AMD64_BU_CFG2:
4217 	case MSR_IA32_PERF_CTL:
4218 	case MSR_AMD64_DC_CFG:
4219 	case MSR_AMD64_TW_CFG:
4220 	case MSR_F15H_EX_CFG:
4221 	/*
4222 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4223 	 * limit) MSRs. Just return 0, as we do not want to expose the host
4224 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
4225 	 * so for existing CPU-specific MSRs.
4226 	 */
4227 	case MSR_RAPL_POWER_UNIT:
4228 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
4229 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
4230 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
4231 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
4232 		msr_info->data = 0;
4233 		break;
4234 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4235 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4236 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4237 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4238 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4239 			return kvm_pmu_get_msr(vcpu, msr_info);
4240 		msr_info->data = 0;
4241 		break;
4242 	case MSR_IA32_UCODE_REV:
4243 		msr_info->data = vcpu->arch.microcode_version;
4244 		break;
4245 	case MSR_IA32_ARCH_CAPABILITIES:
4246 		if (!msr_info->host_initiated &&
4247 		    !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4248 			return 1;
4249 		msr_info->data = vcpu->arch.arch_capabilities;
4250 		break;
4251 	case MSR_IA32_PERF_CAPABILITIES:
4252 		if (!msr_info->host_initiated &&
4253 		    !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
4254 			return 1;
4255 		msr_info->data = vcpu->arch.perf_capabilities;
4256 		break;
4257 	case MSR_IA32_POWER_CTL:
4258 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4259 		break;
4260 	case MSR_IA32_TSC: {
4261 		/*
4262 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4263 		 * even when not intercepted. AMD manual doesn't explicitly
4264 		 * state this but appears to behave the same.
4265 		 *
4266 		 * On userspace reads and writes, however, we unconditionally
4267 		 * return L1's TSC value to ensure backwards-compatible
4268 		 * behavior for migration.
4269 		 */
4270 		u64 offset, ratio;
4271 
4272 		if (msr_info->host_initiated) {
4273 			offset = vcpu->arch.l1_tsc_offset;
4274 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
4275 		} else {
4276 			offset = vcpu->arch.tsc_offset;
4277 			ratio = vcpu->arch.tsc_scaling_ratio;
4278 		}
4279 
4280 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4281 		break;
4282 	}
4283 	case MSR_IA32_CR_PAT:
4284 		msr_info->data = vcpu->arch.pat;
4285 		break;
4286 	case MSR_MTRRcap:
4287 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4288 	case MSR_MTRRdefType:
4289 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4290 	case 0xcd: /* fsb frequency */
4291 		msr_info->data = 3;
4292 		break;
4293 		/*
4294 		 * MSR_EBC_FREQUENCY_ID
4295 		 * Conservative value valid for even the basic CPU models.
4296 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4297 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4298 		 * and 266MHz for model 3, or 4. Set Core Clock
4299 		 * Frequency to System Bus Frequency Ratio to 1 (bits
4300 		 * 31:24) even though these are only valid for CPU
4301 		 * models > 2, however guests may end up dividing or
4302 		 * multiplying by zero otherwise.
4303 		 */
4304 	case MSR_EBC_FREQUENCY_ID:
4305 		msr_info->data = 1 << 24;
4306 		break;
4307 	case MSR_IA32_APICBASE:
4308 		msr_info->data = vcpu->arch.apic_base;
4309 		break;
4310 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4311 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4312 	case MSR_IA32_TSC_DEADLINE:
4313 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4314 		break;
4315 	case MSR_IA32_TSC_ADJUST:
4316 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4317 		break;
4318 	case MSR_IA32_MISC_ENABLE:
4319 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4320 		break;
4321 	case MSR_IA32_SMBASE:
4322 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4323 			return 1;
4324 		msr_info->data = vcpu->arch.smbase;
4325 		break;
4326 	case MSR_SMI_COUNT:
4327 		msr_info->data = vcpu->arch.smi_count;
4328 		break;
4329 	case MSR_IA32_PERF_STATUS:
4330 		/* TSC increment by tick */
4331 		msr_info->data = 1000ULL;
4332 		/* CPU multiplier */
4333 		msr_info->data |= (((uint64_t)4ULL) << 40);
4334 		break;
4335 	case MSR_EFER:
4336 		msr_info->data = vcpu->arch.efer;
4337 		break;
4338 	case MSR_KVM_WALL_CLOCK:
4339 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4340 			return 1;
4341 
4342 		msr_info->data = vcpu->kvm->arch.wall_clock;
4343 		break;
4344 	case MSR_KVM_WALL_CLOCK_NEW:
4345 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4346 			return 1;
4347 
4348 		msr_info->data = vcpu->kvm->arch.wall_clock;
4349 		break;
4350 	case MSR_KVM_SYSTEM_TIME:
4351 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4352 			return 1;
4353 
4354 		msr_info->data = vcpu->arch.time;
4355 		break;
4356 	case MSR_KVM_SYSTEM_TIME_NEW:
4357 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4358 			return 1;
4359 
4360 		msr_info->data = vcpu->arch.time;
4361 		break;
4362 	case MSR_KVM_ASYNC_PF_EN:
4363 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4364 			return 1;
4365 
4366 		msr_info->data = vcpu->arch.apf.msr_en_val;
4367 		break;
4368 	case MSR_KVM_ASYNC_PF_INT:
4369 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4370 			return 1;
4371 
4372 		msr_info->data = vcpu->arch.apf.msr_int_val;
4373 		break;
4374 	case MSR_KVM_ASYNC_PF_ACK:
4375 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4376 			return 1;
4377 
4378 		msr_info->data = 0;
4379 		break;
4380 	case MSR_KVM_STEAL_TIME:
4381 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4382 			return 1;
4383 
4384 		msr_info->data = vcpu->arch.st.msr_val;
4385 		break;
4386 	case MSR_KVM_PV_EOI_EN:
4387 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4388 			return 1;
4389 
4390 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4391 		break;
4392 	case MSR_KVM_POLL_CONTROL:
4393 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4394 			return 1;
4395 
4396 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4397 		break;
4398 	case MSR_IA32_P5_MC_ADDR:
4399 	case MSR_IA32_P5_MC_TYPE:
4400 	case MSR_IA32_MCG_CAP:
4401 	case MSR_IA32_MCG_CTL:
4402 	case MSR_IA32_MCG_STATUS:
4403 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4404 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4405 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4406 				   msr_info->host_initiated);
4407 	case MSR_IA32_XSS:
4408 		if (!msr_info->host_initiated &&
4409 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4410 			return 1;
4411 		msr_info->data = vcpu->arch.ia32_xss;
4412 		break;
4413 	case MSR_K7_CLK_CTL:
4414 		/*
4415 		 * Provide expected ramp-up count for K7. All other
4416 		 * are set to zero, indicating minimum divisors for
4417 		 * every field.
4418 		 *
4419 		 * This prevents guest kernels on AMD host with CPU
4420 		 * type 6, model 8 and higher from exploding due to
4421 		 * the rdmsr failing.
4422 		 */
4423 		msr_info->data = 0x20000000;
4424 		break;
4425 #ifdef CONFIG_KVM_HYPERV
4426 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4427 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4428 	case HV_X64_MSR_SYNDBG_OPTIONS:
4429 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4430 	case HV_X64_MSR_CRASH_CTL:
4431 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4432 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4433 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4434 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4435 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4436 		return kvm_hv_get_msr_common(vcpu,
4437 					     msr_info->index, &msr_info->data,
4438 					     msr_info->host_initiated);
4439 #endif
4440 	case MSR_IA32_BBL_CR_CTL3:
4441 		/* This legacy MSR exists but isn't fully documented in current
4442 		 * silicon.  It is however accessed by winxp in very narrow
4443 		 * scenarios where it sets bit #19, itself documented as
4444 		 * a "reserved" bit.  Best effort attempt to source coherent
4445 		 * read data here should the balance of the register be
4446 		 * interpreted by the guest:
4447 		 *
4448 		 * L2 cache control register 3: 64GB range, 256KB size,
4449 		 * enabled, latency 0x1, configured
4450 		 */
4451 		msr_info->data = 0xbe702111;
4452 		break;
4453 	case MSR_AMD64_OSVW_ID_LENGTH:
4454 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4455 			return 1;
4456 		msr_info->data = vcpu->arch.osvw.length;
4457 		break;
4458 	case MSR_AMD64_OSVW_STATUS:
4459 		if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
4460 			return 1;
4461 		msr_info->data = vcpu->arch.osvw.status;
4462 		break;
4463 	case MSR_PLATFORM_INFO:
4464 		if (!msr_info->host_initiated &&
4465 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4466 			return 1;
4467 		msr_info->data = vcpu->arch.msr_platform_info;
4468 		break;
4469 	case MSR_MISC_FEATURES_ENABLES:
4470 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4471 		break;
4472 	case MSR_K7_HWCR:
4473 		msr_info->data = vcpu->arch.msr_hwcr;
4474 		break;
4475 #ifdef CONFIG_X86_64
4476 	case MSR_IA32_XFD:
4477 		if (!msr_info->host_initiated &&
4478 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4479 			return 1;
4480 
4481 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4482 		break;
4483 	case MSR_IA32_XFD_ERR:
4484 		if (!msr_info->host_initiated &&
4485 		    !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4486 			return 1;
4487 
4488 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4489 		break;
4490 #endif
4491 	default:
4492 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4493 			return kvm_pmu_get_msr(vcpu, msr_info);
4494 
4495 		return KVM_MSR_RET_UNSUPPORTED;
4496 	}
4497 	return 0;
4498 }
4499 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4500 
4501 /*
4502  * Read or write a bunch of msrs. All parameters are kernel addresses.
4503  *
4504  * @return number of msrs set successfully.
4505  */
__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))4506 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4507 		    struct kvm_msr_entry *entries,
4508 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4509 				  unsigned index, u64 *data))
4510 {
4511 	int i;
4512 
4513 	for (i = 0; i < msrs->nmsrs; ++i)
4514 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4515 			break;
4516 
4517 	return i;
4518 }
4519 
4520 /*
4521  * Read or write a bunch of msrs. Parameters are user addresses.
4522  *
4523  * @return number of msrs set successfully.
4524  */
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)4525 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4526 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4527 				unsigned index, u64 *data),
4528 		  int writeback)
4529 {
4530 	struct kvm_msrs msrs;
4531 	struct kvm_msr_entry *entries;
4532 	unsigned size;
4533 	int r;
4534 
4535 	r = -EFAULT;
4536 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4537 		goto out;
4538 
4539 	r = -E2BIG;
4540 	if (msrs.nmsrs >= MAX_IO_MSRS)
4541 		goto out;
4542 
4543 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4544 	entries = memdup_user(user_msrs->entries, size);
4545 	if (IS_ERR(entries)) {
4546 		r = PTR_ERR(entries);
4547 		goto out;
4548 	}
4549 
4550 	r = __msr_io(vcpu, &msrs, entries, do_msr);
4551 
4552 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4553 		r = -EFAULT;
4554 
4555 	kfree(entries);
4556 out:
4557 	return r;
4558 }
4559 
kvm_can_mwait_in_guest(void)4560 static inline bool kvm_can_mwait_in_guest(void)
4561 {
4562 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4563 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4564 		boot_cpu_has(X86_FEATURE_ARAT);
4565 }
4566 
4567 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4568 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4569 					    struct kvm_cpuid2 __user *cpuid_arg)
4570 {
4571 	struct kvm_cpuid2 cpuid;
4572 	int r;
4573 
4574 	r = -EFAULT;
4575 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4576 		return r;
4577 
4578 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4579 	if (r)
4580 		return r;
4581 
4582 	r = -EFAULT;
4583 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4584 		return r;
4585 
4586 	return 0;
4587 }
4588 #endif
4589 
kvm_is_vm_type_supported(unsigned long type)4590 static bool kvm_is_vm_type_supported(unsigned long type)
4591 {
4592 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4593 }
4594 
kvm_sync_valid_fields(struct kvm * kvm)4595 static inline u32 kvm_sync_valid_fields(struct kvm *kvm)
4596 {
4597 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4598 }
4599 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4600 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4601 {
4602 	int r = 0;
4603 
4604 	switch (ext) {
4605 	case KVM_CAP_IRQCHIP:
4606 	case KVM_CAP_HLT:
4607 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4608 	case KVM_CAP_SET_TSS_ADDR:
4609 	case KVM_CAP_EXT_CPUID:
4610 	case KVM_CAP_EXT_EMUL_CPUID:
4611 	case KVM_CAP_CLOCKSOURCE:
4612 	case KVM_CAP_PIT:
4613 	case KVM_CAP_NOP_IO_DELAY:
4614 	case KVM_CAP_MP_STATE:
4615 	case KVM_CAP_SYNC_MMU:
4616 	case KVM_CAP_USER_NMI:
4617 	case KVM_CAP_REINJECT_CONTROL:
4618 	case KVM_CAP_IRQ_INJECT_STATUS:
4619 	case KVM_CAP_IOEVENTFD:
4620 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4621 	case KVM_CAP_PIT2:
4622 	case KVM_CAP_PIT_STATE2:
4623 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4624 	case KVM_CAP_VCPU_EVENTS:
4625 #ifdef CONFIG_KVM_HYPERV
4626 	case KVM_CAP_HYPERV:
4627 	case KVM_CAP_HYPERV_VAPIC:
4628 	case KVM_CAP_HYPERV_SPIN:
4629 	case KVM_CAP_HYPERV_TIME:
4630 	case KVM_CAP_HYPERV_SYNIC:
4631 	case KVM_CAP_HYPERV_SYNIC2:
4632 	case KVM_CAP_HYPERV_VP_INDEX:
4633 	case KVM_CAP_HYPERV_EVENTFD:
4634 	case KVM_CAP_HYPERV_TLBFLUSH:
4635 	case KVM_CAP_HYPERV_SEND_IPI:
4636 	case KVM_CAP_HYPERV_CPUID:
4637 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4638 	case KVM_CAP_SYS_HYPERV_CPUID:
4639 #endif
4640 	case KVM_CAP_PCI_SEGMENT:
4641 	case KVM_CAP_DEBUGREGS:
4642 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4643 	case KVM_CAP_XSAVE:
4644 	case KVM_CAP_ASYNC_PF:
4645 	case KVM_CAP_ASYNC_PF_INT:
4646 	case KVM_CAP_GET_TSC_KHZ:
4647 	case KVM_CAP_KVMCLOCK_CTRL:
4648 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4649 	case KVM_CAP_TSC_DEADLINE_TIMER:
4650 	case KVM_CAP_DISABLE_QUIRKS:
4651 	case KVM_CAP_SET_BOOT_CPU_ID:
4652  	case KVM_CAP_SPLIT_IRQCHIP:
4653 	case KVM_CAP_IMMEDIATE_EXIT:
4654 	case KVM_CAP_PMU_EVENT_FILTER:
4655 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4656 	case KVM_CAP_GET_MSR_FEATURES:
4657 	case KVM_CAP_MSR_PLATFORM_INFO:
4658 	case KVM_CAP_EXCEPTION_PAYLOAD:
4659 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4660 	case KVM_CAP_SET_GUEST_DEBUG:
4661 	case KVM_CAP_LAST_CPU:
4662 	case KVM_CAP_X86_USER_SPACE_MSR:
4663 	case KVM_CAP_X86_MSR_FILTER:
4664 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4665 #ifdef CONFIG_X86_SGX_KVM
4666 	case KVM_CAP_SGX_ATTRIBUTE:
4667 #endif
4668 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4669 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4670 	case KVM_CAP_SREGS2:
4671 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4672 	case KVM_CAP_VCPU_ATTRIBUTES:
4673 	case KVM_CAP_SYS_ATTRIBUTES:
4674 	case KVM_CAP_VAPIC:
4675 	case KVM_CAP_ENABLE_CAP:
4676 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4677 	case KVM_CAP_IRQFD_RESAMPLE:
4678 	case KVM_CAP_MEMORY_FAULT_INFO:
4679 	case KVM_CAP_X86_GUEST_MODE:
4680 		r = 1;
4681 		break;
4682 	case KVM_CAP_PRE_FAULT_MEMORY:
4683 		r = tdp_enabled;
4684 		break;
4685 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4686 		r = APIC_BUS_CYCLE_NS_DEFAULT;
4687 		break;
4688 	case KVM_CAP_EXIT_HYPERCALL:
4689 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4690 		break;
4691 	case KVM_CAP_SET_GUEST_DEBUG2:
4692 		return KVM_GUESTDBG_VALID_MASK;
4693 #ifdef CONFIG_KVM_XEN
4694 	case KVM_CAP_XEN_HVM:
4695 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4696 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4697 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4698 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4699 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4700 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4701 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4702 		if (sched_info_on())
4703 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4704 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4705 		break;
4706 #endif
4707 	case KVM_CAP_SYNC_REGS:
4708 		r = kvm_sync_valid_fields(kvm);
4709 		break;
4710 	case KVM_CAP_ADJUST_CLOCK:
4711 		r = KVM_CLOCK_VALID_FLAGS;
4712 		break;
4713 	case KVM_CAP_X86_DISABLE_EXITS:
4714 		r = KVM_X86_DISABLE_EXITS_PAUSE;
4715 
4716 		if (!mitigate_smt_rsb) {
4717 			r |= KVM_X86_DISABLE_EXITS_HLT |
4718 			     KVM_X86_DISABLE_EXITS_CSTATE;
4719 
4720 			if (kvm_can_mwait_in_guest())
4721 				r |= KVM_X86_DISABLE_EXITS_MWAIT;
4722 		}
4723 		break;
4724 	case KVM_CAP_X86_SMM:
4725 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4726 			break;
4727 
4728 		/* SMBASE is usually relocated above 1M on modern chipsets,
4729 		 * and SMM handlers might indeed rely on 4G segment limits,
4730 		 * so do not report SMM to be available if real mode is
4731 		 * emulated via vm86 mode.  Still, do not go to great lengths
4732 		 * to avoid userspace's usage of the feature, because it is a
4733 		 * fringe case that is not enabled except via specific settings
4734 		 * of the module parameters.
4735 		 */
4736 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4737 		break;
4738 	case KVM_CAP_NR_VCPUS:
4739 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4740 		break;
4741 	case KVM_CAP_MAX_VCPUS:
4742 		r = KVM_MAX_VCPUS;
4743 		break;
4744 	case KVM_CAP_MAX_VCPU_ID:
4745 		r = KVM_MAX_VCPU_IDS;
4746 		break;
4747 	case KVM_CAP_PV_MMU:	/* obsolete */
4748 		r = 0;
4749 		break;
4750 	case KVM_CAP_MCE:
4751 		r = KVM_MAX_MCE_BANKS;
4752 		break;
4753 	case KVM_CAP_XCRS:
4754 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4755 		break;
4756 	case KVM_CAP_TSC_CONTROL:
4757 	case KVM_CAP_VM_TSC_CONTROL:
4758 		r = kvm_caps.has_tsc_control;
4759 		break;
4760 	case KVM_CAP_X2APIC_API:
4761 		r = KVM_X2APIC_API_VALID_FLAGS;
4762 		break;
4763 	case KVM_CAP_NESTED_STATE:
4764 		r = kvm_x86_ops.nested_ops->get_state ?
4765 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4766 		break;
4767 #ifdef CONFIG_KVM_HYPERV
4768 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4769 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4770 		break;
4771 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4772 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4773 		break;
4774 #endif
4775 	case KVM_CAP_SMALLER_MAXPHYADDR:
4776 		r = (int) allow_smaller_maxphyaddr;
4777 		break;
4778 	case KVM_CAP_STEAL_TIME:
4779 		r = sched_info_on();
4780 		break;
4781 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4782 		if (kvm_caps.has_bus_lock_exit)
4783 			r = KVM_BUS_LOCK_DETECTION_OFF |
4784 			    KVM_BUS_LOCK_DETECTION_EXIT;
4785 		else
4786 			r = 0;
4787 		break;
4788 	case KVM_CAP_XSAVE2: {
4789 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4790 		if (r < sizeof(struct kvm_xsave))
4791 			r = sizeof(struct kvm_xsave);
4792 		break;
4793 	}
4794 	case KVM_CAP_PMU_CAPABILITY:
4795 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4796 		break;
4797 	case KVM_CAP_DISABLE_QUIRKS2:
4798 		r = KVM_X86_VALID_QUIRKS;
4799 		break;
4800 	case KVM_CAP_X86_NOTIFY_VMEXIT:
4801 		r = kvm_caps.has_notify_vmexit;
4802 		break;
4803 	case KVM_CAP_VM_TYPES:
4804 		r = kvm_caps.supported_vm_types;
4805 		break;
4806 	case KVM_CAP_READONLY_MEM:
4807 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4808 		break;
4809 	default:
4810 		break;
4811 	}
4812 	return r;
4813 }
4814 
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4815 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4816 {
4817 	if (attr->group) {
4818 		if (kvm_x86_ops.dev_get_attr)
4819 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4820 		return -ENXIO;
4821 	}
4822 
4823 	switch (attr->attr) {
4824 	case KVM_X86_XCOMP_GUEST_SUPP:
4825 		*val = kvm_caps.supported_xcr0;
4826 		return 0;
4827 	default:
4828 		return -ENXIO;
4829 	}
4830 }
4831 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)4832 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4833 {
4834 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4835 	int r;
4836 	u64 val;
4837 
4838 	r = __kvm_x86_dev_get_attr(attr, &val);
4839 	if (r < 0)
4840 		return r;
4841 
4842 	if (put_user(val, uaddr))
4843 		return -EFAULT;
4844 
4845 	return 0;
4846 }
4847 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)4848 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4849 {
4850 	u64 val;
4851 
4852 	return __kvm_x86_dev_get_attr(attr, &val);
4853 }
4854 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4855 long kvm_arch_dev_ioctl(struct file *filp,
4856 			unsigned int ioctl, unsigned long arg)
4857 {
4858 	void __user *argp = (void __user *)arg;
4859 	long r;
4860 
4861 	switch (ioctl) {
4862 	case KVM_GET_MSR_INDEX_LIST: {
4863 		struct kvm_msr_list __user *user_msr_list = argp;
4864 		struct kvm_msr_list msr_list;
4865 		unsigned n;
4866 
4867 		r = -EFAULT;
4868 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4869 			goto out;
4870 		n = msr_list.nmsrs;
4871 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4872 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4873 			goto out;
4874 		r = -E2BIG;
4875 		if (n < msr_list.nmsrs)
4876 			goto out;
4877 		r = -EFAULT;
4878 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4879 				 num_msrs_to_save * sizeof(u32)))
4880 			goto out;
4881 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4882 				 &emulated_msrs,
4883 				 num_emulated_msrs * sizeof(u32)))
4884 			goto out;
4885 		r = 0;
4886 		break;
4887 	}
4888 	case KVM_GET_SUPPORTED_CPUID:
4889 	case KVM_GET_EMULATED_CPUID: {
4890 		struct kvm_cpuid2 __user *cpuid_arg = argp;
4891 		struct kvm_cpuid2 cpuid;
4892 
4893 		r = -EFAULT;
4894 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4895 			goto out;
4896 
4897 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4898 					    ioctl);
4899 		if (r)
4900 			goto out;
4901 
4902 		r = -EFAULT;
4903 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4904 			goto out;
4905 		r = 0;
4906 		break;
4907 	}
4908 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
4909 		r = -EFAULT;
4910 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4911 				 sizeof(kvm_caps.supported_mce_cap)))
4912 			goto out;
4913 		r = 0;
4914 		break;
4915 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4916 		struct kvm_msr_list __user *user_msr_list = argp;
4917 		struct kvm_msr_list msr_list;
4918 		unsigned int n;
4919 
4920 		r = -EFAULT;
4921 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4922 			goto out;
4923 		n = msr_list.nmsrs;
4924 		msr_list.nmsrs = num_msr_based_features;
4925 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4926 			goto out;
4927 		r = -E2BIG;
4928 		if (n < msr_list.nmsrs)
4929 			goto out;
4930 		r = -EFAULT;
4931 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
4932 				 num_msr_based_features * sizeof(u32)))
4933 			goto out;
4934 		r = 0;
4935 		break;
4936 	}
4937 	case KVM_GET_MSRS:
4938 		r = msr_io(NULL, argp, do_get_feature_msr, 1);
4939 		break;
4940 #ifdef CONFIG_KVM_HYPERV
4941 	case KVM_GET_SUPPORTED_HV_CPUID:
4942 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4943 		break;
4944 #endif
4945 	case KVM_GET_DEVICE_ATTR: {
4946 		struct kvm_device_attr attr;
4947 		r = -EFAULT;
4948 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4949 			break;
4950 		r = kvm_x86_dev_get_attr(&attr);
4951 		break;
4952 	}
4953 	case KVM_HAS_DEVICE_ATTR: {
4954 		struct kvm_device_attr attr;
4955 		r = -EFAULT;
4956 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4957 			break;
4958 		r = kvm_x86_dev_has_attr(&attr);
4959 		break;
4960 	}
4961 	default:
4962 		r = -EINVAL;
4963 		break;
4964 	}
4965 out:
4966 	return r;
4967 }
4968 
wbinvd_ipi(void * garbage)4969 static void wbinvd_ipi(void *garbage)
4970 {
4971 	wbinvd();
4972 }
4973 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)4974 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4975 {
4976 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4977 }
4978 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)4979 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4980 {
4981 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
4982 
4983 	vcpu->arch.l1tf_flush_l1d = true;
4984 
4985 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
4986 		pmu->need_cleanup = true;
4987 		kvm_make_request(KVM_REQ_PMU, vcpu);
4988 	}
4989 
4990 	/* Address WBINVD may be executed by guest */
4991 	if (need_emulate_wbinvd(vcpu)) {
4992 		if (kvm_x86_call(has_wbinvd_exit)())
4993 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4994 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4995 			smp_call_function_single(vcpu->cpu,
4996 					wbinvd_ipi, NULL, 1);
4997 	}
4998 
4999 	kvm_x86_call(vcpu_load)(vcpu, cpu);
5000 
5001 	/* Save host pkru register if supported */
5002 	vcpu->arch.host_pkru = read_pkru();
5003 
5004 	/* Apply any externally detected TSC adjustments (due to suspend) */
5005 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5006 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5007 		vcpu->arch.tsc_offset_adjustment = 0;
5008 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5009 	}
5010 
5011 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5012 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5013 				rdtsc() - vcpu->arch.last_host_tsc;
5014 		if (tsc_delta < 0)
5015 			mark_tsc_unstable("KVM discovered backwards TSC");
5016 
5017 		if (kvm_check_tsc_unstable()) {
5018 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5019 						vcpu->arch.last_guest_tsc);
5020 			kvm_vcpu_write_tsc_offset(vcpu, offset);
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 		vcpu->arch.preempted_in_kernel = kvm_arch_vcpu_in_kernel(vcpu);
5094 
5095 		/*
5096 		 * Take the srcu lock as memslots will be accessed to check the gfn
5097 		 * cache generation against the memslots generation.
5098 		 */
5099 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5100 		if (kvm_xen_msr_enabled(vcpu->kvm))
5101 			kvm_xen_runstate_set_preempted(vcpu);
5102 		else
5103 			kvm_steal_time_set_preempted(vcpu);
5104 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5105 	}
5106 
5107 	kvm_x86_call(vcpu_put)(vcpu);
5108 	vcpu->arch.last_host_tsc = rdtsc();
5109 }
5110 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5111 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5112 				    struct kvm_lapic_state *s)
5113 {
5114 	kvm_x86_call(sync_pir_to_irr)(vcpu);
5115 
5116 	return kvm_apic_get_state(vcpu, s);
5117 }
5118 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5119 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5120 				    struct kvm_lapic_state *s)
5121 {
5122 	int r;
5123 
5124 	r = kvm_apic_set_state(vcpu, s);
5125 	if (r)
5126 		return r;
5127 	update_cr8_intercept(vcpu);
5128 
5129 	return 0;
5130 }
5131 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5132 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5133 {
5134 	/*
5135 	 * We can accept userspace's request for interrupt injection
5136 	 * as long as we have a place to store the interrupt number.
5137 	 * The actual injection will happen when the CPU is able to
5138 	 * deliver the interrupt.
5139 	 */
5140 	if (kvm_cpu_has_extint(vcpu))
5141 		return false;
5142 
5143 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
5144 	return (!lapic_in_kernel(vcpu) ||
5145 		kvm_apic_accept_pic_intr(vcpu));
5146 }
5147 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5148 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5149 {
5150 	/*
5151 	 * Do not cause an interrupt window exit if an exception
5152 	 * is pending or an event needs reinjection; userspace
5153 	 * might want to inject the interrupt manually using KVM_SET_REGS
5154 	 * or KVM_SET_SREGS.  For that to work, we must be at an
5155 	 * instruction boundary and with no events half-injected.
5156 	 */
5157 	return (kvm_arch_interrupt_allowed(vcpu) &&
5158 		kvm_cpu_accept_dm_intr(vcpu) &&
5159 		!kvm_event_needs_reinjection(vcpu) &&
5160 		!kvm_is_exception_pending(vcpu));
5161 }
5162 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5163 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5164 				    struct kvm_interrupt *irq)
5165 {
5166 	if (irq->irq >= KVM_NR_INTERRUPTS)
5167 		return -EINVAL;
5168 
5169 	if (!irqchip_in_kernel(vcpu->kvm)) {
5170 		kvm_queue_interrupt(vcpu, irq->irq, false);
5171 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5172 		return 0;
5173 	}
5174 
5175 	/*
5176 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5177 	 * fail for in-kernel 8259.
5178 	 */
5179 	if (pic_in_kernel(vcpu->kvm))
5180 		return -ENXIO;
5181 
5182 	if (vcpu->arch.pending_external_vector != -1)
5183 		return -EEXIST;
5184 
5185 	vcpu->arch.pending_external_vector = irq->irq;
5186 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5187 	return 0;
5188 }
5189 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5190 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5191 {
5192 	kvm_inject_nmi(vcpu);
5193 
5194 	return 0;
5195 }
5196 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5197 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5198 					   struct kvm_tpr_access_ctl *tac)
5199 {
5200 	if (tac->flags)
5201 		return -EINVAL;
5202 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
5203 	return 0;
5204 }
5205 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5206 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5207 					u64 mcg_cap)
5208 {
5209 	int r;
5210 	unsigned bank_num = mcg_cap & 0xff, bank;
5211 
5212 	r = -EINVAL;
5213 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5214 		goto out;
5215 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5216 		goto out;
5217 	r = 0;
5218 	vcpu->arch.mcg_cap = mcg_cap;
5219 	/* Init IA32_MCG_CTL to all 1s */
5220 	if (mcg_cap & MCG_CTL_P)
5221 		vcpu->arch.mcg_ctl = ~(u64)0;
5222 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5223 	for (bank = 0; bank < bank_num; bank++) {
5224 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5225 		if (mcg_cap & MCG_CMCI_P)
5226 			vcpu->arch.mci_ctl2_banks[bank] = 0;
5227 	}
5228 
5229 	kvm_apic_after_set_mcg_cap(vcpu);
5230 
5231 	kvm_x86_call(setup_mce)(vcpu);
5232 out:
5233 	return r;
5234 }
5235 
5236 /*
5237  * Validate this is an UCNA (uncorrectable no action) error by checking the
5238  * MCG_STATUS and MCi_STATUS registers:
5239  * - none of the bits for Machine Check Exceptions are set
5240  * - both the VAL (valid) and UC (uncorrectable) bits are set
5241  * MCI_STATUS_PCC - Processor Context Corrupted
5242  * MCI_STATUS_S - Signaled as a Machine Check Exception
5243  * MCI_STATUS_AR - Software recoverable Action Required
5244  */
is_ucna(struct kvm_x86_mce * mce)5245 static bool is_ucna(struct kvm_x86_mce *mce)
5246 {
5247 	return	!mce->mcg_status &&
5248 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5249 		(mce->status & MCI_STATUS_VAL) &&
5250 		(mce->status & MCI_STATUS_UC);
5251 }
5252 
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5253 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5254 {
5255 	u64 mcg_cap = vcpu->arch.mcg_cap;
5256 
5257 	banks[1] = mce->status;
5258 	banks[2] = mce->addr;
5259 	banks[3] = mce->misc;
5260 	vcpu->arch.mcg_status = mce->mcg_status;
5261 
5262 	if (!(mcg_cap & MCG_CMCI_P) ||
5263 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5264 		return 0;
5265 
5266 	if (lapic_in_kernel(vcpu))
5267 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5268 
5269 	return 0;
5270 }
5271 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5272 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5273 				      struct kvm_x86_mce *mce)
5274 {
5275 	u64 mcg_cap = vcpu->arch.mcg_cap;
5276 	unsigned bank_num = mcg_cap & 0xff;
5277 	u64 *banks = vcpu->arch.mce_banks;
5278 
5279 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5280 		return -EINVAL;
5281 
5282 	banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5283 
5284 	if (is_ucna(mce))
5285 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5286 
5287 	/*
5288 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5289 	 * reporting is disabled
5290 	 */
5291 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5292 	    vcpu->arch.mcg_ctl != ~(u64)0)
5293 		return 0;
5294 	/*
5295 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5296 	 * reporting is disabled for the bank
5297 	 */
5298 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5299 		return 0;
5300 	if (mce->status & MCI_STATUS_UC) {
5301 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5302 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5303 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5304 			return 0;
5305 		}
5306 		if (banks[1] & MCI_STATUS_VAL)
5307 			mce->status |= MCI_STATUS_OVER;
5308 		banks[2] = mce->addr;
5309 		banks[3] = mce->misc;
5310 		vcpu->arch.mcg_status = mce->mcg_status;
5311 		banks[1] = mce->status;
5312 		kvm_queue_exception(vcpu, MC_VECTOR);
5313 	} else if (!(banks[1] & MCI_STATUS_VAL)
5314 		   || !(banks[1] & MCI_STATUS_UC)) {
5315 		if (banks[1] & MCI_STATUS_VAL)
5316 			mce->status |= MCI_STATUS_OVER;
5317 		banks[2] = mce->addr;
5318 		banks[3] = mce->misc;
5319 		banks[1] = mce->status;
5320 	} else
5321 		banks[1] |= MCI_STATUS_OVER;
5322 	return 0;
5323 }
5324 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5325 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5326 					       struct kvm_vcpu_events *events)
5327 {
5328 	struct kvm_queued_exception *ex;
5329 
5330 	process_nmi(vcpu);
5331 
5332 #ifdef CONFIG_KVM_SMM
5333 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
5334 		process_smi(vcpu);
5335 #endif
5336 
5337 	/*
5338 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
5339 	 * the only time there can be two queued exceptions is if there's a
5340 	 * non-exiting _injected_ exception, and a pending exiting exception.
5341 	 * In that case, ignore the VM-Exiting exception as it's an extension
5342 	 * of the injected exception.
5343 	 */
5344 	if (vcpu->arch.exception_vmexit.pending &&
5345 	    !vcpu->arch.exception.pending &&
5346 	    !vcpu->arch.exception.injected)
5347 		ex = &vcpu->arch.exception_vmexit;
5348 	else
5349 		ex = &vcpu->arch.exception;
5350 
5351 	/*
5352 	 * In guest mode, payload delivery should be deferred if the exception
5353 	 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5354 	 * intercepts #PF, ditto for DR6 and #DBs.  If the per-VM capability,
5355 	 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5356 	 * propagate the payload and so it cannot be safely deferred.  Deliver
5357 	 * the payload if the capability hasn't been requested.
5358 	 */
5359 	if (!vcpu->kvm->arch.exception_payload_enabled &&
5360 	    ex->pending && ex->has_payload)
5361 		kvm_deliver_exception_payload(vcpu, ex);
5362 
5363 	memset(events, 0, sizeof(*events));
5364 
5365 	/*
5366 	 * The API doesn't provide the instruction length for software
5367 	 * exceptions, so don't report them. As long as the guest RIP
5368 	 * isn't advanced, we should expect to encounter the exception
5369 	 * again.
5370 	 */
5371 	if (!kvm_exception_is_soft(ex->vector)) {
5372 		events->exception.injected = ex->injected;
5373 		events->exception.pending = ex->pending;
5374 		/*
5375 		 * For ABI compatibility, deliberately conflate
5376 		 * pending and injected exceptions when
5377 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5378 		 */
5379 		if (!vcpu->kvm->arch.exception_payload_enabled)
5380 			events->exception.injected |= ex->pending;
5381 	}
5382 	events->exception.nr = ex->vector;
5383 	events->exception.has_error_code = ex->has_error_code;
5384 	events->exception.error_code = ex->error_code;
5385 	events->exception_has_payload = ex->has_payload;
5386 	events->exception_payload = ex->payload;
5387 
5388 	events->interrupt.injected =
5389 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5390 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5391 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5392 
5393 	events->nmi.injected = vcpu->arch.nmi_injected;
5394 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5395 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5396 
5397 	/* events->sipi_vector is never valid when reporting to user space */
5398 
5399 #ifdef CONFIG_KVM_SMM
5400 	events->smi.smm = is_smm(vcpu);
5401 	events->smi.pending = vcpu->arch.smi_pending;
5402 	events->smi.smm_inside_nmi =
5403 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5404 #endif
5405 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5406 
5407 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5408 			 | KVM_VCPUEVENT_VALID_SHADOW
5409 			 | KVM_VCPUEVENT_VALID_SMM);
5410 	if (vcpu->kvm->arch.exception_payload_enabled)
5411 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5412 	if (vcpu->kvm->arch.triple_fault_event) {
5413 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5414 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5415 	}
5416 }
5417 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5418 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5419 					      struct kvm_vcpu_events *events)
5420 {
5421 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5422 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5423 			      | KVM_VCPUEVENT_VALID_SHADOW
5424 			      | KVM_VCPUEVENT_VALID_SMM
5425 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5426 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5427 		return -EINVAL;
5428 
5429 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5430 		if (!vcpu->kvm->arch.exception_payload_enabled)
5431 			return -EINVAL;
5432 		if (events->exception.pending)
5433 			events->exception.injected = 0;
5434 		else
5435 			events->exception_has_payload = 0;
5436 	} else {
5437 		events->exception.pending = 0;
5438 		events->exception_has_payload = 0;
5439 	}
5440 
5441 	if ((events->exception.injected || events->exception.pending) &&
5442 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5443 		return -EINVAL;
5444 
5445 	/* INITs are latched while in SMM */
5446 	if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5447 	    (events->smi.smm || events->smi.pending) &&
5448 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5449 		return -EINVAL;
5450 
5451 	process_nmi(vcpu);
5452 
5453 	/*
5454 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5455 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5456 	 * pending exceptions, already-injected exceptions are not subject to
5457 	 * intercpetion.  Note, userspace that conflates pending and injected
5458 	 * is hosed, and will incorrectly convert an injected exception into a
5459 	 * pending exception, which in turn may cause a spurious VM-Exit.
5460 	 */
5461 	vcpu->arch.exception_from_userspace = events->exception.pending;
5462 
5463 	vcpu->arch.exception_vmexit.pending = false;
5464 
5465 	vcpu->arch.exception.injected = events->exception.injected;
5466 	vcpu->arch.exception.pending = events->exception.pending;
5467 	vcpu->arch.exception.vector = events->exception.nr;
5468 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5469 	vcpu->arch.exception.error_code = events->exception.error_code;
5470 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5471 	vcpu->arch.exception.payload = events->exception_payload;
5472 
5473 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5474 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5475 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5476 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5477 		kvm_x86_call(set_interrupt_shadow)(vcpu,
5478 						   events->interrupt.shadow);
5479 
5480 	vcpu->arch.nmi_injected = events->nmi.injected;
5481 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5482 		vcpu->arch.nmi_pending = 0;
5483 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5484 		if (events->nmi.pending)
5485 			kvm_make_request(KVM_REQ_NMI, vcpu);
5486 	}
5487 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5488 
5489 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5490 	    lapic_in_kernel(vcpu))
5491 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5492 
5493 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5494 #ifdef CONFIG_KVM_SMM
5495 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5496 			kvm_leave_nested(vcpu);
5497 			kvm_smm_changed(vcpu, events->smi.smm);
5498 		}
5499 
5500 		vcpu->arch.smi_pending = events->smi.pending;
5501 
5502 		if (events->smi.smm) {
5503 			if (events->smi.smm_inside_nmi)
5504 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5505 			else
5506 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5507 		}
5508 
5509 #else
5510 		if (events->smi.smm || events->smi.pending ||
5511 		    events->smi.smm_inside_nmi)
5512 			return -EINVAL;
5513 #endif
5514 
5515 		if (lapic_in_kernel(vcpu)) {
5516 			if (events->smi.latched_init)
5517 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5518 			else
5519 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5520 		}
5521 	}
5522 
5523 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5524 		if (!vcpu->kvm->arch.triple_fault_event)
5525 			return -EINVAL;
5526 		if (events->triple_fault.pending)
5527 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5528 		else
5529 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5530 	}
5531 
5532 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5533 
5534 	return 0;
5535 }
5536 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5537 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5538 					    struct kvm_debugregs *dbgregs)
5539 {
5540 	unsigned int i;
5541 
5542 	if (vcpu->kvm->arch.has_protected_state &&
5543 	    vcpu->arch.guest_state_protected)
5544 		return -EINVAL;
5545 
5546 	memset(dbgregs, 0, sizeof(*dbgregs));
5547 
5548 	BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5549 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5550 		dbgregs->db[i] = vcpu->arch.db[i];
5551 
5552 	dbgregs->dr6 = vcpu->arch.dr6;
5553 	dbgregs->dr7 = vcpu->arch.dr7;
5554 	return 0;
5555 }
5556 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5557 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5558 					    struct kvm_debugregs *dbgregs)
5559 {
5560 	unsigned int i;
5561 
5562 	if (vcpu->kvm->arch.has_protected_state &&
5563 	    vcpu->arch.guest_state_protected)
5564 		return -EINVAL;
5565 
5566 	if (dbgregs->flags)
5567 		return -EINVAL;
5568 
5569 	if (!kvm_dr6_valid(dbgregs->dr6))
5570 		return -EINVAL;
5571 	if (!kvm_dr7_valid(dbgregs->dr7))
5572 		return -EINVAL;
5573 
5574 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5575 		vcpu->arch.db[i] = dbgregs->db[i];
5576 
5577 	kvm_update_dr0123(vcpu);
5578 	vcpu->arch.dr6 = dbgregs->dr6;
5579 	vcpu->arch.dr7 = dbgregs->dr7;
5580 	kvm_update_dr7(vcpu);
5581 
5582 	return 0;
5583 }
5584 
5585 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5586 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5587 					 u8 *state, unsigned int size)
5588 {
5589 	/*
5590 	 * Only copy state for features that are enabled for the guest.  The
5591 	 * state itself isn't problematic, but setting bits in the header for
5592 	 * features that are supported in *this* host but not exposed to the
5593 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5594 	 * compatible host without the features that are NOT exposed to the
5595 	 * guest.
5596 	 *
5597 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5598 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5599 	 * supported by the host.
5600 	 */
5601 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5602 			     XFEATURE_MASK_FPSSE;
5603 
5604 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5605 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5606 
5607 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5608 				       supported_xcr0, vcpu->arch.pkru);
5609 	return 0;
5610 }
5611 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5612 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5613 					struct kvm_xsave *guest_xsave)
5614 {
5615 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5616 					     sizeof(guest_xsave->region));
5617 }
5618 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5619 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5620 					struct kvm_xsave *guest_xsave)
5621 {
5622 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5623 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5624 
5625 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5626 					      guest_xsave->region,
5627 					      kvm_caps.supported_xcr0,
5628 					      &vcpu->arch.pkru);
5629 }
5630 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5631 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5632 				       struct kvm_xcrs *guest_xcrs)
5633 {
5634 	if (vcpu->kvm->arch.has_protected_state &&
5635 	    vcpu->arch.guest_state_protected)
5636 		return -EINVAL;
5637 
5638 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5639 		guest_xcrs->nr_xcrs = 0;
5640 		return 0;
5641 	}
5642 
5643 	guest_xcrs->nr_xcrs = 1;
5644 	guest_xcrs->flags = 0;
5645 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5646 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5647 	return 0;
5648 }
5649 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5650 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5651 				       struct kvm_xcrs *guest_xcrs)
5652 {
5653 	int i, r = 0;
5654 
5655 	if (vcpu->kvm->arch.has_protected_state &&
5656 	    vcpu->arch.guest_state_protected)
5657 		return -EINVAL;
5658 
5659 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5660 		return -EINVAL;
5661 
5662 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5663 		return -EINVAL;
5664 
5665 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5666 		/* Only support XCR0 currently */
5667 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5668 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5669 				guest_xcrs->xcrs[i].value);
5670 			break;
5671 		}
5672 	if (r)
5673 		r = -EINVAL;
5674 	return r;
5675 }
5676 
5677 /*
5678  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5679  * stopped by the hypervisor.  This function will be called from the host only.
5680  * EINVAL is returned when the host attempts to set the flag for a guest that
5681  * does not support pv clocks.
5682  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5683 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5684 {
5685 	if (!vcpu->arch.pv_time.active)
5686 		return -EINVAL;
5687 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5688 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5689 	return 0;
5690 }
5691 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5692 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5693 				 struct kvm_device_attr *attr)
5694 {
5695 	int r;
5696 
5697 	switch (attr->attr) {
5698 	case KVM_VCPU_TSC_OFFSET:
5699 		r = 0;
5700 		break;
5701 	default:
5702 		r = -ENXIO;
5703 	}
5704 
5705 	return r;
5706 }
5707 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5708 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5709 				 struct kvm_device_attr *attr)
5710 {
5711 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5712 	int r;
5713 
5714 	switch (attr->attr) {
5715 	case KVM_VCPU_TSC_OFFSET:
5716 		r = -EFAULT;
5717 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5718 			break;
5719 		r = 0;
5720 		break;
5721 	default:
5722 		r = -ENXIO;
5723 	}
5724 
5725 	return r;
5726 }
5727 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5728 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5729 				 struct kvm_device_attr *attr)
5730 {
5731 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5732 	struct kvm *kvm = vcpu->kvm;
5733 	int r;
5734 
5735 	switch (attr->attr) {
5736 	case KVM_VCPU_TSC_OFFSET: {
5737 		u64 offset, tsc, ns;
5738 		unsigned long flags;
5739 		bool matched;
5740 
5741 		r = -EFAULT;
5742 		if (get_user(offset, uaddr))
5743 			break;
5744 
5745 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5746 
5747 		matched = (vcpu->arch.virtual_tsc_khz &&
5748 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5749 			   kvm->arch.last_tsc_offset == offset);
5750 
5751 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5752 		ns = get_kvmclock_base_ns();
5753 
5754 		kvm->arch.user_set_tsc = true;
5755 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5756 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5757 
5758 		r = 0;
5759 		break;
5760 	}
5761 	default:
5762 		r = -ENXIO;
5763 	}
5764 
5765 	return r;
5766 }
5767 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5768 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5769 				      unsigned int ioctl,
5770 				      void __user *argp)
5771 {
5772 	struct kvm_device_attr attr;
5773 	int r;
5774 
5775 	if (copy_from_user(&attr, argp, sizeof(attr)))
5776 		return -EFAULT;
5777 
5778 	if (attr.group != KVM_VCPU_TSC_CTRL)
5779 		return -ENXIO;
5780 
5781 	switch (ioctl) {
5782 	case KVM_HAS_DEVICE_ATTR:
5783 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
5784 		break;
5785 	case KVM_GET_DEVICE_ATTR:
5786 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
5787 		break;
5788 	case KVM_SET_DEVICE_ATTR:
5789 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
5790 		break;
5791 	}
5792 
5793 	return r;
5794 }
5795 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5796 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5797 				     struct kvm_enable_cap *cap)
5798 {
5799 	if (cap->flags)
5800 		return -EINVAL;
5801 
5802 	switch (cap->cap) {
5803 #ifdef CONFIG_KVM_HYPERV
5804 	case KVM_CAP_HYPERV_SYNIC2:
5805 		if (cap->args[0])
5806 			return -EINVAL;
5807 		fallthrough;
5808 
5809 	case KVM_CAP_HYPERV_SYNIC:
5810 		if (!irqchip_in_kernel(vcpu->kvm))
5811 			return -EINVAL;
5812 		return kvm_hv_activate_synic(vcpu, cap->cap ==
5813 					     KVM_CAP_HYPERV_SYNIC2);
5814 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5815 		{
5816 			int r;
5817 			uint16_t vmcs_version;
5818 			void __user *user_ptr;
5819 
5820 			if (!kvm_x86_ops.nested_ops->enable_evmcs)
5821 				return -ENOTTY;
5822 			r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5823 			if (!r) {
5824 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
5825 				if (copy_to_user(user_ptr, &vmcs_version,
5826 						 sizeof(vmcs_version)))
5827 					r = -EFAULT;
5828 			}
5829 			return r;
5830 		}
5831 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5832 		if (!kvm_x86_ops.enable_l2_tlb_flush)
5833 			return -ENOTTY;
5834 
5835 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
5836 
5837 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
5838 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5839 #endif
5840 
5841 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5842 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
5843 		if (vcpu->arch.pv_cpuid.enforce)
5844 			kvm_update_pv_runtime(vcpu);
5845 
5846 		return 0;
5847 	default:
5848 		return -EINVAL;
5849 	}
5850 }
5851 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5852 long kvm_arch_vcpu_ioctl(struct file *filp,
5853 			 unsigned int ioctl, unsigned long arg)
5854 {
5855 	struct kvm_vcpu *vcpu = filp->private_data;
5856 	void __user *argp = (void __user *)arg;
5857 	int r;
5858 	union {
5859 		struct kvm_sregs2 *sregs2;
5860 		struct kvm_lapic_state *lapic;
5861 		struct kvm_xsave *xsave;
5862 		struct kvm_xcrs *xcrs;
5863 		void *buffer;
5864 	} u;
5865 
5866 	vcpu_load(vcpu);
5867 
5868 	u.buffer = NULL;
5869 	switch (ioctl) {
5870 	case KVM_GET_LAPIC: {
5871 		r = -EINVAL;
5872 		if (!lapic_in_kernel(vcpu))
5873 			goto out;
5874 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
5875 
5876 		r = -ENOMEM;
5877 		if (!u.lapic)
5878 			goto out;
5879 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5880 		if (r)
5881 			goto out;
5882 		r = -EFAULT;
5883 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5884 			goto out;
5885 		r = 0;
5886 		break;
5887 	}
5888 	case KVM_SET_LAPIC: {
5889 		r = -EINVAL;
5890 		if (!lapic_in_kernel(vcpu))
5891 			goto out;
5892 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
5893 		if (IS_ERR(u.lapic)) {
5894 			r = PTR_ERR(u.lapic);
5895 			goto out_nofree;
5896 		}
5897 
5898 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5899 		break;
5900 	}
5901 	case KVM_INTERRUPT: {
5902 		struct kvm_interrupt irq;
5903 
5904 		r = -EFAULT;
5905 		if (copy_from_user(&irq, argp, sizeof(irq)))
5906 			goto out;
5907 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5908 		break;
5909 	}
5910 	case KVM_NMI: {
5911 		r = kvm_vcpu_ioctl_nmi(vcpu);
5912 		break;
5913 	}
5914 	case KVM_SMI: {
5915 		r = kvm_inject_smi(vcpu);
5916 		break;
5917 	}
5918 	case KVM_SET_CPUID: {
5919 		struct kvm_cpuid __user *cpuid_arg = argp;
5920 		struct kvm_cpuid cpuid;
5921 
5922 		r = -EFAULT;
5923 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5924 			goto out;
5925 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5926 		break;
5927 	}
5928 	case KVM_SET_CPUID2: {
5929 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5930 		struct kvm_cpuid2 cpuid;
5931 
5932 		r = -EFAULT;
5933 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5934 			goto out;
5935 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5936 					      cpuid_arg->entries);
5937 		break;
5938 	}
5939 	case KVM_GET_CPUID2: {
5940 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5941 		struct kvm_cpuid2 cpuid;
5942 
5943 		r = -EFAULT;
5944 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5945 			goto out;
5946 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5947 					      cpuid_arg->entries);
5948 		if (r)
5949 			goto out;
5950 		r = -EFAULT;
5951 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5952 			goto out;
5953 		r = 0;
5954 		break;
5955 	}
5956 	case KVM_GET_MSRS: {
5957 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5958 		r = msr_io(vcpu, argp, do_get_msr, 1);
5959 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5960 		break;
5961 	}
5962 	case KVM_SET_MSRS: {
5963 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
5964 		r = msr_io(vcpu, argp, do_set_msr, 0);
5965 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5966 		break;
5967 	}
5968 	case KVM_TPR_ACCESS_REPORTING: {
5969 		struct kvm_tpr_access_ctl tac;
5970 
5971 		r = -EFAULT;
5972 		if (copy_from_user(&tac, argp, sizeof(tac)))
5973 			goto out;
5974 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5975 		if (r)
5976 			goto out;
5977 		r = -EFAULT;
5978 		if (copy_to_user(argp, &tac, sizeof(tac)))
5979 			goto out;
5980 		r = 0;
5981 		break;
5982 	};
5983 	case KVM_SET_VAPIC_ADDR: {
5984 		struct kvm_vapic_addr va;
5985 		int idx;
5986 
5987 		r = -EINVAL;
5988 		if (!lapic_in_kernel(vcpu))
5989 			goto out;
5990 		r = -EFAULT;
5991 		if (copy_from_user(&va, argp, sizeof(va)))
5992 			goto out;
5993 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5994 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
5995 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5996 		break;
5997 	}
5998 	case KVM_X86_SETUP_MCE: {
5999 		u64 mcg_cap;
6000 
6001 		r = -EFAULT;
6002 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6003 			goto out;
6004 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6005 		break;
6006 	}
6007 	case KVM_X86_SET_MCE: {
6008 		struct kvm_x86_mce mce;
6009 
6010 		r = -EFAULT;
6011 		if (copy_from_user(&mce, argp, sizeof(mce)))
6012 			goto out;
6013 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6014 		break;
6015 	}
6016 	case KVM_GET_VCPU_EVENTS: {
6017 		struct kvm_vcpu_events events;
6018 
6019 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6020 
6021 		r = -EFAULT;
6022 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6023 			break;
6024 		r = 0;
6025 		break;
6026 	}
6027 	case KVM_SET_VCPU_EVENTS: {
6028 		struct kvm_vcpu_events events;
6029 
6030 		r = -EFAULT;
6031 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6032 			break;
6033 
6034 		kvm_vcpu_srcu_read_lock(vcpu);
6035 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6036 		kvm_vcpu_srcu_read_unlock(vcpu);
6037 		break;
6038 	}
6039 	case KVM_GET_DEBUGREGS: {
6040 		struct kvm_debugregs dbgregs;
6041 
6042 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6043 		if (r < 0)
6044 			break;
6045 
6046 		r = -EFAULT;
6047 		if (copy_to_user(argp, &dbgregs,
6048 				 sizeof(struct kvm_debugregs)))
6049 			break;
6050 		r = 0;
6051 		break;
6052 	}
6053 	case KVM_SET_DEBUGREGS: {
6054 		struct kvm_debugregs dbgregs;
6055 
6056 		r = -EFAULT;
6057 		if (copy_from_user(&dbgregs, argp,
6058 				   sizeof(struct kvm_debugregs)))
6059 			break;
6060 
6061 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6062 		break;
6063 	}
6064 	case KVM_GET_XSAVE: {
6065 		r = -EINVAL;
6066 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6067 			break;
6068 
6069 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6070 		r = -ENOMEM;
6071 		if (!u.xsave)
6072 			break;
6073 
6074 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6075 		if (r < 0)
6076 			break;
6077 
6078 		r = -EFAULT;
6079 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6080 			break;
6081 		r = 0;
6082 		break;
6083 	}
6084 	case KVM_SET_XSAVE: {
6085 		int size = vcpu->arch.guest_fpu.uabi_size;
6086 
6087 		u.xsave = memdup_user(argp, size);
6088 		if (IS_ERR(u.xsave)) {
6089 			r = PTR_ERR(u.xsave);
6090 			goto out_nofree;
6091 		}
6092 
6093 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6094 		break;
6095 	}
6096 
6097 	case KVM_GET_XSAVE2: {
6098 		int size = vcpu->arch.guest_fpu.uabi_size;
6099 
6100 		u.xsave = kzalloc(size, GFP_KERNEL);
6101 		r = -ENOMEM;
6102 		if (!u.xsave)
6103 			break;
6104 
6105 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6106 		if (r < 0)
6107 			break;
6108 
6109 		r = -EFAULT;
6110 		if (copy_to_user(argp, u.xsave, size))
6111 			break;
6112 
6113 		r = 0;
6114 		break;
6115 	}
6116 
6117 	case KVM_GET_XCRS: {
6118 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6119 		r = -ENOMEM;
6120 		if (!u.xcrs)
6121 			break;
6122 
6123 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6124 		if (r < 0)
6125 			break;
6126 
6127 		r = -EFAULT;
6128 		if (copy_to_user(argp, u.xcrs,
6129 				 sizeof(struct kvm_xcrs)))
6130 			break;
6131 		r = 0;
6132 		break;
6133 	}
6134 	case KVM_SET_XCRS: {
6135 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6136 		if (IS_ERR(u.xcrs)) {
6137 			r = PTR_ERR(u.xcrs);
6138 			goto out_nofree;
6139 		}
6140 
6141 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6142 		break;
6143 	}
6144 	case KVM_SET_TSC_KHZ: {
6145 		u32 user_tsc_khz;
6146 
6147 		r = -EINVAL;
6148 		user_tsc_khz = (u32)arg;
6149 
6150 		if (kvm_caps.has_tsc_control &&
6151 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6152 			goto out;
6153 
6154 		if (user_tsc_khz == 0)
6155 			user_tsc_khz = tsc_khz;
6156 
6157 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6158 			r = 0;
6159 
6160 		goto out;
6161 	}
6162 	case KVM_GET_TSC_KHZ: {
6163 		r = vcpu->arch.virtual_tsc_khz;
6164 		goto out;
6165 	}
6166 	case KVM_KVMCLOCK_CTRL: {
6167 		r = kvm_set_guest_paused(vcpu);
6168 		goto out;
6169 	}
6170 	case KVM_ENABLE_CAP: {
6171 		struct kvm_enable_cap cap;
6172 
6173 		r = -EFAULT;
6174 		if (copy_from_user(&cap, argp, sizeof(cap)))
6175 			goto out;
6176 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6177 		break;
6178 	}
6179 	case KVM_GET_NESTED_STATE: {
6180 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6181 		u32 user_data_size;
6182 
6183 		r = -EINVAL;
6184 		if (!kvm_x86_ops.nested_ops->get_state)
6185 			break;
6186 
6187 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6188 		r = -EFAULT;
6189 		if (get_user(user_data_size, &user_kvm_nested_state->size))
6190 			break;
6191 
6192 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6193 						     user_data_size);
6194 		if (r < 0)
6195 			break;
6196 
6197 		if (r > user_data_size) {
6198 			if (put_user(r, &user_kvm_nested_state->size))
6199 				r = -EFAULT;
6200 			else
6201 				r = -E2BIG;
6202 			break;
6203 		}
6204 
6205 		r = 0;
6206 		break;
6207 	}
6208 	case KVM_SET_NESTED_STATE: {
6209 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6210 		struct kvm_nested_state kvm_state;
6211 		int idx;
6212 
6213 		r = -EINVAL;
6214 		if (!kvm_x86_ops.nested_ops->set_state)
6215 			break;
6216 
6217 		r = -EFAULT;
6218 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6219 			break;
6220 
6221 		r = -EINVAL;
6222 		if (kvm_state.size < sizeof(kvm_state))
6223 			break;
6224 
6225 		if (kvm_state.flags &
6226 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6227 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6228 		      | KVM_STATE_NESTED_GIF_SET))
6229 			break;
6230 
6231 		/* nested_run_pending implies guest_mode.  */
6232 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6233 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6234 			break;
6235 
6236 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6237 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6238 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6239 		break;
6240 	}
6241 #ifdef CONFIG_KVM_HYPERV
6242 	case KVM_GET_SUPPORTED_HV_CPUID:
6243 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6244 		break;
6245 #endif
6246 #ifdef CONFIG_KVM_XEN
6247 	case KVM_XEN_VCPU_GET_ATTR: {
6248 		struct kvm_xen_vcpu_attr xva;
6249 
6250 		r = -EFAULT;
6251 		if (copy_from_user(&xva, argp, sizeof(xva)))
6252 			goto out;
6253 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6254 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6255 			r = -EFAULT;
6256 		break;
6257 	}
6258 	case KVM_XEN_VCPU_SET_ATTR: {
6259 		struct kvm_xen_vcpu_attr xva;
6260 
6261 		r = -EFAULT;
6262 		if (copy_from_user(&xva, argp, sizeof(xva)))
6263 			goto out;
6264 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6265 		break;
6266 	}
6267 #endif
6268 	case KVM_GET_SREGS2: {
6269 		r = -EINVAL;
6270 		if (vcpu->kvm->arch.has_protected_state &&
6271 		    vcpu->arch.guest_state_protected)
6272 			goto out;
6273 
6274 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6275 		r = -ENOMEM;
6276 		if (!u.sregs2)
6277 			goto out;
6278 		__get_sregs2(vcpu, u.sregs2);
6279 		r = -EFAULT;
6280 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6281 			goto out;
6282 		r = 0;
6283 		break;
6284 	}
6285 	case KVM_SET_SREGS2: {
6286 		r = -EINVAL;
6287 		if (vcpu->kvm->arch.has_protected_state &&
6288 		    vcpu->arch.guest_state_protected)
6289 			goto out;
6290 
6291 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6292 		if (IS_ERR(u.sregs2)) {
6293 			r = PTR_ERR(u.sregs2);
6294 			u.sregs2 = NULL;
6295 			goto out;
6296 		}
6297 		r = __set_sregs2(vcpu, u.sregs2);
6298 		break;
6299 	}
6300 	case KVM_HAS_DEVICE_ATTR:
6301 	case KVM_GET_DEVICE_ATTR:
6302 	case KVM_SET_DEVICE_ATTR:
6303 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6304 		break;
6305 	default:
6306 		r = -EINVAL;
6307 	}
6308 out:
6309 	kfree(u.buffer);
6310 out_nofree:
6311 	vcpu_put(vcpu);
6312 	return r;
6313 }
6314 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6315 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6316 {
6317 	return VM_FAULT_SIGBUS;
6318 }
6319 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6320 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6321 {
6322 	int ret;
6323 
6324 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
6325 		return -EINVAL;
6326 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6327 	return ret;
6328 }
6329 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6330 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6331 					      u64 ident_addr)
6332 {
6333 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6334 }
6335 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6336 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6337 					 unsigned long kvm_nr_mmu_pages)
6338 {
6339 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6340 		return -EINVAL;
6341 
6342 	mutex_lock(&kvm->slots_lock);
6343 
6344 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6345 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6346 
6347 	mutex_unlock(&kvm->slots_lock);
6348 	return 0;
6349 }
6350 
kvm_vm_ioctl_get_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6351 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6352 {
6353 	struct kvm_pic *pic = kvm->arch.vpic;
6354 	int r;
6355 
6356 	r = 0;
6357 	switch (chip->chip_id) {
6358 	case KVM_IRQCHIP_PIC_MASTER:
6359 		memcpy(&chip->chip.pic, &pic->pics[0],
6360 			sizeof(struct kvm_pic_state));
6361 		break;
6362 	case KVM_IRQCHIP_PIC_SLAVE:
6363 		memcpy(&chip->chip.pic, &pic->pics[1],
6364 			sizeof(struct kvm_pic_state));
6365 		break;
6366 	case KVM_IRQCHIP_IOAPIC:
6367 		kvm_get_ioapic(kvm, &chip->chip.ioapic);
6368 		break;
6369 	default:
6370 		r = -EINVAL;
6371 		break;
6372 	}
6373 	return r;
6374 }
6375 
kvm_vm_ioctl_set_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6376 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6377 {
6378 	struct kvm_pic *pic = kvm->arch.vpic;
6379 	int r;
6380 
6381 	r = 0;
6382 	switch (chip->chip_id) {
6383 	case KVM_IRQCHIP_PIC_MASTER:
6384 		spin_lock(&pic->lock);
6385 		memcpy(&pic->pics[0], &chip->chip.pic,
6386 			sizeof(struct kvm_pic_state));
6387 		spin_unlock(&pic->lock);
6388 		break;
6389 	case KVM_IRQCHIP_PIC_SLAVE:
6390 		spin_lock(&pic->lock);
6391 		memcpy(&pic->pics[1], &chip->chip.pic,
6392 			sizeof(struct kvm_pic_state));
6393 		spin_unlock(&pic->lock);
6394 		break;
6395 	case KVM_IRQCHIP_IOAPIC:
6396 		kvm_set_ioapic(kvm, &chip->chip.ioapic);
6397 		break;
6398 	default:
6399 		r = -EINVAL;
6400 		break;
6401 	}
6402 	kvm_pic_update_irq(pic);
6403 	return r;
6404 }
6405 
kvm_vm_ioctl_get_pit(struct kvm * kvm,struct kvm_pit_state * ps)6406 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6407 {
6408 	struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6409 
6410 	BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6411 
6412 	mutex_lock(&kps->lock);
6413 	memcpy(ps, &kps->channels, sizeof(*ps));
6414 	mutex_unlock(&kps->lock);
6415 	return 0;
6416 }
6417 
kvm_vm_ioctl_set_pit(struct kvm * kvm,struct kvm_pit_state * ps)6418 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6419 {
6420 	int i;
6421 	struct kvm_pit *pit = kvm->arch.vpit;
6422 
6423 	mutex_lock(&pit->pit_state.lock);
6424 	memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6425 	for (i = 0; i < 3; i++)
6426 		kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6427 	mutex_unlock(&pit->pit_state.lock);
6428 	return 0;
6429 }
6430 
kvm_vm_ioctl_get_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6431 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6432 {
6433 	mutex_lock(&kvm->arch.vpit->pit_state.lock);
6434 	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6435 		sizeof(ps->channels));
6436 	ps->flags = kvm->arch.vpit->pit_state.flags;
6437 	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6438 	memset(&ps->reserved, 0, sizeof(ps->reserved));
6439 	return 0;
6440 }
6441 
kvm_vm_ioctl_set_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6442 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6443 {
6444 	int start = 0;
6445 	int i;
6446 	u32 prev_legacy, cur_legacy;
6447 	struct kvm_pit *pit = kvm->arch.vpit;
6448 
6449 	mutex_lock(&pit->pit_state.lock);
6450 	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6451 	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6452 	if (!prev_legacy && cur_legacy)
6453 		start = 1;
6454 	memcpy(&pit->pit_state.channels, &ps->channels,
6455 	       sizeof(pit->pit_state.channels));
6456 	pit->pit_state.flags = ps->flags;
6457 	for (i = 0; i < 3; i++)
6458 		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6459 				   start && i == 0);
6460 	mutex_unlock(&pit->pit_state.lock);
6461 	return 0;
6462 }
6463 
kvm_vm_ioctl_reinject(struct kvm * kvm,struct kvm_reinject_control * control)6464 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6465 				 struct kvm_reinject_control *control)
6466 {
6467 	struct kvm_pit *pit = kvm->arch.vpit;
6468 
6469 	/* pit->pit_state.lock was overloaded to prevent userspace from getting
6470 	 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6471 	 * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
6472 	 */
6473 	mutex_lock(&pit->pit_state.lock);
6474 	kvm_pit_set_reinject(pit, control->pit_reinject);
6475 	mutex_unlock(&pit->pit_state.lock);
6476 
6477 	return 0;
6478 }
6479 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6480 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6481 {
6482 
6483 	/*
6484 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6485 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6486 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6487 	 * VM-Exit.
6488 	 */
6489 	struct kvm_vcpu *vcpu;
6490 	unsigned long i;
6491 
6492 	if (!kvm_x86_ops.cpu_dirty_log_size)
6493 		return;
6494 
6495 	kvm_for_each_vcpu(i, vcpu, kvm)
6496 		kvm_vcpu_kick(vcpu);
6497 }
6498 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_event,bool line_status)6499 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6500 			bool line_status)
6501 {
6502 	if (!irqchip_in_kernel(kvm))
6503 		return -ENXIO;
6504 
6505 	irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6506 					irq_event->irq, irq_event->level,
6507 					line_status);
6508 	return 0;
6509 }
6510 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6511 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6512 			    struct kvm_enable_cap *cap)
6513 {
6514 	int r;
6515 
6516 	if (cap->flags)
6517 		return -EINVAL;
6518 
6519 	switch (cap->cap) {
6520 	case KVM_CAP_DISABLE_QUIRKS2:
6521 		r = -EINVAL;
6522 		if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6523 			break;
6524 		fallthrough;
6525 	case KVM_CAP_DISABLE_QUIRKS:
6526 		kvm->arch.disabled_quirks = cap->args[0];
6527 		r = 0;
6528 		break;
6529 	case KVM_CAP_SPLIT_IRQCHIP: {
6530 		mutex_lock(&kvm->lock);
6531 		r = -EINVAL;
6532 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6533 			goto split_irqchip_unlock;
6534 		r = -EEXIST;
6535 		if (irqchip_in_kernel(kvm))
6536 			goto split_irqchip_unlock;
6537 		if (kvm->created_vcpus)
6538 			goto split_irqchip_unlock;
6539 		/* Pairs with irqchip_in_kernel. */
6540 		smp_wmb();
6541 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6542 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6543 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6544 		r = 0;
6545 split_irqchip_unlock:
6546 		mutex_unlock(&kvm->lock);
6547 		break;
6548 	}
6549 	case KVM_CAP_X2APIC_API:
6550 		r = -EINVAL;
6551 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6552 			break;
6553 
6554 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6555 			kvm->arch.x2apic_format = true;
6556 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6557 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6558 
6559 		r = 0;
6560 		break;
6561 	case KVM_CAP_X86_DISABLE_EXITS:
6562 		r = -EINVAL;
6563 		if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6564 			break;
6565 
6566 		if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6567 			kvm->arch.pause_in_guest = true;
6568 
6569 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6570 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6571 
6572 		if (!mitigate_smt_rsb) {
6573 			if (boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible() &&
6574 			    (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6575 				pr_warn_once(SMT_RSB_MSG);
6576 
6577 			if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6578 			    kvm_can_mwait_in_guest())
6579 				kvm->arch.mwait_in_guest = true;
6580 			if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6581 				kvm->arch.hlt_in_guest = true;
6582 			if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6583 				kvm->arch.cstate_in_guest = true;
6584 		}
6585 
6586 		r = 0;
6587 		break;
6588 	case KVM_CAP_MSR_PLATFORM_INFO:
6589 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6590 		r = 0;
6591 		break;
6592 	case KVM_CAP_EXCEPTION_PAYLOAD:
6593 		kvm->arch.exception_payload_enabled = cap->args[0];
6594 		r = 0;
6595 		break;
6596 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6597 		kvm->arch.triple_fault_event = cap->args[0];
6598 		r = 0;
6599 		break;
6600 	case KVM_CAP_X86_USER_SPACE_MSR:
6601 		r = -EINVAL;
6602 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6603 			break;
6604 		kvm->arch.user_space_msr_mask = cap->args[0];
6605 		r = 0;
6606 		break;
6607 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6608 		r = -EINVAL;
6609 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6610 			break;
6611 
6612 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6613 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6614 			break;
6615 
6616 		if (kvm_caps.has_bus_lock_exit &&
6617 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6618 			kvm->arch.bus_lock_detection_enabled = true;
6619 		r = 0;
6620 		break;
6621 #ifdef CONFIG_X86_SGX_KVM
6622 	case KVM_CAP_SGX_ATTRIBUTE: {
6623 		unsigned long allowed_attributes = 0;
6624 
6625 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6626 		if (r)
6627 			break;
6628 
6629 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6630 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6631 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6632 			kvm->arch.sgx_provisioning_allowed = true;
6633 		else
6634 			r = -EINVAL;
6635 		break;
6636 	}
6637 #endif
6638 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6639 		r = -EINVAL;
6640 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6641 			break;
6642 
6643 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6644 		break;
6645 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6646 		r = -EINVAL;
6647 		if (!kvm_x86_ops.vm_move_enc_context_from)
6648 			break;
6649 
6650 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6651 		break;
6652 	case KVM_CAP_EXIT_HYPERCALL:
6653 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6654 			r = -EINVAL;
6655 			break;
6656 		}
6657 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6658 		r = 0;
6659 		break;
6660 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6661 		r = -EINVAL;
6662 		if (cap->args[0] & ~1)
6663 			break;
6664 		kvm->arch.exit_on_emulation_error = cap->args[0];
6665 		r = 0;
6666 		break;
6667 	case KVM_CAP_PMU_CAPABILITY:
6668 		r = -EINVAL;
6669 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6670 			break;
6671 
6672 		mutex_lock(&kvm->lock);
6673 		if (!kvm->created_vcpus) {
6674 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6675 			r = 0;
6676 		}
6677 		mutex_unlock(&kvm->lock);
6678 		break;
6679 	case KVM_CAP_MAX_VCPU_ID:
6680 		r = -EINVAL;
6681 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6682 			break;
6683 
6684 		mutex_lock(&kvm->lock);
6685 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6686 			;
6687 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6688 			r = 0;
6689 		} else if (!kvm->arch.max_vcpu_ids) {
6690 			kvm->arch.max_vcpu_ids = cap->args[0];
6691 			r = 0;
6692 		}
6693 		mutex_unlock(&kvm->lock);
6694 		break;
6695 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6696 		r = -EINVAL;
6697 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6698 			break;
6699 		if (!kvm_caps.has_notify_vmexit)
6700 			break;
6701 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6702 			break;
6703 		mutex_lock(&kvm->lock);
6704 		if (!kvm->created_vcpus) {
6705 			kvm->arch.notify_window = cap->args[0] >> 32;
6706 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6707 			r = 0;
6708 		}
6709 		mutex_unlock(&kvm->lock);
6710 		break;
6711 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6712 		r = -EINVAL;
6713 
6714 		/*
6715 		 * Since the risk of disabling NX hugepages is a guest crashing
6716 		 * the system, ensure the userspace process has permission to
6717 		 * reboot the system.
6718 		 *
6719 		 * Note that unlike the reboot() syscall, the process must have
6720 		 * this capability in the root namespace because exposing
6721 		 * /dev/kvm into a container does not limit the scope of the
6722 		 * iTLB multihit bug to that container. In other words,
6723 		 * this must use capable(), not ns_capable().
6724 		 */
6725 		if (!capable(CAP_SYS_BOOT)) {
6726 			r = -EPERM;
6727 			break;
6728 		}
6729 
6730 		if (cap->args[0])
6731 			break;
6732 
6733 		mutex_lock(&kvm->lock);
6734 		if (!kvm->created_vcpus) {
6735 			kvm->arch.disable_nx_huge_pages = true;
6736 			r = 0;
6737 		}
6738 		mutex_unlock(&kvm->lock);
6739 		break;
6740 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6741 		u64 bus_cycle_ns = cap->args[0];
6742 		u64 unused;
6743 
6744 		/*
6745 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
6746 		 * divide value that can be programmed in APIC_TDCR.
6747 		 */
6748 		r = -EINVAL;
6749 		if (!bus_cycle_ns ||
6750 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6751 			break;
6752 
6753 		r = 0;
6754 		mutex_lock(&kvm->lock);
6755 		if (!irqchip_in_kernel(kvm))
6756 			r = -ENXIO;
6757 		else if (kvm->created_vcpus)
6758 			r = -EINVAL;
6759 		else
6760 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6761 		mutex_unlock(&kvm->lock);
6762 		break;
6763 	}
6764 	default:
6765 		r = -EINVAL;
6766 		break;
6767 	}
6768 	return r;
6769 }
6770 
kvm_alloc_msr_filter(bool default_allow)6771 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6772 {
6773 	struct kvm_x86_msr_filter *msr_filter;
6774 
6775 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6776 	if (!msr_filter)
6777 		return NULL;
6778 
6779 	msr_filter->default_allow = default_allow;
6780 	return msr_filter;
6781 }
6782 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6783 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6784 {
6785 	u32 i;
6786 
6787 	if (!msr_filter)
6788 		return;
6789 
6790 	for (i = 0; i < msr_filter->count; i++)
6791 		kfree(msr_filter->ranges[i].bitmap);
6792 
6793 	kfree(msr_filter);
6794 }
6795 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6796 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6797 			      struct kvm_msr_filter_range *user_range)
6798 {
6799 	unsigned long *bitmap;
6800 	size_t bitmap_size;
6801 
6802 	if (!user_range->nmsrs)
6803 		return 0;
6804 
6805 	if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6806 		return -EINVAL;
6807 
6808 	if (!user_range->flags)
6809 		return -EINVAL;
6810 
6811 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6812 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6813 		return -EINVAL;
6814 
6815 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6816 	if (IS_ERR(bitmap))
6817 		return PTR_ERR(bitmap);
6818 
6819 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6820 		.flags = user_range->flags,
6821 		.base = user_range->base,
6822 		.nmsrs = user_range->nmsrs,
6823 		.bitmap = bitmap,
6824 	};
6825 
6826 	msr_filter->count++;
6827 	return 0;
6828 }
6829 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)6830 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6831 				       struct kvm_msr_filter *filter)
6832 {
6833 	struct kvm_x86_msr_filter *new_filter, *old_filter;
6834 	bool default_allow;
6835 	bool empty = true;
6836 	int r;
6837 	u32 i;
6838 
6839 	if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
6840 		return -EINVAL;
6841 
6842 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6843 		empty &= !filter->ranges[i].nmsrs;
6844 
6845 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6846 	if (empty && !default_allow)
6847 		return -EINVAL;
6848 
6849 	new_filter = kvm_alloc_msr_filter(default_allow);
6850 	if (!new_filter)
6851 		return -ENOMEM;
6852 
6853 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6854 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6855 		if (r) {
6856 			kvm_free_msr_filter(new_filter);
6857 			return r;
6858 		}
6859 	}
6860 
6861 	mutex_lock(&kvm->lock);
6862 	old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6863 					 mutex_is_locked(&kvm->lock));
6864 	mutex_unlock(&kvm->lock);
6865 	synchronize_srcu(&kvm->srcu);
6866 
6867 	kvm_free_msr_filter(old_filter);
6868 
6869 	kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6870 
6871 	return 0;
6872 }
6873 
6874 #ifdef CONFIG_KVM_COMPAT
6875 /* for KVM_X86_SET_MSR_FILTER */
6876 struct kvm_msr_filter_range_compat {
6877 	__u32 flags;
6878 	__u32 nmsrs;
6879 	__u32 base;
6880 	__u32 bitmap;
6881 };
6882 
6883 struct kvm_msr_filter_compat {
6884 	__u32 flags;
6885 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6886 };
6887 
6888 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6889 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6890 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6891 			      unsigned long arg)
6892 {
6893 	void __user *argp = (void __user *)arg;
6894 	struct kvm *kvm = filp->private_data;
6895 	long r = -ENOTTY;
6896 
6897 	switch (ioctl) {
6898 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
6899 		struct kvm_msr_filter __user *user_msr_filter = argp;
6900 		struct kvm_msr_filter_compat filter_compat;
6901 		struct kvm_msr_filter filter;
6902 		int i;
6903 
6904 		if (copy_from_user(&filter_compat, user_msr_filter,
6905 				   sizeof(filter_compat)))
6906 			return -EFAULT;
6907 
6908 		filter.flags = filter_compat.flags;
6909 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6910 			struct kvm_msr_filter_range_compat *cr;
6911 
6912 			cr = &filter_compat.ranges[i];
6913 			filter.ranges[i] = (struct kvm_msr_filter_range) {
6914 				.flags = cr->flags,
6915 				.nmsrs = cr->nmsrs,
6916 				.base = cr->base,
6917 				.bitmap = (__u8 *)(ulong)cr->bitmap,
6918 			};
6919 		}
6920 
6921 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6922 		break;
6923 	}
6924 	}
6925 
6926 	return r;
6927 }
6928 #endif
6929 
6930 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)6931 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6932 {
6933 	struct kvm_vcpu *vcpu;
6934 	unsigned long i;
6935 	int ret = 0;
6936 
6937 	mutex_lock(&kvm->lock);
6938 	kvm_for_each_vcpu(i, vcpu, kvm) {
6939 		if (!vcpu->arch.pv_time.active)
6940 			continue;
6941 
6942 		ret = kvm_set_guest_paused(vcpu);
6943 		if (ret) {
6944 			kvm_err("Failed to pause guest VCPU%d: %d\n",
6945 				vcpu->vcpu_id, ret);
6946 			break;
6947 		}
6948 	}
6949 	mutex_unlock(&kvm->lock);
6950 
6951 	return ret ? NOTIFY_BAD : NOTIFY_DONE;
6952 }
6953 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)6954 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6955 {
6956 	switch (state) {
6957 	case PM_HIBERNATION_PREPARE:
6958 	case PM_SUSPEND_PREPARE:
6959 		return kvm_arch_suspend_notifier(kvm);
6960 	}
6961 
6962 	return NOTIFY_DONE;
6963 }
6964 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6965 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)6966 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6967 {
6968 	struct kvm_clock_data data = { 0 };
6969 
6970 	get_kvmclock(kvm, &data);
6971 	if (copy_to_user(argp, &data, sizeof(data)))
6972 		return -EFAULT;
6973 
6974 	return 0;
6975 }
6976 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)6977 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6978 {
6979 	struct kvm_arch *ka = &kvm->arch;
6980 	struct kvm_clock_data data;
6981 	u64 now_raw_ns;
6982 
6983 	if (copy_from_user(&data, argp, sizeof(data)))
6984 		return -EFAULT;
6985 
6986 	/*
6987 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6988 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6989 	 */
6990 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
6991 		return -EINVAL;
6992 
6993 	kvm_hv_request_tsc_page_update(kvm);
6994 	kvm_start_pvclock_update(kvm);
6995 	pvclock_update_vm_gtod_copy(kvm);
6996 
6997 	/*
6998 	 * This pairs with kvm_guest_time_update(): when masterclock is
6999 	 * in use, we use master_kernel_ns + kvmclock_offset to set
7000 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7001 	 * is slightly ahead) here we risk going negative on unsigned
7002 	 * 'system_time' when 'data.clock' is very small.
7003 	 */
7004 	if (data.flags & KVM_CLOCK_REALTIME) {
7005 		u64 now_real_ns = ktime_get_real_ns();
7006 
7007 		/*
7008 		 * Avoid stepping the kvmclock backwards.
7009 		 */
7010 		if (now_real_ns > data.realtime)
7011 			data.clock += now_real_ns - data.realtime;
7012 	}
7013 
7014 	if (ka->use_master_clock)
7015 		now_raw_ns = ka->master_kernel_ns;
7016 	else
7017 		now_raw_ns = get_kvmclock_base_ns();
7018 	ka->kvmclock_offset = data.clock - now_raw_ns;
7019 	kvm_end_pvclock_update(kvm);
7020 	return 0;
7021 }
7022 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7023 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7024 {
7025 	struct kvm *kvm = filp->private_data;
7026 	void __user *argp = (void __user *)arg;
7027 	int r = -ENOTTY;
7028 	/*
7029 	 * This union makes it completely explicit to gcc-3.x
7030 	 * that these two variables' stack usage should be
7031 	 * combined, not added together.
7032 	 */
7033 	union {
7034 		struct kvm_pit_state ps;
7035 		struct kvm_pit_state2 ps2;
7036 		struct kvm_pit_config pit_config;
7037 	} u;
7038 
7039 	switch (ioctl) {
7040 	case KVM_SET_TSS_ADDR:
7041 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7042 		break;
7043 	case KVM_SET_IDENTITY_MAP_ADDR: {
7044 		u64 ident_addr;
7045 
7046 		mutex_lock(&kvm->lock);
7047 		r = -EINVAL;
7048 		if (kvm->created_vcpus)
7049 			goto set_identity_unlock;
7050 		r = -EFAULT;
7051 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7052 			goto set_identity_unlock;
7053 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7054 set_identity_unlock:
7055 		mutex_unlock(&kvm->lock);
7056 		break;
7057 	}
7058 	case KVM_SET_NR_MMU_PAGES:
7059 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7060 		break;
7061 	case KVM_CREATE_IRQCHIP: {
7062 		mutex_lock(&kvm->lock);
7063 
7064 		r = -EEXIST;
7065 		if (irqchip_in_kernel(kvm))
7066 			goto create_irqchip_unlock;
7067 
7068 		r = -EINVAL;
7069 		if (kvm->created_vcpus)
7070 			goto create_irqchip_unlock;
7071 
7072 		r = kvm_pic_init(kvm);
7073 		if (r)
7074 			goto create_irqchip_unlock;
7075 
7076 		r = kvm_ioapic_init(kvm);
7077 		if (r) {
7078 			kvm_pic_destroy(kvm);
7079 			goto create_irqchip_unlock;
7080 		}
7081 
7082 		r = kvm_setup_default_irq_routing(kvm);
7083 		if (r) {
7084 			kvm_ioapic_destroy(kvm);
7085 			kvm_pic_destroy(kvm);
7086 			goto create_irqchip_unlock;
7087 		}
7088 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7089 		smp_wmb();
7090 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7091 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7092 	create_irqchip_unlock:
7093 		mutex_unlock(&kvm->lock);
7094 		break;
7095 	}
7096 	case KVM_CREATE_PIT:
7097 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7098 		goto create_pit;
7099 	case KVM_CREATE_PIT2:
7100 		r = -EFAULT;
7101 		if (copy_from_user(&u.pit_config, argp,
7102 				   sizeof(struct kvm_pit_config)))
7103 			goto out;
7104 	create_pit:
7105 		mutex_lock(&kvm->lock);
7106 		r = -EEXIST;
7107 		if (kvm->arch.vpit)
7108 			goto create_pit_unlock;
7109 		r = -ENOENT;
7110 		if (!pic_in_kernel(kvm))
7111 			goto create_pit_unlock;
7112 		r = -ENOMEM;
7113 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7114 		if (kvm->arch.vpit)
7115 			r = 0;
7116 	create_pit_unlock:
7117 		mutex_unlock(&kvm->lock);
7118 		break;
7119 	case KVM_GET_IRQCHIP: {
7120 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7121 		struct kvm_irqchip *chip;
7122 
7123 		chip = memdup_user(argp, sizeof(*chip));
7124 		if (IS_ERR(chip)) {
7125 			r = PTR_ERR(chip);
7126 			goto out;
7127 		}
7128 
7129 		r = -ENXIO;
7130 		if (!irqchip_kernel(kvm))
7131 			goto get_irqchip_out;
7132 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7133 		if (r)
7134 			goto get_irqchip_out;
7135 		r = -EFAULT;
7136 		if (copy_to_user(argp, chip, sizeof(*chip)))
7137 			goto get_irqchip_out;
7138 		r = 0;
7139 	get_irqchip_out:
7140 		kfree(chip);
7141 		break;
7142 	}
7143 	case KVM_SET_IRQCHIP: {
7144 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7145 		struct kvm_irqchip *chip;
7146 
7147 		chip = memdup_user(argp, sizeof(*chip));
7148 		if (IS_ERR(chip)) {
7149 			r = PTR_ERR(chip);
7150 			goto out;
7151 		}
7152 
7153 		r = -ENXIO;
7154 		if (!irqchip_kernel(kvm))
7155 			goto set_irqchip_out;
7156 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7157 	set_irqchip_out:
7158 		kfree(chip);
7159 		break;
7160 	}
7161 	case KVM_GET_PIT: {
7162 		r = -EFAULT;
7163 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7164 			goto out;
7165 		r = -ENXIO;
7166 		if (!kvm->arch.vpit)
7167 			goto out;
7168 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7169 		if (r)
7170 			goto out;
7171 		r = -EFAULT;
7172 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7173 			goto out;
7174 		r = 0;
7175 		break;
7176 	}
7177 	case KVM_SET_PIT: {
7178 		r = -EFAULT;
7179 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7180 			goto out;
7181 		mutex_lock(&kvm->lock);
7182 		r = -ENXIO;
7183 		if (!kvm->arch.vpit)
7184 			goto set_pit_out;
7185 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7186 set_pit_out:
7187 		mutex_unlock(&kvm->lock);
7188 		break;
7189 	}
7190 	case KVM_GET_PIT2: {
7191 		r = -ENXIO;
7192 		if (!kvm->arch.vpit)
7193 			goto out;
7194 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7195 		if (r)
7196 			goto out;
7197 		r = -EFAULT;
7198 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7199 			goto out;
7200 		r = 0;
7201 		break;
7202 	}
7203 	case KVM_SET_PIT2: {
7204 		r = -EFAULT;
7205 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7206 			goto out;
7207 		mutex_lock(&kvm->lock);
7208 		r = -ENXIO;
7209 		if (!kvm->arch.vpit)
7210 			goto set_pit2_out;
7211 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7212 set_pit2_out:
7213 		mutex_unlock(&kvm->lock);
7214 		break;
7215 	}
7216 	case KVM_REINJECT_CONTROL: {
7217 		struct kvm_reinject_control control;
7218 		r =  -EFAULT;
7219 		if (copy_from_user(&control, argp, sizeof(control)))
7220 			goto out;
7221 		r = -ENXIO;
7222 		if (!kvm->arch.vpit)
7223 			goto out;
7224 		r = kvm_vm_ioctl_reinject(kvm, &control);
7225 		break;
7226 	}
7227 	case KVM_SET_BOOT_CPU_ID:
7228 		r = 0;
7229 		mutex_lock(&kvm->lock);
7230 		if (kvm->created_vcpus)
7231 			r = -EBUSY;
7232 		else if (arg > KVM_MAX_VCPU_IDS ||
7233 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7234 			r = -EINVAL;
7235 		else
7236 			kvm->arch.bsp_vcpu_id = arg;
7237 		mutex_unlock(&kvm->lock);
7238 		break;
7239 #ifdef CONFIG_KVM_XEN
7240 	case KVM_XEN_HVM_CONFIG: {
7241 		struct kvm_xen_hvm_config xhc;
7242 		r = -EFAULT;
7243 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
7244 			goto out;
7245 		r = kvm_xen_hvm_config(kvm, &xhc);
7246 		break;
7247 	}
7248 	case KVM_XEN_HVM_GET_ATTR: {
7249 		struct kvm_xen_hvm_attr xha;
7250 
7251 		r = -EFAULT;
7252 		if (copy_from_user(&xha, argp, sizeof(xha)))
7253 			goto out;
7254 		r = kvm_xen_hvm_get_attr(kvm, &xha);
7255 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7256 			r = -EFAULT;
7257 		break;
7258 	}
7259 	case KVM_XEN_HVM_SET_ATTR: {
7260 		struct kvm_xen_hvm_attr xha;
7261 
7262 		r = -EFAULT;
7263 		if (copy_from_user(&xha, argp, sizeof(xha)))
7264 			goto out;
7265 		r = kvm_xen_hvm_set_attr(kvm, &xha);
7266 		break;
7267 	}
7268 	case KVM_XEN_HVM_EVTCHN_SEND: {
7269 		struct kvm_irq_routing_xen_evtchn uxe;
7270 
7271 		r = -EFAULT;
7272 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
7273 			goto out;
7274 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7275 		break;
7276 	}
7277 #endif
7278 	case KVM_SET_CLOCK:
7279 		r = kvm_vm_ioctl_set_clock(kvm, argp);
7280 		break;
7281 	case KVM_GET_CLOCK:
7282 		r = kvm_vm_ioctl_get_clock(kvm, argp);
7283 		break;
7284 	case KVM_SET_TSC_KHZ: {
7285 		u32 user_tsc_khz;
7286 
7287 		r = -EINVAL;
7288 		user_tsc_khz = (u32)arg;
7289 
7290 		if (kvm_caps.has_tsc_control &&
7291 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7292 			goto out;
7293 
7294 		if (user_tsc_khz == 0)
7295 			user_tsc_khz = tsc_khz;
7296 
7297 		WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7298 		r = 0;
7299 
7300 		goto out;
7301 	}
7302 	case KVM_GET_TSC_KHZ: {
7303 		r = READ_ONCE(kvm->arch.default_tsc_khz);
7304 		goto out;
7305 	}
7306 	case KVM_MEMORY_ENCRYPT_OP: {
7307 		r = -ENOTTY;
7308 		if (!kvm_x86_ops.mem_enc_ioctl)
7309 			goto out;
7310 
7311 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7312 		break;
7313 	}
7314 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
7315 		struct kvm_enc_region region;
7316 
7317 		r = -EFAULT;
7318 		if (copy_from_user(&region, argp, sizeof(region)))
7319 			goto out;
7320 
7321 		r = -ENOTTY;
7322 		if (!kvm_x86_ops.mem_enc_register_region)
7323 			goto out;
7324 
7325 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
7326 		break;
7327 	}
7328 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7329 		struct kvm_enc_region region;
7330 
7331 		r = -EFAULT;
7332 		if (copy_from_user(&region, argp, sizeof(region)))
7333 			goto out;
7334 
7335 		r = -ENOTTY;
7336 		if (!kvm_x86_ops.mem_enc_unregister_region)
7337 			goto out;
7338 
7339 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
7340 		break;
7341 	}
7342 #ifdef CONFIG_KVM_HYPERV
7343 	case KVM_HYPERV_EVENTFD: {
7344 		struct kvm_hyperv_eventfd hvevfd;
7345 
7346 		r = -EFAULT;
7347 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7348 			goto out;
7349 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7350 		break;
7351 	}
7352 #endif
7353 	case KVM_SET_PMU_EVENT_FILTER:
7354 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7355 		break;
7356 	case KVM_X86_SET_MSR_FILTER: {
7357 		struct kvm_msr_filter __user *user_msr_filter = argp;
7358 		struct kvm_msr_filter filter;
7359 
7360 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7361 			return -EFAULT;
7362 
7363 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7364 		break;
7365 	}
7366 	default:
7367 		r = -ENOTTY;
7368 	}
7369 out:
7370 	return r;
7371 }
7372 
kvm_probe_feature_msr(u32 msr_index)7373 static void kvm_probe_feature_msr(u32 msr_index)
7374 {
7375 	u64 data;
7376 
7377 	if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7378 		return;
7379 
7380 	msr_based_features[num_msr_based_features++] = msr_index;
7381 }
7382 
kvm_probe_msr_to_save(u32 msr_index)7383 static void kvm_probe_msr_to_save(u32 msr_index)
7384 {
7385 	u32 dummy[2];
7386 
7387 	if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7388 		return;
7389 
7390 	/*
7391 	 * Even MSRs that are valid in the host may not be exposed to guests in
7392 	 * some cases.
7393 	 */
7394 	switch (msr_index) {
7395 	case MSR_IA32_BNDCFGS:
7396 		if (!kvm_mpx_supported())
7397 			return;
7398 		break;
7399 	case MSR_TSC_AUX:
7400 		if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7401 		    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7402 			return;
7403 		break;
7404 	case MSR_IA32_UMWAIT_CONTROL:
7405 		if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7406 			return;
7407 		break;
7408 	case MSR_IA32_RTIT_CTL:
7409 	case MSR_IA32_RTIT_STATUS:
7410 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7411 			return;
7412 		break;
7413 	case MSR_IA32_RTIT_CR3_MATCH:
7414 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7415 		    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7416 			return;
7417 		break;
7418 	case MSR_IA32_RTIT_OUTPUT_BASE:
7419 	case MSR_IA32_RTIT_OUTPUT_MASK:
7420 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7421 		    (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7422 		     !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7423 			return;
7424 		break;
7425 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7426 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7427 		    (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7428 		     intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7429 			return;
7430 		break;
7431 	case MSR_ARCH_PERFMON_PERFCTR0 ...
7432 	     MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7433 		if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7434 		    kvm_pmu_cap.num_counters_gp)
7435 			return;
7436 		break;
7437 	case MSR_ARCH_PERFMON_EVENTSEL0 ...
7438 	     MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7439 		if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7440 		    kvm_pmu_cap.num_counters_gp)
7441 			return;
7442 		break;
7443 	case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7444 	     MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7445 		if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7446 		    kvm_pmu_cap.num_counters_fixed)
7447 			return;
7448 		break;
7449 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7450 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7451 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7452 		if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7453 			return;
7454 		break;
7455 	case MSR_IA32_XFD:
7456 	case MSR_IA32_XFD_ERR:
7457 		if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7458 			return;
7459 		break;
7460 	case MSR_IA32_TSX_CTRL:
7461 		if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7462 			return;
7463 		break;
7464 	default:
7465 		break;
7466 	}
7467 
7468 	msrs_to_save[num_msrs_to_save++] = msr_index;
7469 }
7470 
kvm_init_msr_lists(void)7471 static void kvm_init_msr_lists(void)
7472 {
7473 	unsigned i;
7474 
7475 	BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7476 			 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7477 
7478 	num_msrs_to_save = 0;
7479 	num_emulated_msrs = 0;
7480 	num_msr_based_features = 0;
7481 
7482 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7483 		kvm_probe_msr_to_save(msrs_to_save_base[i]);
7484 
7485 	if (enable_pmu) {
7486 		for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7487 			kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7488 	}
7489 
7490 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7491 		if (!kvm_x86_call(has_emulated_msr)(NULL,
7492 						    emulated_msrs_all[i]))
7493 			continue;
7494 
7495 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7496 	}
7497 
7498 	for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7499 		kvm_probe_feature_msr(i);
7500 
7501 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7502 		kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7503 }
7504 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7505 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7506 			   const void *v)
7507 {
7508 	int handled = 0;
7509 	int n;
7510 
7511 	do {
7512 		n = min(len, 8);
7513 		if (!(lapic_in_kernel(vcpu) &&
7514 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7515 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7516 			break;
7517 		handled += n;
7518 		addr += n;
7519 		len -= n;
7520 		v += n;
7521 	} while (len);
7522 
7523 	return handled;
7524 }
7525 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7526 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7527 {
7528 	int handled = 0;
7529 	int n;
7530 
7531 	do {
7532 		n = min(len, 8);
7533 		if (!(lapic_in_kernel(vcpu) &&
7534 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7535 					 addr, n, v))
7536 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7537 			break;
7538 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7539 		handled += n;
7540 		addr += n;
7541 		len -= n;
7542 		v += n;
7543 	} while (len);
7544 
7545 	return handled;
7546 }
7547 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7548 void kvm_set_segment(struct kvm_vcpu *vcpu,
7549 		     struct kvm_segment *var, int seg)
7550 {
7551 	kvm_x86_call(set_segment)(vcpu, var, seg);
7552 }
7553 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7554 void kvm_get_segment(struct kvm_vcpu *vcpu,
7555 		     struct kvm_segment *var, int seg)
7556 {
7557 	kvm_x86_call(get_segment)(vcpu, var, seg);
7558 }
7559 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7560 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7561 			   struct x86_exception *exception)
7562 {
7563 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7564 	gpa_t t_gpa;
7565 
7566 	BUG_ON(!mmu_is_nested(vcpu));
7567 
7568 	/* NPT walks are always user-walks */
7569 	access |= PFERR_USER_MASK;
7570 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7571 
7572 	return t_gpa;
7573 }
7574 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7575 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7576 			      struct x86_exception *exception)
7577 {
7578 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7579 
7580 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7581 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7582 }
7583 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7584 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7585 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7586 			       struct x86_exception *exception)
7587 {
7588 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7589 
7590 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7591 	access |= PFERR_WRITE_MASK;
7592 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7593 }
7594 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7595 
7596 /* 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)7597 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7598 				struct x86_exception *exception)
7599 {
7600 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7601 
7602 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7603 }
7604 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7605 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7606 				      struct kvm_vcpu *vcpu, u64 access,
7607 				      struct x86_exception *exception)
7608 {
7609 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7610 	void *data = val;
7611 	int r = X86EMUL_CONTINUE;
7612 
7613 	while (bytes) {
7614 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7615 		unsigned offset = addr & (PAGE_SIZE-1);
7616 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7617 		int ret;
7618 
7619 		if (gpa == INVALID_GPA)
7620 			return X86EMUL_PROPAGATE_FAULT;
7621 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7622 					       offset, toread);
7623 		if (ret < 0) {
7624 			r = X86EMUL_IO_NEEDED;
7625 			goto out;
7626 		}
7627 
7628 		bytes -= toread;
7629 		data += toread;
7630 		addr += toread;
7631 	}
7632 out:
7633 	return r;
7634 }
7635 
7636 /* 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)7637 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7638 				gva_t addr, void *val, unsigned int bytes,
7639 				struct x86_exception *exception)
7640 {
7641 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7642 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7643 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7644 	unsigned offset;
7645 	int ret;
7646 
7647 	/* Inline kvm_read_guest_virt_helper for speed.  */
7648 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7649 				    exception);
7650 	if (unlikely(gpa == INVALID_GPA))
7651 		return X86EMUL_PROPAGATE_FAULT;
7652 
7653 	offset = addr & (PAGE_SIZE-1);
7654 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7655 		bytes = (unsigned)PAGE_SIZE - offset;
7656 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7657 				       offset, bytes);
7658 	if (unlikely(ret < 0))
7659 		return X86EMUL_IO_NEEDED;
7660 
7661 	return X86EMUL_CONTINUE;
7662 }
7663 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7664 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7665 			       gva_t addr, void *val, unsigned int bytes,
7666 			       struct x86_exception *exception)
7667 {
7668 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7669 
7670 	/*
7671 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7672 	 * is returned, but our callers are not ready for that and they blindly
7673 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7674 	 * uninitialized kernel stack memory into cr2 and error code.
7675 	 */
7676 	memset(exception, 0, sizeof(*exception));
7677 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7678 					  exception);
7679 }
7680 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7681 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7682 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7683 			     gva_t addr, void *val, unsigned int bytes,
7684 			     struct x86_exception *exception, bool system)
7685 {
7686 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7687 	u64 access = 0;
7688 
7689 	if (system)
7690 		access |= PFERR_IMPLICIT_ACCESS;
7691 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7692 		access |= PFERR_USER_MASK;
7693 
7694 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7695 }
7696 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7697 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7698 				      struct kvm_vcpu *vcpu, u64 access,
7699 				      struct x86_exception *exception)
7700 {
7701 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7702 	void *data = val;
7703 	int r = X86EMUL_CONTINUE;
7704 
7705 	while (bytes) {
7706 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7707 		unsigned offset = addr & (PAGE_SIZE-1);
7708 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7709 		int ret;
7710 
7711 		if (gpa == INVALID_GPA)
7712 			return X86EMUL_PROPAGATE_FAULT;
7713 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7714 		if (ret < 0) {
7715 			r = X86EMUL_IO_NEEDED;
7716 			goto out;
7717 		}
7718 
7719 		bytes -= towrite;
7720 		data += towrite;
7721 		addr += towrite;
7722 	}
7723 out:
7724 	return r;
7725 }
7726 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7727 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7728 			      unsigned int bytes, struct x86_exception *exception,
7729 			      bool system)
7730 {
7731 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7732 	u64 access = PFERR_WRITE_MASK;
7733 
7734 	if (system)
7735 		access |= PFERR_IMPLICIT_ACCESS;
7736 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7737 		access |= PFERR_USER_MASK;
7738 
7739 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7740 					   access, exception);
7741 }
7742 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7743 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7744 				unsigned int bytes, struct x86_exception *exception)
7745 {
7746 	/* kvm_write_guest_virt_system can pull in tons of pages. */
7747 	vcpu->arch.l1tf_flush_l1d = true;
7748 
7749 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7750 					   PFERR_WRITE_MASK, exception);
7751 }
7752 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7753 
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7754 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7755 				  void *insn, int insn_len)
7756 {
7757 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7758 						       insn, insn_len);
7759 }
7760 
handle_ud(struct kvm_vcpu * vcpu)7761 int handle_ud(struct kvm_vcpu *vcpu)
7762 {
7763 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7764 	int fep_flags = READ_ONCE(force_emulation_prefix);
7765 	int emul_type = EMULTYPE_TRAP_UD;
7766 	char sig[5]; /* ud2; .ascii "kvm" */
7767 	struct x86_exception e;
7768 	int r;
7769 
7770 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7771 	if (r != X86EMUL_CONTINUE)
7772 		return 1;
7773 
7774 	if (fep_flags &&
7775 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7776 				sig, sizeof(sig), &e) == 0 &&
7777 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7778 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7779 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7780 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7781 		emul_type = EMULTYPE_TRAP_UD_FORCED;
7782 	}
7783 
7784 	return kvm_emulate_instruction(vcpu, emul_type);
7785 }
7786 EXPORT_SYMBOL_GPL(handle_ud);
7787 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)7788 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7789 			    gpa_t gpa, bool write)
7790 {
7791 	/* For APIC access vmexit */
7792 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7793 		return 1;
7794 
7795 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7796 		trace_vcpu_match_mmio(gva, gpa, write, true);
7797 		return 1;
7798 	}
7799 
7800 	return 0;
7801 }
7802 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)7803 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7804 				gpa_t *gpa, struct x86_exception *exception,
7805 				bool write)
7806 {
7807 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7808 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7809 		     | (write ? PFERR_WRITE_MASK : 0);
7810 
7811 	/*
7812 	 * currently PKRU is only applied to ept enabled guest so
7813 	 * there is no pkey in EPT page table for L1 guest or EPT
7814 	 * shadow page table for L2 guest.
7815 	 */
7816 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7817 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
7818 			      vcpu->arch.mmio_access, 0, access))) {
7819 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7820 					(gva & (PAGE_SIZE - 1));
7821 		trace_vcpu_match_mmio(gva, *gpa, write, false);
7822 		return 1;
7823 	}
7824 
7825 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7826 
7827 	if (*gpa == INVALID_GPA)
7828 		return -1;
7829 
7830 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7831 }
7832 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)7833 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7834 			const void *val, int bytes)
7835 {
7836 	int ret;
7837 
7838 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7839 	if (ret < 0)
7840 		return 0;
7841 	kvm_page_track_write(vcpu, gpa, val, bytes);
7842 	return 1;
7843 }
7844 
7845 struct read_write_emulator_ops {
7846 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7847 				  int bytes);
7848 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7849 				  void *val, int bytes);
7850 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7851 			       int bytes, void *val);
7852 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7853 				    void *val, int bytes);
7854 	bool write;
7855 };
7856 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)7857 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7858 {
7859 	if (vcpu->mmio_read_completed) {
7860 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7861 			       vcpu->mmio_fragments[0].gpa, val);
7862 		vcpu->mmio_read_completed = 0;
7863 		return 1;
7864 	}
7865 
7866 	return 0;
7867 }
7868 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7869 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7870 			void *val, int bytes)
7871 {
7872 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7873 }
7874 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7875 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7876 			 void *val, int bytes)
7877 {
7878 	return emulator_write_phys(vcpu, gpa, val, bytes);
7879 }
7880 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)7881 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7882 {
7883 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7884 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
7885 }
7886 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7887 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7888 			  void *val, int bytes)
7889 {
7890 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7891 	return X86EMUL_IO_NEEDED;
7892 }
7893 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7894 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7895 			   void *val, int bytes)
7896 {
7897 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7898 
7899 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7900 	return X86EMUL_CONTINUE;
7901 }
7902 
7903 static const struct read_write_emulator_ops read_emultor = {
7904 	.read_write_prepare = read_prepare,
7905 	.read_write_emulate = read_emulate,
7906 	.read_write_mmio = vcpu_mmio_read,
7907 	.read_write_exit_mmio = read_exit_mmio,
7908 };
7909 
7910 static const struct read_write_emulator_ops write_emultor = {
7911 	.read_write_emulate = write_emulate,
7912 	.read_write_mmio = write_mmio,
7913 	.read_write_exit_mmio = write_exit_mmio,
7914 	.write = true,
7915 };
7916 
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)7917 static int emulator_read_write_onepage(unsigned long addr, void *val,
7918 				       unsigned int bytes,
7919 				       struct x86_exception *exception,
7920 				       struct kvm_vcpu *vcpu,
7921 				       const struct read_write_emulator_ops *ops)
7922 {
7923 	gpa_t gpa;
7924 	int handled, ret;
7925 	bool write = ops->write;
7926 	struct kvm_mmio_fragment *frag;
7927 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7928 
7929 	/*
7930 	 * If the exit was due to a NPF we may already have a GPA.
7931 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7932 	 * Note, this cannot be used on string operations since string
7933 	 * operation using rep will only have the initial GPA from the NPF
7934 	 * occurred.
7935 	 */
7936 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7937 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7938 		gpa = ctxt->gpa_val;
7939 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7940 	} else {
7941 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7942 		if (ret < 0)
7943 			return X86EMUL_PROPAGATE_FAULT;
7944 	}
7945 
7946 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7947 		return X86EMUL_CONTINUE;
7948 
7949 	/*
7950 	 * Is this MMIO handled locally?
7951 	 */
7952 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7953 	if (handled == bytes)
7954 		return X86EMUL_CONTINUE;
7955 
7956 	gpa += handled;
7957 	bytes -= handled;
7958 	val += handled;
7959 
7960 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7961 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7962 	frag->gpa = gpa;
7963 	frag->data = val;
7964 	frag->len = bytes;
7965 	return X86EMUL_CONTINUE;
7966 }
7967 
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)7968 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7969 			unsigned long addr,
7970 			void *val, unsigned int bytes,
7971 			struct x86_exception *exception,
7972 			const struct read_write_emulator_ops *ops)
7973 {
7974 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7975 	gpa_t gpa;
7976 	int rc;
7977 
7978 	if (ops->read_write_prepare &&
7979 		  ops->read_write_prepare(vcpu, val, bytes))
7980 		return X86EMUL_CONTINUE;
7981 
7982 	vcpu->mmio_nr_fragments = 0;
7983 
7984 	/* Crossing a page boundary? */
7985 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
7986 		int now;
7987 
7988 		now = -addr & ~PAGE_MASK;
7989 		rc = emulator_read_write_onepage(addr, val, now, exception,
7990 						 vcpu, ops);
7991 
7992 		if (rc != X86EMUL_CONTINUE)
7993 			return rc;
7994 		addr += now;
7995 		if (ctxt->mode != X86EMUL_MODE_PROT64)
7996 			addr = (u32)addr;
7997 		val += now;
7998 		bytes -= now;
7999 	}
8000 
8001 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
8002 					 vcpu, ops);
8003 	if (rc != X86EMUL_CONTINUE)
8004 		return rc;
8005 
8006 	if (!vcpu->mmio_nr_fragments)
8007 		return rc;
8008 
8009 	gpa = vcpu->mmio_fragments[0].gpa;
8010 
8011 	vcpu->mmio_needed = 1;
8012 	vcpu->mmio_cur_fragment = 0;
8013 
8014 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8015 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8016 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
8017 	vcpu->run->mmio.phys_addr = gpa;
8018 
8019 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8020 }
8021 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8022 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8023 				  unsigned long addr,
8024 				  void *val,
8025 				  unsigned int bytes,
8026 				  struct x86_exception *exception)
8027 {
8028 	return emulator_read_write(ctxt, addr, val, bytes,
8029 				   exception, &read_emultor);
8030 }
8031 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8032 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8033 			    unsigned long addr,
8034 			    const void *val,
8035 			    unsigned int bytes,
8036 			    struct x86_exception *exception)
8037 {
8038 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
8039 				   exception, &write_emultor);
8040 }
8041 
8042 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8043 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8044 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8045 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8046 				     unsigned long addr,
8047 				     const void *old,
8048 				     const void *new,
8049 				     unsigned int bytes,
8050 				     struct x86_exception *exception)
8051 {
8052 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8053 	u64 page_line_mask;
8054 	unsigned long hva;
8055 	gpa_t gpa;
8056 	int r;
8057 
8058 	/* guests cmpxchg8b have to be emulated atomically */
8059 	if (bytes > 8 || (bytes & (bytes - 1)))
8060 		goto emul_write;
8061 
8062 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8063 
8064 	if (gpa == INVALID_GPA ||
8065 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8066 		goto emul_write;
8067 
8068 	/*
8069 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
8070 	 * enabled in the host and the access splits a cache line.
8071 	 */
8072 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8073 		page_line_mask = ~(cache_line_size() - 1);
8074 	else
8075 		page_line_mask = PAGE_MASK;
8076 
8077 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8078 		goto emul_write;
8079 
8080 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8081 	if (kvm_is_error_hva(hva))
8082 		goto emul_write;
8083 
8084 	hva += offset_in_page(gpa);
8085 
8086 	switch (bytes) {
8087 	case 1:
8088 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
8089 		break;
8090 	case 2:
8091 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
8092 		break;
8093 	case 4:
8094 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
8095 		break;
8096 	case 8:
8097 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
8098 		break;
8099 	default:
8100 		BUG();
8101 	}
8102 
8103 	if (r < 0)
8104 		return X86EMUL_UNHANDLEABLE;
8105 
8106 	/*
8107 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8108 	 * successful, as the old value is written back on failure.  Note, for
8109 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
8110 	 * back the original value and the access is atomic, but KVM's ABI is
8111 	 * that all writes are dirty logged, regardless of the value written.
8112 	 */
8113 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8114 
8115 	if (r)
8116 		return X86EMUL_CMPXCHG_FAILED;
8117 
8118 	kvm_page_track_write(vcpu, gpa, new, bytes);
8119 
8120 	return X86EMUL_CONTINUE;
8121 
8122 emul_write:
8123 	pr_warn_once("emulating exchange as write\n");
8124 
8125 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8126 }
8127 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8128 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8129 			       unsigned short port, void *data,
8130 			       unsigned int count, bool in)
8131 {
8132 	unsigned i;
8133 	int r;
8134 
8135 	WARN_ON_ONCE(vcpu->arch.pio.count);
8136 	for (i = 0; i < count; i++) {
8137 		if (in)
8138 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8139 		else
8140 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8141 
8142 		if (r) {
8143 			if (i == 0)
8144 				goto userspace_io;
8145 
8146 			/*
8147 			 * Userspace must have unregistered the device while PIO
8148 			 * was running.  Drop writes / read as 0.
8149 			 */
8150 			if (in)
8151 				memset(data, 0, size * (count - i));
8152 			break;
8153 		}
8154 
8155 		data += size;
8156 	}
8157 	return 1;
8158 
8159 userspace_io:
8160 	vcpu->arch.pio.port = port;
8161 	vcpu->arch.pio.in = in;
8162 	vcpu->arch.pio.count = count;
8163 	vcpu->arch.pio.size = size;
8164 
8165 	if (in)
8166 		memset(vcpu->arch.pio_data, 0, size * count);
8167 	else
8168 		memcpy(vcpu->arch.pio_data, data, size * count);
8169 
8170 	vcpu->run->exit_reason = KVM_EXIT_IO;
8171 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8172 	vcpu->run->io.size = size;
8173 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8174 	vcpu->run->io.count = count;
8175 	vcpu->run->io.port = port;
8176 	return 0;
8177 }
8178 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8179 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8180       			   unsigned short port, void *val, unsigned int count)
8181 {
8182 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8183 	if (r)
8184 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8185 
8186 	return r;
8187 }
8188 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8189 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8190 {
8191 	int size = vcpu->arch.pio.size;
8192 	unsigned int count = vcpu->arch.pio.count;
8193 	memcpy(val, vcpu->arch.pio_data, size * count);
8194 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8195 	vcpu->arch.pio.count = 0;
8196 }
8197 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8198 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8199 				    int size, unsigned short port, void *val,
8200 				    unsigned int count)
8201 {
8202 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8203 	if (vcpu->arch.pio.count) {
8204 		/*
8205 		 * Complete a previous iteration that required userspace I/O.
8206 		 * Note, @count isn't guaranteed to match pio.count as userspace
8207 		 * can modify ECX before rerunning the vCPU.  Ignore any such
8208 		 * shenanigans as KVM doesn't support modifying the rep count,
8209 		 * and the emulator ensures @count doesn't overflow the buffer.
8210 		 */
8211 		complete_emulator_pio_in(vcpu, val);
8212 		return 1;
8213 	}
8214 
8215 	return emulator_pio_in(vcpu, size, port, val, count);
8216 }
8217 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8218 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8219 			    unsigned short port, const void *val,
8220 			    unsigned int count)
8221 {
8222 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8223 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8224 }
8225 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8226 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8227 				     int size, unsigned short port,
8228 				     const void *val, unsigned int count)
8229 {
8230 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8231 }
8232 
get_segment_base(struct kvm_vcpu * vcpu,int seg)8233 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8234 {
8235 	return kvm_x86_call(get_segment_base)(vcpu, seg);
8236 }
8237 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8238 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8239 {
8240 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8241 }
8242 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8243 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8244 {
8245 	if (!need_emulate_wbinvd(vcpu))
8246 		return X86EMUL_CONTINUE;
8247 
8248 	if (kvm_x86_call(has_wbinvd_exit)()) {
8249 		int cpu = get_cpu();
8250 
8251 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8252 		on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
8253 				wbinvd_ipi, NULL, 1);
8254 		put_cpu();
8255 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8256 	} else
8257 		wbinvd();
8258 	return X86EMUL_CONTINUE;
8259 }
8260 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8261 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8262 {
8263 	kvm_emulate_wbinvd_noskip(vcpu);
8264 	return kvm_skip_emulated_instruction(vcpu);
8265 }
8266 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8267 
8268 
8269 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8270 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8271 {
8272 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8273 }
8274 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8275 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8276 {
8277 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8278 }
8279 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8280 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8281 			   unsigned long value)
8282 {
8283 
8284 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8285 }
8286 
mk_cr_64(u64 curr_cr,u32 new_val)8287 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8288 {
8289 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8290 }
8291 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8292 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8293 {
8294 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8295 	unsigned long value;
8296 
8297 	switch (cr) {
8298 	case 0:
8299 		value = kvm_read_cr0(vcpu);
8300 		break;
8301 	case 2:
8302 		value = vcpu->arch.cr2;
8303 		break;
8304 	case 3:
8305 		value = kvm_read_cr3(vcpu);
8306 		break;
8307 	case 4:
8308 		value = kvm_read_cr4(vcpu);
8309 		break;
8310 	case 8:
8311 		value = kvm_get_cr8(vcpu);
8312 		break;
8313 	default:
8314 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8315 		return 0;
8316 	}
8317 
8318 	return value;
8319 }
8320 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8321 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8322 {
8323 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8324 	int res = 0;
8325 
8326 	switch (cr) {
8327 	case 0:
8328 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8329 		break;
8330 	case 2:
8331 		vcpu->arch.cr2 = val;
8332 		break;
8333 	case 3:
8334 		res = kvm_set_cr3(vcpu, val);
8335 		break;
8336 	case 4:
8337 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8338 		break;
8339 	case 8:
8340 		res = kvm_set_cr8(vcpu, val);
8341 		break;
8342 	default:
8343 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8344 		res = -1;
8345 	}
8346 
8347 	return res;
8348 }
8349 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8350 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8351 {
8352 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8353 }
8354 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8355 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8356 {
8357 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8358 }
8359 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8360 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8361 {
8362 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8363 }
8364 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8365 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8366 {
8367 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8368 }
8369 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8370 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8371 {
8372 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8373 }
8374 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8375 static unsigned long emulator_get_cached_segment_base(
8376 	struct x86_emulate_ctxt *ctxt, int seg)
8377 {
8378 	return get_segment_base(emul_to_vcpu(ctxt), seg);
8379 }
8380 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8381 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8382 				 struct desc_struct *desc, u32 *base3,
8383 				 int seg)
8384 {
8385 	struct kvm_segment var;
8386 
8387 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8388 	*selector = var.selector;
8389 
8390 	if (var.unusable) {
8391 		memset(desc, 0, sizeof(*desc));
8392 		if (base3)
8393 			*base3 = 0;
8394 		return false;
8395 	}
8396 
8397 	if (var.g)
8398 		var.limit >>= 12;
8399 	set_desc_limit(desc, var.limit);
8400 	set_desc_base(desc, (unsigned long)var.base);
8401 #ifdef CONFIG_X86_64
8402 	if (base3)
8403 		*base3 = var.base >> 32;
8404 #endif
8405 	desc->type = var.type;
8406 	desc->s = var.s;
8407 	desc->dpl = var.dpl;
8408 	desc->p = var.present;
8409 	desc->avl = var.avl;
8410 	desc->l = var.l;
8411 	desc->d = var.db;
8412 	desc->g = var.g;
8413 
8414 	return true;
8415 }
8416 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8417 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8418 				 struct desc_struct *desc, u32 base3,
8419 				 int seg)
8420 {
8421 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8422 	struct kvm_segment var;
8423 
8424 	var.selector = selector;
8425 	var.base = get_desc_base(desc);
8426 #ifdef CONFIG_X86_64
8427 	var.base |= ((u64)base3) << 32;
8428 #endif
8429 	var.limit = get_desc_limit(desc);
8430 	if (desc->g)
8431 		var.limit = (var.limit << 12) | 0xfff;
8432 	var.type = desc->type;
8433 	var.dpl = desc->dpl;
8434 	var.db = desc->d;
8435 	var.s = desc->s;
8436 	var.l = desc->l;
8437 	var.g = desc->g;
8438 	var.avl = desc->avl;
8439 	var.present = desc->p;
8440 	var.unusable = !var.present;
8441 	var.padding = 0;
8442 
8443 	kvm_set_segment(vcpu, &var, seg);
8444 	return;
8445 }
8446 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8447 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8448 					u32 msr_index, u64 *pdata)
8449 {
8450 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8451 	int r;
8452 
8453 	r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8454 	if (r < 0)
8455 		return X86EMUL_UNHANDLEABLE;
8456 
8457 	if (r) {
8458 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8459 				       complete_emulated_rdmsr, r))
8460 			return X86EMUL_IO_NEEDED;
8461 
8462 		trace_kvm_msr_read_ex(msr_index);
8463 		return X86EMUL_PROPAGATE_FAULT;
8464 	}
8465 
8466 	trace_kvm_msr_read(msr_index, *pdata);
8467 	return X86EMUL_CONTINUE;
8468 }
8469 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8470 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8471 					u32 msr_index, u64 data)
8472 {
8473 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8474 	int r;
8475 
8476 	r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8477 	if (r < 0)
8478 		return X86EMUL_UNHANDLEABLE;
8479 
8480 	if (r) {
8481 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8482 				       complete_emulated_msr_access, r))
8483 			return X86EMUL_IO_NEEDED;
8484 
8485 		trace_kvm_msr_write_ex(msr_index, data);
8486 		return X86EMUL_PROPAGATE_FAULT;
8487 	}
8488 
8489 	trace_kvm_msr_write(msr_index, data);
8490 	return X86EMUL_CONTINUE;
8491 }
8492 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8493 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8494 			    u32 msr_index, u64 *pdata)
8495 {
8496 	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8497 }
8498 
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8499 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8500 {
8501 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8502 }
8503 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8504 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8505 			     u32 pmc, u64 *pdata)
8506 {
8507 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8508 }
8509 
emulator_halt(struct x86_emulate_ctxt * ctxt)8510 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8511 {
8512 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8513 }
8514 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8515 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8516 			      struct x86_instruction_info *info,
8517 			      enum x86_intercept_stage stage)
8518 {
8519 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8520 					     &ctxt->exception);
8521 }
8522 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8523 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8524 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8525 			      bool exact_only)
8526 {
8527 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8528 }
8529 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8530 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8531 {
8532 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8533 }
8534 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8535 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8536 {
8537 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8538 }
8539 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8540 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8541 {
8542 	return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8543 }
8544 
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8545 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8546 {
8547 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8548 }
8549 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8550 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8551 {
8552 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8553 }
8554 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8555 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8556 {
8557 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8558 }
8559 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8560 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8561 {
8562 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8563 }
8564 
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8565 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8566 {
8567 	return is_smm(emul_to_vcpu(ctxt));
8568 }
8569 
8570 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8571 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8572 {
8573 	WARN_ON_ONCE(1);
8574 	return X86EMUL_UNHANDLEABLE;
8575 }
8576 #endif
8577 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8578 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8579 {
8580 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8581 }
8582 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8583 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8584 {
8585 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8586 }
8587 
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8588 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8589 {
8590 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8591 
8592 	if (!kvm->vm_bugged)
8593 		kvm_vm_bugged(kvm);
8594 }
8595 
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8596 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8597 					gva_t addr, unsigned int flags)
8598 {
8599 	if (!kvm_x86_ops.get_untagged_addr)
8600 		return addr;
8601 
8602 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8603 					       addr, flags);
8604 }
8605 
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8606 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8607 				       gva_t addr, unsigned int flags)
8608 {
8609 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8610 }
8611 
8612 static const struct x86_emulate_ops emulate_ops = {
8613 	.vm_bugged           = emulator_vm_bugged,
8614 	.read_gpr            = emulator_read_gpr,
8615 	.write_gpr           = emulator_write_gpr,
8616 	.read_std            = emulator_read_std,
8617 	.write_std           = emulator_write_std,
8618 	.fetch               = kvm_fetch_guest_virt,
8619 	.read_emulated       = emulator_read_emulated,
8620 	.write_emulated      = emulator_write_emulated,
8621 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8622 	.invlpg              = emulator_invlpg,
8623 	.pio_in_emulated     = emulator_pio_in_emulated,
8624 	.pio_out_emulated    = emulator_pio_out_emulated,
8625 	.get_segment         = emulator_get_segment,
8626 	.set_segment         = emulator_set_segment,
8627 	.get_cached_segment_base = emulator_get_cached_segment_base,
8628 	.get_gdt             = emulator_get_gdt,
8629 	.get_idt	     = emulator_get_idt,
8630 	.set_gdt             = emulator_set_gdt,
8631 	.set_idt	     = emulator_set_idt,
8632 	.get_cr              = emulator_get_cr,
8633 	.set_cr              = emulator_set_cr,
8634 	.cpl                 = emulator_get_cpl,
8635 	.get_dr              = emulator_get_dr,
8636 	.set_dr              = emulator_set_dr,
8637 	.set_msr_with_filter = emulator_set_msr_with_filter,
8638 	.get_msr_with_filter = emulator_get_msr_with_filter,
8639 	.get_msr             = emulator_get_msr,
8640 	.check_rdpmc_early   = emulator_check_rdpmc_early,
8641 	.read_pmc            = emulator_read_pmc,
8642 	.halt                = emulator_halt,
8643 	.wbinvd              = emulator_wbinvd,
8644 	.fix_hypercall       = emulator_fix_hypercall,
8645 	.intercept           = emulator_intercept,
8646 	.get_cpuid           = emulator_get_cpuid,
8647 	.guest_has_movbe     = emulator_guest_has_movbe,
8648 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8649 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8650 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8651 	.set_nmi_mask        = emulator_set_nmi_mask,
8652 	.is_smm              = emulator_is_smm,
8653 	.leave_smm           = emulator_leave_smm,
8654 	.triple_fault        = emulator_triple_fault,
8655 	.set_xcr             = emulator_set_xcr,
8656 	.get_untagged_addr   = emulator_get_untagged_addr,
8657 	.is_canonical_addr   = emulator_is_canonical_addr,
8658 };
8659 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8660 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8661 {
8662 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8663 	/*
8664 	 * an sti; sti; sequence only disable interrupts for the first
8665 	 * instruction. So, if the last instruction, be it emulated or
8666 	 * not, left the system with the INT_STI flag enabled, it
8667 	 * means that the last instruction is an sti. We should not
8668 	 * leave the flag on in this case. The same goes for mov ss
8669 	 */
8670 	if (int_shadow & mask)
8671 		mask = 0;
8672 	if (unlikely(int_shadow || mask)) {
8673 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8674 		if (!mask)
8675 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8676 	}
8677 }
8678 
inject_emulated_exception(struct kvm_vcpu * vcpu)8679 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8680 {
8681 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8682 
8683 	if (ctxt->exception.vector == PF_VECTOR)
8684 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8685 	else if (ctxt->exception.error_code_valid)
8686 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8687 				      ctxt->exception.error_code);
8688 	else
8689 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8690 }
8691 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8692 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8693 {
8694 	struct x86_emulate_ctxt *ctxt;
8695 
8696 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8697 	if (!ctxt) {
8698 		pr_err("failed to allocate vcpu's emulator\n");
8699 		return NULL;
8700 	}
8701 
8702 	ctxt->vcpu = vcpu;
8703 	ctxt->ops = &emulate_ops;
8704 	vcpu->arch.emulate_ctxt = ctxt;
8705 
8706 	return ctxt;
8707 }
8708 
init_emulate_ctxt(struct kvm_vcpu * vcpu)8709 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8710 {
8711 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8712 	int cs_db, cs_l;
8713 
8714 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8715 
8716 	ctxt->gpa_available = false;
8717 	ctxt->eflags = kvm_get_rflags(vcpu);
8718 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8719 
8720 	ctxt->eip = kvm_rip_read(vcpu);
8721 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8722 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8723 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8724 		     cs_db				? X86EMUL_MODE_PROT32 :
8725 							  X86EMUL_MODE_PROT16;
8726 	ctxt->interruptibility = 0;
8727 	ctxt->have_exception = false;
8728 	ctxt->exception.vector = -1;
8729 	ctxt->perm_ok = false;
8730 
8731 	init_decode_cache(ctxt);
8732 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8733 }
8734 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8735 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8736 {
8737 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8738 	int ret;
8739 
8740 	init_emulate_ctxt(vcpu);
8741 
8742 	ctxt->op_bytes = 2;
8743 	ctxt->ad_bytes = 2;
8744 	ctxt->_eip = ctxt->eip + inc_eip;
8745 	ret = emulate_int_real(ctxt, irq);
8746 
8747 	if (ret != X86EMUL_CONTINUE) {
8748 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8749 	} else {
8750 		ctxt->eip = ctxt->_eip;
8751 		kvm_rip_write(vcpu, ctxt->eip);
8752 		kvm_set_rflags(vcpu, ctxt->eflags);
8753 	}
8754 }
8755 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8756 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)8757 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8758 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
8759 {
8760 	struct kvm_run *run = vcpu->run;
8761 	u64 info[5];
8762 	u8 info_start;
8763 
8764 	/*
8765 	 * Zero the whole array used to retrieve the exit info, as casting to
8766 	 * u32 for select entries will leave some chunks uninitialized.
8767 	 */
8768 	memset(&info, 0, sizeof(info));
8769 
8770 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
8771 				    (u32 *)&info[3], (u32 *)&info[4]);
8772 
8773 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8774 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8775 
8776 	/*
8777 	 * There's currently space for 13 entries, but 5 are used for the exit
8778 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
8779 	 * when expanding kvm_run.emulation_failure in the future.
8780 	 */
8781 	if (WARN_ON_ONCE(ndata > 4))
8782 		ndata = 4;
8783 
8784 	/* Always include the flags as a 'data' entry. */
8785 	info_start = 1;
8786 	run->emulation_failure.flags = 0;
8787 
8788 	if (insn_size) {
8789 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8790 			      sizeof(run->emulation_failure.insn_bytes) != 16));
8791 		info_start += 2;
8792 		run->emulation_failure.flags |=
8793 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8794 		run->emulation_failure.insn_size = insn_size;
8795 		memset(run->emulation_failure.insn_bytes, 0x90,
8796 		       sizeof(run->emulation_failure.insn_bytes));
8797 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8798 	}
8799 
8800 	memcpy(&run->internal.data[info_start], info, sizeof(info));
8801 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8802 	       ndata * sizeof(data[0]));
8803 
8804 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8805 }
8806 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)8807 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8808 {
8809 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8810 
8811 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8812 				       ctxt->fetch.end - ctxt->fetch.data);
8813 }
8814 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)8815 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8816 					  u8 ndata)
8817 {
8818 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8819 }
8820 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8821 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)8822 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8823 {
8824 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8825 }
8826 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8827 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)8828 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8829 {
8830 	struct kvm *kvm = vcpu->kvm;
8831 
8832 	++vcpu->stat.insn_emulation_fail;
8833 	trace_kvm_emulate_insn_failed(vcpu);
8834 
8835 	if (emulation_type & EMULTYPE_VMWARE_GP) {
8836 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8837 		return 1;
8838 	}
8839 
8840 	if (kvm->arch.exit_on_emulation_error ||
8841 	    (emulation_type & EMULTYPE_SKIP)) {
8842 		prepare_emulation_ctxt_failure_exit(vcpu);
8843 		return 0;
8844 	}
8845 
8846 	kvm_queue_exception(vcpu, UD_VECTOR);
8847 
8848 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
8849 		prepare_emulation_ctxt_failure_exit(vcpu);
8850 		return 0;
8851 	}
8852 
8853 	return 1;
8854 }
8855 
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)8856 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
8857 					       gpa_t cr2_or_gpa,
8858 					       int emulation_type)
8859 {
8860 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8861 		return false;
8862 
8863 	/*
8864 	 * If the failed instruction faulted on an access to page tables that
8865 	 * are used to translate any part of the instruction, KVM can't resolve
8866 	 * the issue by unprotecting the gfn, as zapping the shadow page will
8867 	 * result in the instruction taking a !PRESENT page fault and thus put
8868 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
8869 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8870 	 * then zap the SPTE to unprotect the gfn, and then do it all over
8871 	 * again.  Report the error to userspace.
8872 	 */
8873 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
8874 		return false;
8875 
8876 	/*
8877 	 * If emulation may have been triggered by a write to a shadowed page
8878 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8879 	 * guest to let the CPU re-execute the instruction in the hope that the
8880 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
8881 	 */
8882 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
8883 
8884 	/*
8885 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
8886 	 * all SPTEs were already zapped by a different task.  The alternative
8887 	 * is to report the error to userspace and likely terminate the guest,
8888 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
8889 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
8890 	 */
8891 	return true;
8892 }
8893 
8894 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8895 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8896 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)8897 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8898 				unsigned long *db)
8899 {
8900 	u32 dr6 = 0;
8901 	int i;
8902 	u32 enable, rwlen;
8903 
8904 	enable = dr7;
8905 	rwlen = dr7 >> 16;
8906 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8907 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8908 			dr6 |= (1 << i);
8909 	return dr6;
8910 }
8911 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)8912 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8913 {
8914 	struct kvm_run *kvm_run = vcpu->run;
8915 
8916 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8917 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8918 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8919 		kvm_run->debug.arch.exception = DB_VECTOR;
8920 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
8921 		return 0;
8922 	}
8923 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8924 	return 1;
8925 }
8926 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)8927 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8928 {
8929 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
8930 	int r;
8931 
8932 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
8933 	if (unlikely(!r))
8934 		return 0;
8935 
8936 	kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
8937 
8938 	/*
8939 	 * rflags is the old, "raw" value of the flags.  The new value has
8940 	 * not been saved yet.
8941 	 *
8942 	 * This is correct even for TF set by the guest, because "the
8943 	 * processor will not generate this exception after the instruction
8944 	 * that sets the TF flag".
8945 	 */
8946 	if (unlikely(rflags & X86_EFLAGS_TF))
8947 		r = kvm_vcpu_do_singlestep(vcpu);
8948 	return r;
8949 }
8950 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8951 
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)8952 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
8953 {
8954 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8955 		return true;
8956 
8957 	/*
8958 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
8959 	 * active, but AMD compatible CPUs do not.
8960 	 */
8961 	if (!guest_cpuid_is_intel_compatible(vcpu))
8962 		return false;
8963 
8964 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
8965 }
8966 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)8967 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8968 					   int emulation_type, int *r)
8969 {
8970 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8971 
8972 	/*
8973 	 * Do not check for code breakpoints if hardware has already done the
8974 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
8975 	 * the instruction has passed all exception checks, and all intercepted
8976 	 * exceptions that trigger emulation have lower priority than code
8977 	 * breakpoints, i.e. the fact that the intercepted exception occurred
8978 	 * means any code breakpoints have already been serviced.
8979 	 *
8980 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
8981 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
8982 	 * the instruction being emulated.  The intent of forced emulation is
8983 	 * to behave as if KVM intercepted the instruction without an exception
8984 	 * and without a prefix.
8985 	 */
8986 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
8987 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
8988 		return false;
8989 
8990 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8991 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
8992 		struct kvm_run *kvm_run = vcpu->run;
8993 		unsigned long eip = kvm_get_linear_rip(vcpu);
8994 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
8995 					   vcpu->arch.guest_debug_dr7,
8996 					   vcpu->arch.eff_db);
8997 
8998 		if (dr6 != 0) {
8999 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9000 			kvm_run->debug.arch.pc = eip;
9001 			kvm_run->debug.arch.exception = DB_VECTOR;
9002 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
9003 			*r = 0;
9004 			return true;
9005 		}
9006 	}
9007 
9008 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9009 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
9010 		unsigned long eip = kvm_get_linear_rip(vcpu);
9011 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9012 					   vcpu->arch.dr7,
9013 					   vcpu->arch.db);
9014 
9015 		if (dr6 != 0) {
9016 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9017 			*r = 1;
9018 			return true;
9019 		}
9020 	}
9021 
9022 	return false;
9023 }
9024 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9025 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9026 {
9027 	switch (ctxt->opcode_len) {
9028 	case 1:
9029 		switch (ctxt->b) {
9030 		case 0xe4:	/* IN */
9031 		case 0xe5:
9032 		case 0xec:
9033 		case 0xed:
9034 		case 0xe6:	/* OUT */
9035 		case 0xe7:
9036 		case 0xee:
9037 		case 0xef:
9038 		case 0x6c:	/* INS */
9039 		case 0x6d:
9040 		case 0x6e:	/* OUTS */
9041 		case 0x6f:
9042 			return true;
9043 		}
9044 		break;
9045 	case 2:
9046 		switch (ctxt->b) {
9047 		case 0x33:	/* RDPMC */
9048 			return true;
9049 		}
9050 		break;
9051 	}
9052 
9053 	return false;
9054 }
9055 
9056 /*
9057  * Decode an instruction for emulation.  The caller is responsible for handling
9058  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
9059  * (and wrong) when emulating on an intercepted fault-like exception[*], as
9060  * code breakpoints have higher priority and thus have already been done by
9061  * hardware.
9062  *
9063  * [*] Except #MC, which is higher priority, but KVM should never emulate in
9064  *     response to a machine check.
9065  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9066 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9067 				    void *insn, int insn_len)
9068 {
9069 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9070 	int r;
9071 
9072 	init_emulate_ctxt(vcpu);
9073 
9074 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9075 
9076 	trace_kvm_emulate_insn_start(vcpu);
9077 	++vcpu->stat.insn_emulation;
9078 
9079 	return r;
9080 }
9081 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9082 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9083 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9084 			    int emulation_type, void *insn, int insn_len)
9085 {
9086 	int r;
9087 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9088 	bool writeback = true;
9089 
9090 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9091 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9092 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9093 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9094 
9095 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9096 	if (r != X86EMUL_CONTINUE) {
9097 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9098 			return 1;
9099 
9100 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9101 		return handle_emulation_failure(vcpu, emulation_type);
9102 	}
9103 
9104 	vcpu->arch.l1tf_flush_l1d = true;
9105 
9106 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9107 		kvm_clear_exception_queue(vcpu);
9108 
9109 		/*
9110 		 * Return immediately if RIP hits a code breakpoint, such #DBs
9111 		 * are fault-like and are higher priority than any faults on
9112 		 * the code fetch itself.
9113 		 */
9114 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9115 			return r;
9116 
9117 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
9118 						    insn, insn_len);
9119 		if (r != EMULATION_OK)  {
9120 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
9121 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9122 				kvm_queue_exception(vcpu, UD_VECTOR);
9123 				return 1;
9124 			}
9125 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9126 							       emulation_type))
9127 				return 1;
9128 
9129 			if (ctxt->have_exception &&
9130 			    !(emulation_type & EMULTYPE_SKIP)) {
9131 				/*
9132 				 * #UD should result in just EMULATION_FAILED, and trap-like
9133 				 * exception should not be encountered during decode.
9134 				 */
9135 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9136 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9137 				inject_emulated_exception(vcpu);
9138 				return 1;
9139 			}
9140 			return handle_emulation_failure(vcpu, emulation_type);
9141 		}
9142 	}
9143 
9144 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9145 	    !is_vmware_backdoor_opcode(ctxt)) {
9146 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9147 		return 1;
9148 	}
9149 
9150 	/*
9151 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9152 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9153 	 * The caller is responsible for updating interruptibility state and
9154 	 * injecting single-step #DBs.
9155 	 */
9156 	if (emulation_type & EMULTYPE_SKIP) {
9157 		if (ctxt->mode != X86EMUL_MODE_PROT64)
9158 			ctxt->eip = (u32)ctxt->_eip;
9159 		else
9160 			ctxt->eip = ctxt->_eip;
9161 
9162 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9163 			r = 1;
9164 			goto writeback;
9165 		}
9166 
9167 		kvm_rip_write(vcpu, ctxt->eip);
9168 		if (ctxt->eflags & X86_EFLAGS_RF)
9169 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9170 		return 1;
9171 	}
9172 
9173 	/*
9174 	 * If emulation was caused by a write-protection #PF on a non-page_table
9175 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9176 	 * and retry the instruction, as the vCPU is likely no longer using the
9177 	 * gfn as a page table.
9178 	 */
9179 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9180 	    !x86_page_table_writing_insn(ctxt) &&
9181 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9182 		return 1;
9183 
9184 	/* this is needed for vmware backdoor interface to work since it
9185 	   changes registers values  during IO operation */
9186 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9187 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9188 		emulator_invalidate_register_cache(ctxt);
9189 	}
9190 
9191 restart:
9192 	if (emulation_type & EMULTYPE_PF) {
9193 		/* Save the faulting GPA (cr2) in the address field */
9194 		ctxt->exception.address = cr2_or_gpa;
9195 
9196 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
9197 		if (vcpu->arch.mmu->root_role.direct) {
9198 			ctxt->gpa_available = true;
9199 			ctxt->gpa_val = cr2_or_gpa;
9200 		}
9201 	} else {
9202 		/* Sanitize the address out of an abundance of paranoia. */
9203 		ctxt->exception.address = 0;
9204 	}
9205 
9206 	/*
9207 	 * Check L1's instruction intercepts when emulating instructions for
9208 	 * L2, unless KVM is re-emulating a previously decoded instruction,
9209 	 * e.g. to complete userspace I/O, in which case KVM has already
9210 	 * checked the intercepts.
9211 	 */
9212 	r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9213 				   !(emulation_type & EMULTYPE_NO_DECODE));
9214 
9215 	if (r == EMULATION_INTERCEPTED)
9216 		return 1;
9217 
9218 	if (r == EMULATION_FAILED) {
9219 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9220 						       emulation_type))
9221 			return 1;
9222 
9223 		return handle_emulation_failure(vcpu, emulation_type);
9224 	}
9225 
9226 	if (ctxt->have_exception) {
9227 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9228 		vcpu->mmio_needed = false;
9229 		r = 1;
9230 		inject_emulated_exception(vcpu);
9231 	} else if (vcpu->arch.pio.count) {
9232 		if (!vcpu->arch.pio.in) {
9233 			/* FIXME: return into emulator if single-stepping.  */
9234 			vcpu->arch.pio.count = 0;
9235 		} else {
9236 			writeback = false;
9237 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
9238 		}
9239 		r = 0;
9240 	} else if (vcpu->mmio_needed) {
9241 		++vcpu->stat.mmio_exits;
9242 
9243 		if (!vcpu->mmio_is_write)
9244 			writeback = false;
9245 		r = 0;
9246 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9247 	} else if (vcpu->arch.complete_userspace_io) {
9248 		writeback = false;
9249 		r = 0;
9250 	} else if (r == EMULATION_RESTART)
9251 		goto restart;
9252 	else
9253 		r = 1;
9254 
9255 writeback:
9256 	if (writeback) {
9257 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9258 		toggle_interruptibility(vcpu, ctxt->interruptibility);
9259 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9260 
9261 		/*
9262 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9263 		 * only supports code breakpoints and general detect #DB, both
9264 		 * of which are fault-like.
9265 		 */
9266 		if (!ctxt->have_exception ||
9267 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9268 			kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9269 			if (ctxt->is_branch)
9270 				kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
9271 			kvm_rip_write(vcpu, ctxt->eip);
9272 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9273 				r = kvm_vcpu_do_singlestep(vcpu);
9274 			kvm_x86_call(update_emulated_instruction)(vcpu);
9275 			__kvm_set_rflags(vcpu, ctxt->eflags);
9276 		}
9277 
9278 		/*
9279 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9280 		 * do nothing, and it will be requested again as soon as
9281 		 * the shadow expires.  But we still need to check here,
9282 		 * because POPF has no interrupt shadow.
9283 		 */
9284 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9285 			kvm_make_request(KVM_REQ_EVENT, vcpu);
9286 	} else
9287 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9288 
9289 	return r;
9290 }
9291 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9292 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9293 {
9294 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9295 }
9296 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9297 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9298 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9299 					void *insn, int insn_len)
9300 {
9301 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9302 }
9303 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9304 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9305 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9306 {
9307 	vcpu->arch.pio.count = 0;
9308 	return 1;
9309 }
9310 
complete_fast_pio_out(struct kvm_vcpu * vcpu)9311 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9312 {
9313 	vcpu->arch.pio.count = 0;
9314 
9315 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
9316 		return 1;
9317 
9318 	return kvm_skip_emulated_instruction(vcpu);
9319 }
9320 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9321 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9322 			    unsigned short port)
9323 {
9324 	unsigned long val = kvm_rax_read(vcpu);
9325 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9326 
9327 	if (ret)
9328 		return ret;
9329 
9330 	/*
9331 	 * Workaround userspace that relies on old KVM behavior of %rip being
9332 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9333 	 */
9334 	if (port == 0x7e &&
9335 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9336 		vcpu->arch.complete_userspace_io =
9337 			complete_fast_pio_out_port_0x7e;
9338 		kvm_skip_emulated_instruction(vcpu);
9339 	} else {
9340 		vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9341 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9342 	}
9343 	return 0;
9344 }
9345 
complete_fast_pio_in(struct kvm_vcpu * vcpu)9346 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9347 {
9348 	unsigned long val;
9349 
9350 	/* We should only ever be called with arch.pio.count equal to 1 */
9351 	BUG_ON(vcpu->arch.pio.count != 1);
9352 
9353 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
9354 		vcpu->arch.pio.count = 0;
9355 		return 1;
9356 	}
9357 
9358 	/* For size less than 4 we merge, else we zero extend */
9359 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9360 
9361 	complete_emulator_pio_in(vcpu, &val);
9362 	kvm_rax_write(vcpu, val);
9363 
9364 	return kvm_skip_emulated_instruction(vcpu);
9365 }
9366 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9367 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9368 			   unsigned short port)
9369 {
9370 	unsigned long val;
9371 	int ret;
9372 
9373 	/* For size less than 4 we merge, else we zero extend */
9374 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9375 
9376 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
9377 	if (ret) {
9378 		kvm_rax_write(vcpu, val);
9379 		return ret;
9380 	}
9381 
9382 	vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
9383 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9384 
9385 	return 0;
9386 }
9387 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9388 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9389 {
9390 	int ret;
9391 
9392 	if (in)
9393 		ret = kvm_fast_pio_in(vcpu, size, port);
9394 	else
9395 		ret = kvm_fast_pio_out(vcpu, size, port);
9396 	return ret && kvm_skip_emulated_instruction(vcpu);
9397 }
9398 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9399 
kvmclock_cpu_down_prep(unsigned int cpu)9400 static int kvmclock_cpu_down_prep(unsigned int cpu)
9401 {
9402 	__this_cpu_write(cpu_tsc_khz, 0);
9403 	return 0;
9404 }
9405 
tsc_khz_changed(void * data)9406 static void tsc_khz_changed(void *data)
9407 {
9408 	struct cpufreq_freqs *freq = data;
9409 	unsigned long khz;
9410 
9411 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9412 
9413 	if (data)
9414 		khz = freq->new;
9415 	else
9416 		khz = cpufreq_quick_get(raw_smp_processor_id());
9417 	if (!khz)
9418 		khz = tsc_khz;
9419 	__this_cpu_write(cpu_tsc_khz, khz);
9420 }
9421 
9422 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9423 static void kvm_hyperv_tsc_notifier(void)
9424 {
9425 	struct kvm *kvm;
9426 	int cpu;
9427 
9428 	mutex_lock(&kvm_lock);
9429 	list_for_each_entry(kvm, &vm_list, vm_list)
9430 		kvm_make_mclock_inprogress_request(kvm);
9431 
9432 	/* no guest entries from this point */
9433 	hyperv_stop_tsc_emulation();
9434 
9435 	/* TSC frequency always matches when on Hyper-V */
9436 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9437 		for_each_present_cpu(cpu)
9438 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9439 	}
9440 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9441 
9442 	list_for_each_entry(kvm, &vm_list, vm_list) {
9443 		__kvm_start_pvclock_update(kvm);
9444 		pvclock_update_vm_gtod_copy(kvm);
9445 		kvm_end_pvclock_update(kvm);
9446 	}
9447 
9448 	mutex_unlock(&kvm_lock);
9449 }
9450 #endif
9451 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9452 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9453 {
9454 	struct kvm *kvm;
9455 	struct kvm_vcpu *vcpu;
9456 	int send_ipi = 0;
9457 	unsigned long i;
9458 
9459 	/*
9460 	 * We allow guests to temporarily run on slowing clocks,
9461 	 * provided we notify them after, or to run on accelerating
9462 	 * clocks, provided we notify them before.  Thus time never
9463 	 * goes backwards.
9464 	 *
9465 	 * However, we have a problem.  We can't atomically update
9466 	 * the frequency of a given CPU from this function; it is
9467 	 * merely a notifier, which can be called from any CPU.
9468 	 * Changing the TSC frequency at arbitrary points in time
9469 	 * requires a recomputation of local variables related to
9470 	 * the TSC for each VCPU.  We must flag these local variables
9471 	 * to be updated and be sure the update takes place with the
9472 	 * new frequency before any guests proceed.
9473 	 *
9474 	 * Unfortunately, the combination of hotplug CPU and frequency
9475 	 * change creates an intractable locking scenario; the order
9476 	 * of when these callouts happen is undefined with respect to
9477 	 * CPU hotplug, and they can race with each other.  As such,
9478 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9479 	 * undefined; you can actually have a CPU frequency change take
9480 	 * place in between the computation of X and the setting of the
9481 	 * variable.  To protect against this problem, all updates of
9482 	 * the per_cpu tsc_khz variable are done in an interrupt
9483 	 * protected IPI, and all callers wishing to update the value
9484 	 * must wait for a synchronous IPI to complete (which is trivial
9485 	 * if the caller is on the CPU already).  This establishes the
9486 	 * necessary total order on variable updates.
9487 	 *
9488 	 * Note that because a guest time update may take place
9489 	 * anytime after the setting of the VCPU's request bit, the
9490 	 * correct TSC value must be set before the request.  However,
9491 	 * to ensure the update actually makes it to any guest which
9492 	 * starts running in hardware virtualization between the set
9493 	 * and the acquisition of the spinlock, we must also ping the
9494 	 * CPU after setting the request bit.
9495 	 *
9496 	 */
9497 
9498 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9499 
9500 	mutex_lock(&kvm_lock);
9501 	list_for_each_entry(kvm, &vm_list, vm_list) {
9502 		kvm_for_each_vcpu(i, vcpu, kvm) {
9503 			if (vcpu->cpu != cpu)
9504 				continue;
9505 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9506 			if (vcpu->cpu != raw_smp_processor_id())
9507 				send_ipi = 1;
9508 		}
9509 	}
9510 	mutex_unlock(&kvm_lock);
9511 
9512 	if (freq->old < freq->new && send_ipi) {
9513 		/*
9514 		 * We upscale the frequency.  Must make the guest
9515 		 * doesn't see old kvmclock values while running with
9516 		 * the new frequency, otherwise we risk the guest sees
9517 		 * time go backwards.
9518 		 *
9519 		 * In case we update the frequency for another cpu
9520 		 * (which might be in guest context) send an interrupt
9521 		 * to kick the cpu out of guest context.  Next time
9522 		 * guest context is entered kvmclock will be updated,
9523 		 * so the guest will not see stale values.
9524 		 */
9525 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9526 	}
9527 }
9528 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9529 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9530 				     void *data)
9531 {
9532 	struct cpufreq_freqs *freq = data;
9533 	int cpu;
9534 
9535 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9536 		return 0;
9537 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9538 		return 0;
9539 
9540 	for_each_cpu(cpu, freq->policy->cpus)
9541 		__kvmclock_cpufreq_notifier(freq, cpu);
9542 
9543 	return 0;
9544 }
9545 
9546 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9547 	.notifier_call  = kvmclock_cpufreq_notifier
9548 };
9549 
kvmclock_cpu_online(unsigned int cpu)9550 static int kvmclock_cpu_online(unsigned int cpu)
9551 {
9552 	tsc_khz_changed(NULL);
9553 	return 0;
9554 }
9555 
kvm_timer_init(void)9556 static void kvm_timer_init(void)
9557 {
9558 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9559 		max_tsc_khz = tsc_khz;
9560 
9561 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9562 			struct cpufreq_policy *policy;
9563 			int cpu;
9564 
9565 			cpu = get_cpu();
9566 			policy = cpufreq_cpu_get(cpu);
9567 			if (policy) {
9568 				if (policy->cpuinfo.max_freq)
9569 					max_tsc_khz = policy->cpuinfo.max_freq;
9570 				cpufreq_cpu_put(policy);
9571 			}
9572 			put_cpu();
9573 		}
9574 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9575 					  CPUFREQ_TRANSITION_NOTIFIER);
9576 
9577 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9578 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9579 	}
9580 }
9581 
9582 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9583 static void pvclock_gtod_update_fn(struct work_struct *work)
9584 {
9585 	struct kvm *kvm;
9586 	struct kvm_vcpu *vcpu;
9587 	unsigned long i;
9588 
9589 	mutex_lock(&kvm_lock);
9590 	list_for_each_entry(kvm, &vm_list, vm_list)
9591 		kvm_for_each_vcpu(i, vcpu, kvm)
9592 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9593 	atomic_set(&kvm_guest_has_master_clock, 0);
9594 	mutex_unlock(&kvm_lock);
9595 }
9596 
9597 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9598 
9599 /*
9600  * Indirection to move queue_work() out of the tk_core.seq write held
9601  * region to prevent possible deadlocks against time accessors which
9602  * are invoked with work related locks held.
9603  */
pvclock_irq_work_fn(struct irq_work * w)9604 static void pvclock_irq_work_fn(struct irq_work *w)
9605 {
9606 	queue_work(system_long_wq, &pvclock_gtod_work);
9607 }
9608 
9609 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9610 
9611 /*
9612  * Notification about pvclock gtod data update.
9613  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9614 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9615 			       void *priv)
9616 {
9617 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9618 	struct timekeeper *tk = priv;
9619 
9620 	update_pvclock_gtod(tk);
9621 
9622 	/*
9623 	 * Disable master clock if host does not trust, or does not use,
9624 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9625 	 * this is invoked with tk_core.seq write held.
9626 	 */
9627 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9628 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9629 		irq_work_queue(&pvclock_irq_work);
9630 	return 0;
9631 }
9632 
9633 static struct notifier_block pvclock_gtod_notifier = {
9634 	.notifier_call = pvclock_gtod_notify,
9635 };
9636 #endif
9637 
kvm_ops_update(struct kvm_x86_init_ops * ops)9638 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9639 {
9640 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9641 
9642 #define __KVM_X86_OP(func) \
9643 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9644 #define KVM_X86_OP(func) \
9645 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9646 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9647 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9648 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9649 					   (void *)__static_call_return0);
9650 #include <asm/kvm-x86-ops.h>
9651 #undef __KVM_X86_OP
9652 
9653 	kvm_pmu_ops_update(ops->pmu_ops);
9654 }
9655 
kvm_x86_check_processor_compatibility(void)9656 static int kvm_x86_check_processor_compatibility(void)
9657 {
9658 	int cpu = smp_processor_id();
9659 	struct cpuinfo_x86 *c = &cpu_data(cpu);
9660 
9661 	/*
9662 	 * Compatibility checks are done when loading KVM and when enabling
9663 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9664 	 * compatible, i.e. KVM should never perform a compatibility check on
9665 	 * an offline CPU.
9666 	 */
9667 	WARN_ON(!cpu_online(cpu));
9668 
9669 	if (__cr4_reserved_bits(cpu_has, c) !=
9670 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9671 		return -EIO;
9672 
9673 	return kvm_x86_call(check_processor_compatibility)();
9674 }
9675 
kvm_x86_check_cpu_compat(void * ret)9676 static void kvm_x86_check_cpu_compat(void *ret)
9677 {
9678 	*(int *)ret = kvm_x86_check_processor_compatibility();
9679 }
9680 
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9681 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9682 {
9683 	u64 host_pat;
9684 	int r, cpu;
9685 
9686 	guard(mutex)(&vendor_module_lock);
9687 
9688 	if (kvm_x86_ops.enable_virtualization_cpu) {
9689 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9690 		return -EEXIST;
9691 	}
9692 
9693 	/*
9694 	 * KVM explicitly assumes that the guest has an FPU and
9695 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9696 	 * vCPU's FPU state as a fxregs_state struct.
9697 	 */
9698 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9699 		pr_err("inadequate fpu\n");
9700 		return -EOPNOTSUPP;
9701 	}
9702 
9703 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9704 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9705 		return -EOPNOTSUPP;
9706 	}
9707 
9708 	/*
9709 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9710 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
9711 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
9712 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
9713 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9714 	 */
9715 	if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9716 	    (host_pat & GENMASK(2, 0)) != 6) {
9717 		pr_err("host PAT[0] is not WB\n");
9718 		return -EIO;
9719 	}
9720 
9721 	memset(&kvm_caps, 0, sizeof(kvm_caps));
9722 
9723 	x86_emulator_cache = kvm_alloc_emulator_cache();
9724 	if (!x86_emulator_cache) {
9725 		pr_err("failed to allocate cache for x86 emulator\n");
9726 		return -ENOMEM;
9727 	}
9728 
9729 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9730 	if (!user_return_msrs) {
9731 		pr_err("failed to allocate percpu kvm_user_return_msrs\n");
9732 		r = -ENOMEM;
9733 		goto out_free_x86_emulator_cache;
9734 	}
9735 	kvm_nr_uret_msrs = 0;
9736 
9737 	r = kvm_mmu_vendor_module_init();
9738 	if (r)
9739 		goto out_free_percpu;
9740 
9741 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
9742 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
9743 
9744 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9745 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9746 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
9747 	}
9748 
9749 	rdmsrl_safe(MSR_EFER, &kvm_host.efer);
9750 
9751 	if (boot_cpu_has(X86_FEATURE_XSAVES))
9752 		rdmsrl(MSR_IA32_XSS, kvm_host.xss);
9753 
9754 	kvm_init_pmu_capability(ops->pmu_ops);
9755 
9756 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
9757 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
9758 
9759 	r = ops->hardware_setup();
9760 	if (r != 0)
9761 		goto out_mmu_exit;
9762 
9763 	kvm_ops_update(ops);
9764 
9765 	for_each_online_cpu(cpu) {
9766 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
9767 		if (r < 0)
9768 			goto out_unwind_ops;
9769 	}
9770 
9771 	/*
9772 	 * Point of no return!  DO NOT add error paths below this point unless
9773 	 * absolutely necessary, as most operations from this point forward
9774 	 * require unwinding.
9775 	 */
9776 	kvm_timer_init();
9777 
9778 	if (pi_inject_timer == -1)
9779 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9780 #ifdef CONFIG_X86_64
9781 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9782 
9783 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9784 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9785 #endif
9786 
9787 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9788 
9789 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9790 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9791 
9792 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9793 		kvm_caps.supported_xss = 0;
9794 
9795 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9796 	cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9797 #undef __kvm_cpu_cap_has
9798 
9799 	if (kvm_caps.has_tsc_control) {
9800 		/*
9801 		 * Make sure the user can only configure tsc_khz values that
9802 		 * fit into a signed integer.
9803 		 * A min value is not calculated because it will always
9804 		 * be 1 on all machines.
9805 		 */
9806 		u64 max = min(0x7fffffffULL,
9807 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9808 		kvm_caps.max_guest_tsc_khz = max;
9809 	}
9810 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9811 	kvm_init_msr_lists();
9812 	return 0;
9813 
9814 out_unwind_ops:
9815 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9816 	kvm_x86_call(hardware_unsetup)();
9817 out_mmu_exit:
9818 	kvm_mmu_vendor_module_exit();
9819 out_free_percpu:
9820 	free_percpu(user_return_msrs);
9821 out_free_x86_emulator_cache:
9822 	kmem_cache_destroy(x86_emulator_cache);
9823 	return r;
9824 }
9825 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9826 
kvm_x86_vendor_exit(void)9827 void kvm_x86_vendor_exit(void)
9828 {
9829 	kvm_unregister_perf_callbacks();
9830 
9831 #ifdef CONFIG_X86_64
9832 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9833 		clear_hv_tscchange_cb();
9834 #endif
9835 	kvm_lapic_exit();
9836 
9837 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9838 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9839 					    CPUFREQ_TRANSITION_NOTIFIER);
9840 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9841 	}
9842 #ifdef CONFIG_X86_64
9843 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9844 	irq_work_sync(&pvclock_irq_work);
9845 	cancel_work_sync(&pvclock_gtod_work);
9846 #endif
9847 	kvm_x86_call(hardware_unsetup)();
9848 	kvm_mmu_vendor_module_exit();
9849 	free_percpu(user_return_msrs);
9850 	kmem_cache_destroy(x86_emulator_cache);
9851 #ifdef CONFIG_KVM_XEN
9852 	static_key_deferred_flush(&kvm_xen_enabled);
9853 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9854 #endif
9855 	mutex_lock(&vendor_module_lock);
9856 	kvm_x86_ops.enable_virtualization_cpu = NULL;
9857 	mutex_unlock(&vendor_module_lock);
9858 }
9859 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9860 
9861 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)9862 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9863 			        unsigned long clock_type)
9864 {
9865 	struct kvm_clock_pairing clock_pairing;
9866 	struct timespec64 ts;
9867 	u64 cycle;
9868 	int ret;
9869 
9870 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9871 		return -KVM_EOPNOTSUPP;
9872 
9873 	/*
9874 	 * When tsc is in permanent catchup mode guests won't be able to use
9875 	 * pvclock_read_retry loop to get consistent view of pvclock
9876 	 */
9877 	if (vcpu->arch.tsc_always_catchup)
9878 		return -KVM_EOPNOTSUPP;
9879 
9880 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9881 		return -KVM_EOPNOTSUPP;
9882 
9883 	clock_pairing.sec = ts.tv_sec;
9884 	clock_pairing.nsec = ts.tv_nsec;
9885 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9886 	clock_pairing.flags = 0;
9887 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9888 
9889 	ret = 0;
9890 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9891 			    sizeof(struct kvm_clock_pairing)))
9892 		ret = -KVM_EFAULT;
9893 
9894 	return ret;
9895 }
9896 #endif
9897 
9898 /*
9899  * kvm_pv_kick_cpu_op:  Kick a vcpu.
9900  *
9901  * @apicid - apicid of vcpu to be kicked.
9902  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)9903 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9904 {
9905 	/*
9906 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9907 	 * common code, e.g. for tracing. Defer initialization to the compiler.
9908 	 */
9909 	struct kvm_lapic_irq lapic_irq = {
9910 		.delivery_mode = APIC_DM_REMRD,
9911 		.dest_mode = APIC_DEST_PHYSICAL,
9912 		.shorthand = APIC_DEST_NOSHORT,
9913 		.dest_id = apicid,
9914 	};
9915 
9916 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9917 }
9918 
kvm_apicv_activated(struct kvm * kvm)9919 bool kvm_apicv_activated(struct kvm *kvm)
9920 {
9921 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9922 }
9923 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9924 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)9925 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9926 {
9927 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9928 	ulong vcpu_reasons =
9929 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
9930 
9931 	return (vm_reasons | vcpu_reasons) == 0;
9932 }
9933 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
9934 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)9935 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9936 				       enum kvm_apicv_inhibit reason, bool set)
9937 {
9938 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
9939 
9940 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
9941 
9942 	if (set)
9943 		__set_bit(reason, inhibits);
9944 	else
9945 		__clear_bit(reason, inhibits);
9946 
9947 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9948 }
9949 
kvm_apicv_init(struct kvm * kvm)9950 static void kvm_apicv_init(struct kvm *kvm)
9951 {
9952 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
9953 						       APICV_INHIBIT_REASON_DISABLED;
9954 
9955 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
9956 
9957 	init_rwsem(&kvm->arch.apicv_update_lock);
9958 }
9959 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)9960 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
9961 {
9962 	struct kvm_vcpu *target = NULL;
9963 	struct kvm_apic_map *map;
9964 
9965 	vcpu->stat.directed_yield_attempted++;
9966 
9967 	if (single_task_running())
9968 		goto no_yield;
9969 
9970 	rcu_read_lock();
9971 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
9972 
9973 	if (likely(map) && dest_id <= map->max_apic_id) {
9974 		dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
9975 		if (map->phys_map[dest_id])
9976 			target = map->phys_map[dest_id]->vcpu;
9977 	}
9978 
9979 	rcu_read_unlock();
9980 
9981 	if (!target || !READ_ONCE(target->ready))
9982 		goto no_yield;
9983 
9984 	/* Ignore requests to yield to self */
9985 	if (vcpu == target)
9986 		goto no_yield;
9987 
9988 	if (kvm_vcpu_yield_to(target) <= 0)
9989 		goto no_yield;
9990 
9991 	vcpu->stat.directed_yield_successful++;
9992 
9993 no_yield:
9994 	return;
9995 }
9996 
complete_hypercall_exit(struct kvm_vcpu * vcpu)9997 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9998 {
9999 	u64 ret = vcpu->run->hypercall.ret;
10000 
10001 	if (!is_64_bit_hypercall(vcpu))
10002 		ret = (u32)ret;
10003 	kvm_rax_write(vcpu, ret);
10004 	++vcpu->stat.hypercalls;
10005 	return kvm_skip_emulated_instruction(vcpu);
10006 }
10007 
__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)10008 unsigned long __kvm_emulate_hypercall(struct kvm_vcpu *vcpu, unsigned long nr,
10009 				      unsigned long a0, unsigned long a1,
10010 				      unsigned long a2, unsigned long a3,
10011 				      int op_64_bit, int cpl)
10012 {
10013 	unsigned long ret;
10014 
10015 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
10016 
10017 	if (!op_64_bit) {
10018 		nr &= 0xFFFFFFFF;
10019 		a0 &= 0xFFFFFFFF;
10020 		a1 &= 0xFFFFFFFF;
10021 		a2 &= 0xFFFFFFFF;
10022 		a3 &= 0xFFFFFFFF;
10023 	}
10024 
10025 	if (cpl) {
10026 		ret = -KVM_EPERM;
10027 		goto out;
10028 	}
10029 
10030 	ret = -KVM_ENOSYS;
10031 
10032 	switch (nr) {
10033 	case KVM_HC_VAPIC_POLL_IRQ:
10034 		ret = 0;
10035 		break;
10036 	case KVM_HC_KICK_CPU:
10037 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10038 			break;
10039 
10040 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10041 		kvm_sched_yield(vcpu, a1);
10042 		ret = 0;
10043 		break;
10044 #ifdef CONFIG_X86_64
10045 	case KVM_HC_CLOCK_PAIRING:
10046 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10047 		break;
10048 #endif
10049 	case KVM_HC_SEND_IPI:
10050 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10051 			break;
10052 
10053 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10054 		break;
10055 	case KVM_HC_SCHED_YIELD:
10056 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10057 			break;
10058 
10059 		kvm_sched_yield(vcpu, a0);
10060 		ret = 0;
10061 		break;
10062 	case KVM_HC_MAP_GPA_RANGE: {
10063 		u64 gpa = a0, npages = a1, attrs = a2;
10064 
10065 		ret = -KVM_ENOSYS;
10066 		if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
10067 			break;
10068 
10069 		if (!PAGE_ALIGNED(gpa) || !npages ||
10070 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10071 			ret = -KVM_EINVAL;
10072 			break;
10073 		}
10074 
10075 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
10076 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
10077 		vcpu->run->hypercall.args[0]  = gpa;
10078 		vcpu->run->hypercall.args[1]  = npages;
10079 		vcpu->run->hypercall.args[2]  = attrs;
10080 		vcpu->run->hypercall.flags    = 0;
10081 		if (op_64_bit)
10082 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10083 
10084 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10085 		vcpu->arch.complete_userspace_io = complete_hypercall_exit;
10086 		/* stat is incremented on completion. */
10087 		return 0;
10088 	}
10089 	default:
10090 		ret = -KVM_ENOSYS;
10091 		break;
10092 	}
10093 
10094 out:
10095 	++vcpu->stat.hypercalls;
10096 	return ret;
10097 }
10098 EXPORT_SYMBOL_GPL(__kvm_emulate_hypercall);
10099 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10100 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10101 {
10102 	unsigned long nr, a0, a1, a2, a3, ret;
10103 	int op_64_bit;
10104 	int cpl;
10105 
10106 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
10107 		return kvm_xen_hypercall(vcpu);
10108 
10109 	if (kvm_hv_hypercall_enabled(vcpu))
10110 		return kvm_hv_hypercall(vcpu);
10111 
10112 	nr = kvm_rax_read(vcpu);
10113 	a0 = kvm_rbx_read(vcpu);
10114 	a1 = kvm_rcx_read(vcpu);
10115 	a2 = kvm_rdx_read(vcpu);
10116 	a3 = kvm_rsi_read(vcpu);
10117 	op_64_bit = is_64_bit_hypercall(vcpu);
10118 	cpl = kvm_x86_call(get_cpl)(vcpu);
10119 
10120 	ret = __kvm_emulate_hypercall(vcpu, nr, a0, a1, a2, a3, op_64_bit, cpl);
10121 	if (nr == KVM_HC_MAP_GPA_RANGE && !ret)
10122 		/* MAP_GPA tosses the request to the user space. */
10123 		return 0;
10124 
10125 	if (!op_64_bit)
10126 		ret = (u32)ret;
10127 	kvm_rax_write(vcpu, ret);
10128 
10129 	return kvm_skip_emulated_instruction(vcpu);
10130 }
10131 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10132 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10133 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10134 {
10135 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10136 	char instruction[3];
10137 	unsigned long rip = kvm_rip_read(vcpu);
10138 
10139 	/*
10140 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10141 	 * the pieces.
10142 	 */
10143 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10144 		ctxt->exception.error_code_valid = false;
10145 		ctxt->exception.vector = UD_VECTOR;
10146 		ctxt->have_exception = true;
10147 		return X86EMUL_PROPAGATE_FAULT;
10148 	}
10149 
10150 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
10151 
10152 	return emulator_write_emulated(ctxt, rip, instruction, 3,
10153 		&ctxt->exception);
10154 }
10155 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10156 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10157 {
10158 	return vcpu->run->request_interrupt_window &&
10159 		likely(!pic_in_kernel(vcpu->kvm));
10160 }
10161 
10162 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)10163 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10164 {
10165 	struct kvm_run *kvm_run = vcpu->run;
10166 
10167 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10168 	kvm_run->cr8 = kvm_get_cr8(vcpu);
10169 	kvm_run->apic_base = vcpu->arch.apic_base;
10170 
10171 	kvm_run->ready_for_interrupt_injection =
10172 		pic_in_kernel(vcpu->kvm) ||
10173 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
10174 
10175 	if (is_smm(vcpu))
10176 		kvm_run->flags |= KVM_RUN_X86_SMM;
10177 	if (is_guest_mode(vcpu))
10178 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10179 }
10180 
update_cr8_intercept(struct kvm_vcpu * vcpu)10181 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10182 {
10183 	int max_irr, tpr;
10184 
10185 	if (!kvm_x86_ops.update_cr8_intercept)
10186 		return;
10187 
10188 	if (!lapic_in_kernel(vcpu))
10189 		return;
10190 
10191 	if (vcpu->arch.apic->apicv_active)
10192 		return;
10193 
10194 	if (!vcpu->arch.apic->vapic_addr)
10195 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10196 	else
10197 		max_irr = -1;
10198 
10199 	if (max_irr != -1)
10200 		max_irr >>= 4;
10201 
10202 	tpr = kvm_lapic_get_cr8(vcpu);
10203 
10204 	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10205 }
10206 
10207 
kvm_check_nested_events(struct kvm_vcpu * vcpu)10208 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10209 {
10210 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10211 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
10212 		return 1;
10213 	}
10214 
10215 	return kvm_x86_ops.nested_ops->check_events(vcpu);
10216 }
10217 
kvm_inject_exception(struct kvm_vcpu * vcpu)10218 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10219 {
10220 	/*
10221 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10222 	 * exceptions don't report error codes.  The presence of an error code
10223 	 * is carried with the exception and only stripped when the exception
10224 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10225 	 * report an error code despite the CPU being in Real Mode.
10226 	 */
10227 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10228 
10229 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
10230 				vcpu->arch.exception.has_error_code,
10231 				vcpu->arch.exception.error_code,
10232 				vcpu->arch.exception.injected);
10233 
10234 	kvm_x86_call(inject_exception)(vcpu);
10235 }
10236 
10237 /*
10238  * Check for any event (interrupt or exception) that is ready to be injected,
10239  * and if there is at least one event, inject the event with the highest
10240  * priority.  This handles both "pending" events, i.e. events that have never
10241  * been injected into the guest, and "injected" events, i.e. events that were
10242  * injected as part of a previous VM-Enter, but weren't successfully delivered
10243  * and need to be re-injected.
10244  *
10245  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10246  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
10247  * be able to inject exceptions in the "middle" of an instruction, and so must
10248  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10249  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10250  * boundaries is necessary and correct.
10251  *
10252  * For simplicity, KVM uses a single path to inject all events (except events
10253  * that are injected directly from L1 to L2) and doesn't explicitly track
10254  * instruction boundaries for asynchronous events.  However, because VM-Exits
10255  * that can occur during instruction execution typically result in KVM skipping
10256  * the instruction or injecting an exception, e.g. instruction and exception
10257  * intercepts, and because pending exceptions have higher priority than pending
10258  * interrupts, KVM still honors instruction boundaries in most scenarios.
10259  *
10260  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10261  * the instruction or inject an exception, then KVM can incorrecty inject a new
10262  * asynchronous event if the event became pending after the CPU fetched the
10263  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
10264  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10265  * injected on the restarted instruction instead of being deferred until the
10266  * instruction completes.
10267  *
10268  * In practice, this virtualization hole is unlikely to be observed by the
10269  * guest, and even less likely to cause functional problems.  To detect the
10270  * hole, the guest would have to trigger an event on a side effect of an early
10271  * phase of instruction execution, e.g. on the instruction fetch from memory.
10272  * And for it to be a functional problem, the guest would need to depend on the
10273  * ordering between that side effect, the instruction completing, _and_ the
10274  * delivery of the asynchronous event.
10275  */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10276 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10277 				       bool *req_immediate_exit)
10278 {
10279 	bool can_inject;
10280 	int r;
10281 
10282 	/*
10283 	 * Process nested events first, as nested VM-Exit supersedes event
10284 	 * re-injection.  If there's an event queued for re-injection, it will
10285 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10286 	 */
10287 	if (is_guest_mode(vcpu))
10288 		r = kvm_check_nested_events(vcpu);
10289 	else
10290 		r = 0;
10291 
10292 	/*
10293 	 * Re-inject exceptions and events *especially* if immediate entry+exit
10294 	 * to/from L2 is needed, as any event that has already been injected
10295 	 * into L2 needs to complete its lifecycle before injecting a new event.
10296 	 *
10297 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
10298 	 * This collision arises if an exception occurred while vectoring the
10299 	 * injected event, KVM intercepted said exception, and KVM ultimately
10300 	 * determined the fault belongs to the guest and queues the exception
10301 	 * for injection back into the guest.
10302 	 *
10303 	 * "Injected" interrupts can also collide with pending exceptions if
10304 	 * userspace ignores the "ready for injection" flag and blindly queues
10305 	 * an interrupt.  In that case, prioritizing the exception is correct,
10306 	 * as the exception "occurred" before the exit to userspace.  Trap-like
10307 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10308 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10309 	 * priority, they're only generated (pended) during instruction
10310 	 * execution, and interrupts are recognized at instruction boundaries.
10311 	 * Thus a pending fault-like exception means the fault occurred on the
10312 	 * *previous* instruction and must be serviced prior to recognizing any
10313 	 * new events in order to fully complete the previous instruction.
10314 	 */
10315 	if (vcpu->arch.exception.injected)
10316 		kvm_inject_exception(vcpu);
10317 	else if (kvm_is_exception_pending(vcpu))
10318 		; /* see above */
10319 	else if (vcpu->arch.nmi_injected)
10320 		kvm_x86_call(inject_nmi)(vcpu);
10321 	else if (vcpu->arch.interrupt.injected)
10322 		kvm_x86_call(inject_irq)(vcpu, true);
10323 
10324 	/*
10325 	 * Exceptions that morph to VM-Exits are handled above, and pending
10326 	 * exceptions on top of injected exceptions that do not VM-Exit should
10327 	 * either morph to #DF or, sadly, override the injected exception.
10328 	 */
10329 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
10330 		     vcpu->arch.exception.pending);
10331 
10332 	/*
10333 	 * Bail if immediate entry+exit to/from the guest is needed to complete
10334 	 * nested VM-Enter or event re-injection so that a different pending
10335 	 * event can be serviced (or if KVM needs to exit to userspace).
10336 	 *
10337 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
10338 	 * VM-Exit will have cleared exceptions that were meant for L2, but
10339 	 * there may now be events that can be injected into L1.
10340 	 */
10341 	if (r < 0)
10342 		goto out;
10343 
10344 	/*
10345 	 * A pending exception VM-Exit should either result in nested VM-Exit
10346 	 * or force an immediate re-entry and exit to/from L2, and exception
10347 	 * VM-Exits cannot be injected (flag should _never_ be set).
10348 	 */
10349 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10350 		     vcpu->arch.exception_vmexit.pending);
10351 
10352 	/*
10353 	 * New events, other than exceptions, cannot be injected if KVM needs
10354 	 * to re-inject a previous event.  See above comments on re-injecting
10355 	 * for why pending exceptions get priority.
10356 	 */
10357 	can_inject = !kvm_event_needs_reinjection(vcpu);
10358 
10359 	if (vcpu->arch.exception.pending) {
10360 		/*
10361 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10362 		 * value pushed on the stack.  Trap-like exception and all #DBs
10363 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
10364 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10365 		 *
10366 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10367 		 * describe the behavior of General Detect #DBs, which are
10368 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
10369 		 */
10370 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10371 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10372 					     X86_EFLAGS_RF);
10373 
10374 		if (vcpu->arch.exception.vector == DB_VECTOR) {
10375 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10376 			if (vcpu->arch.dr7 & DR7_GD) {
10377 				vcpu->arch.dr7 &= ~DR7_GD;
10378 				kvm_update_dr7(vcpu);
10379 			}
10380 		}
10381 
10382 		kvm_inject_exception(vcpu);
10383 
10384 		vcpu->arch.exception.pending = false;
10385 		vcpu->arch.exception.injected = true;
10386 
10387 		can_inject = false;
10388 	}
10389 
10390 	/* Don't inject interrupts if the user asked to avoid doing so */
10391 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10392 		return 0;
10393 
10394 	/*
10395 	 * Finally, inject interrupt events.  If an event cannot be injected
10396 	 * due to architectural conditions (e.g. IF=0) a window-open exit
10397 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
10398 	 * and can architecturally be injected, but we cannot do it right now:
10399 	 * an interrupt could have arrived just now and we have to inject it
10400 	 * as a vmexit, or there could already an event in the queue, which is
10401 	 * indicated by can_inject.  In that case we request an immediate exit
10402 	 * in order to make progress and get back here for another iteration.
10403 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10404 	 */
10405 #ifdef CONFIG_KVM_SMM
10406 	if (vcpu->arch.smi_pending) {
10407 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10408 				 -EBUSY;
10409 		if (r < 0)
10410 			goto out;
10411 		if (r) {
10412 			vcpu->arch.smi_pending = false;
10413 			++vcpu->arch.smi_count;
10414 			enter_smm(vcpu);
10415 			can_inject = false;
10416 		} else
10417 			kvm_x86_call(enable_smi_window)(vcpu);
10418 	}
10419 #endif
10420 
10421 	if (vcpu->arch.nmi_pending) {
10422 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10423 				 -EBUSY;
10424 		if (r < 0)
10425 			goto out;
10426 		if (r) {
10427 			--vcpu->arch.nmi_pending;
10428 			vcpu->arch.nmi_injected = true;
10429 			kvm_x86_call(inject_nmi)(vcpu);
10430 			can_inject = false;
10431 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10432 		}
10433 		if (vcpu->arch.nmi_pending)
10434 			kvm_x86_call(enable_nmi_window)(vcpu);
10435 	}
10436 
10437 	if (kvm_cpu_has_injectable_intr(vcpu)) {
10438 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10439 				 -EBUSY;
10440 		if (r < 0)
10441 			goto out;
10442 		if (r) {
10443 			int irq = kvm_cpu_get_interrupt(vcpu);
10444 
10445 			if (!WARN_ON_ONCE(irq == -1)) {
10446 				kvm_queue_interrupt(vcpu, irq, false);
10447 				kvm_x86_call(inject_irq)(vcpu, false);
10448 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10449 			}
10450 		}
10451 		if (kvm_cpu_has_injectable_intr(vcpu))
10452 			kvm_x86_call(enable_irq_window)(vcpu);
10453 	}
10454 
10455 	if (is_guest_mode(vcpu) &&
10456 	    kvm_x86_ops.nested_ops->has_events &&
10457 	    kvm_x86_ops.nested_ops->has_events(vcpu, true))
10458 		*req_immediate_exit = true;
10459 
10460 	/*
10461 	 * KVM must never queue a new exception while injecting an event; KVM
10462 	 * is done emulating and should only propagate the to-be-injected event
10463 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
10464 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
10465 	 * exception and start the cycle all over.
10466 	 *
10467 	 * Exempt triple faults as they have special handling and won't put the
10468 	 * vCPU into an infinite loop.  Triple fault can be queued when running
10469 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
10470 	 * Mode events (see kvm_inject_realmode_interrupt()).
10471 	 */
10472 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
10473 		     vcpu->arch.exception_vmexit.pending);
10474 	return 0;
10475 
10476 out:
10477 	if (r == -EBUSY) {
10478 		*req_immediate_exit = true;
10479 		r = 0;
10480 	}
10481 	return r;
10482 }
10483 
process_nmi(struct kvm_vcpu * vcpu)10484 static void process_nmi(struct kvm_vcpu *vcpu)
10485 {
10486 	unsigned int limit;
10487 
10488 	/*
10489 	 * x86 is limited to one NMI pending, but because KVM can't react to
10490 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10491 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
10492 	 * up at the same time.  To handle this scenario, allow two NMIs to be
10493 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10494 	 * waiting for a previous NMI injection to complete (which effectively
10495 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
10496 	 * will request an NMI window to handle the second NMI.
10497 	 */
10498 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10499 		limit = 1;
10500 	else
10501 		limit = 2;
10502 
10503 	/*
10504 	 * Adjust the limit to account for pending virtual NMIs, which aren't
10505 	 * tracked in vcpu->arch.nmi_pending.
10506 	 */
10507 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
10508 		limit--;
10509 
10510 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10511 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10512 
10513 	if (vcpu->arch.nmi_pending &&
10514 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
10515 		vcpu->arch.nmi_pending--;
10516 
10517 	if (vcpu->arch.nmi_pending)
10518 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10519 }
10520 
10521 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10522 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10523 {
10524 	return vcpu->arch.nmi_pending +
10525 	       kvm_x86_call(is_vnmi_pending)(vcpu);
10526 }
10527 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10528 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10529 				       unsigned long *vcpu_bitmap)
10530 {
10531 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10532 }
10533 
kvm_make_scan_ioapic_request(struct kvm * kvm)10534 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10535 {
10536 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10537 }
10538 
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10539 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10540 {
10541 	struct kvm_lapic *apic = vcpu->arch.apic;
10542 	bool activate;
10543 
10544 	if (!lapic_in_kernel(vcpu))
10545 		return;
10546 
10547 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10548 	preempt_disable();
10549 
10550 	/* Do not activate APICV when APIC is disabled */
10551 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10552 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10553 
10554 	if (apic->apicv_active == activate)
10555 		goto out;
10556 
10557 	apic->apicv_active = activate;
10558 	kvm_apic_update_apicv(vcpu);
10559 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10560 
10561 	/*
10562 	 * When APICv gets disabled, we may still have injected interrupts
10563 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10564 	 * still active when the interrupt got accepted. Make sure
10565 	 * kvm_check_and_inject_events() is called to check for that.
10566 	 */
10567 	if (!apic->apicv_active)
10568 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10569 
10570 out:
10571 	preempt_enable();
10572 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10573 }
10574 EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10575 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10576 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10577 {
10578 	if (!lapic_in_kernel(vcpu))
10579 		return;
10580 
10581 	/*
10582 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10583 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10584 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
10585 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
10586 	 * this case so that KVM can the AVIC doorbell to inject interrupts to
10587 	 * running vCPUs, but KVM must not create SPTEs for the APIC base as
10588 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10589 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
10590 	 * access page is sticky.
10591 	 */
10592 	if (apic_x2apic_mode(vcpu->arch.apic) &&
10593 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10594 		kvm_inhibit_apic_access_page(vcpu);
10595 
10596 	__kvm_vcpu_update_apicv(vcpu);
10597 }
10598 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10599 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10600 				      enum kvm_apicv_inhibit reason, bool set)
10601 {
10602 	unsigned long old, new;
10603 
10604 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10605 
10606 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10607 		return;
10608 
10609 	old = new = kvm->arch.apicv_inhibit_reasons;
10610 
10611 	set_or_clear_apicv_inhibit(&new, reason, set);
10612 
10613 	if (!!old != !!new) {
10614 		/*
10615 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10616 		 * false positives in the sanity check WARN in svm_vcpu_run().
10617 		 * This task will wait for all vCPUs to ack the kick IRQ before
10618 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10619 		 * block on acquiring apicv_update_lock so that vCPUs can't
10620 		 * redo svm_vcpu_run() without seeing the new inhibit state.
10621 		 *
10622 		 * Note, holding apicv_update_lock and taking it in the read
10623 		 * side (handling the request) also prevents other vCPUs from
10624 		 * servicing the request with a stale apicv_inhibit_reasons.
10625 		 */
10626 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10627 		kvm->arch.apicv_inhibit_reasons = new;
10628 		if (new) {
10629 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10630 			int idx = srcu_read_lock(&kvm->srcu);
10631 
10632 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10633 			srcu_read_unlock(&kvm->srcu, idx);
10634 		}
10635 	} else {
10636 		kvm->arch.apicv_inhibit_reasons = new;
10637 	}
10638 }
10639 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10640 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10641 				    enum kvm_apicv_inhibit reason, bool set)
10642 {
10643 	if (!enable_apicv)
10644 		return;
10645 
10646 	down_write(&kvm->arch.apicv_update_lock);
10647 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10648 	up_write(&kvm->arch.apicv_update_lock);
10649 }
10650 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10651 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10652 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10653 {
10654 	if (!kvm_apic_present(vcpu))
10655 		return;
10656 
10657 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10658 
10659 	kvm_x86_call(sync_pir_to_irr)(vcpu);
10660 
10661 	if (irqchip_split(vcpu->kvm))
10662 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10663 	else if (ioapic_in_kernel(vcpu->kvm))
10664 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10665 
10666 	if (is_guest_mode(vcpu))
10667 		vcpu->arch.load_eoi_exitmap_pending = true;
10668 	else
10669 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10670 }
10671 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10672 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10673 {
10674 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10675 		return;
10676 
10677 #ifdef CONFIG_KVM_HYPERV
10678 	if (to_hv_vcpu(vcpu)) {
10679 		u64 eoi_exit_bitmap[4];
10680 
10681 		bitmap_or((ulong *)eoi_exit_bitmap,
10682 			  vcpu->arch.ioapic_handled_vectors,
10683 			  to_hv_synic(vcpu)->vec_bitmap, 256);
10684 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10685 		return;
10686 	}
10687 #endif
10688 	kvm_x86_call(load_eoi_exitmap)(
10689 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10690 }
10691 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)10692 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10693 {
10694 	kvm_x86_call(guest_memory_reclaimed)(kvm);
10695 }
10696 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)10697 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10698 {
10699 	if (!lapic_in_kernel(vcpu))
10700 		return;
10701 
10702 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
10703 }
10704 
10705 /*
10706  * Called within kvm->srcu read side.
10707  * Returns 1 to let vcpu_run() continue the guest execution loop without
10708  * exiting to the userspace.  Otherwise, the value will be returned to the
10709  * userspace.
10710  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)10711 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10712 {
10713 	int r;
10714 	bool req_int_win =
10715 		dm_request_for_irq_injection(vcpu) &&
10716 		kvm_cpu_accept_dm_intr(vcpu);
10717 	fastpath_t exit_fastpath;
10718 	u64 run_flags, debug_ctl;
10719 
10720 	bool req_immediate_exit = false;
10721 
10722 	if (kvm_request_pending(vcpu)) {
10723 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10724 			r = -EIO;
10725 			goto out;
10726 		}
10727 
10728 		if (kvm_dirty_ring_check_request(vcpu)) {
10729 			r = 0;
10730 			goto out;
10731 		}
10732 
10733 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10734 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10735 				r = 0;
10736 				goto out;
10737 			}
10738 		}
10739 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10740 			kvm_mmu_free_obsolete_roots(vcpu);
10741 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10742 			__kvm_migrate_timers(vcpu);
10743 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10744 			kvm_update_masterclock(vcpu->kvm);
10745 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10746 			kvm_gen_kvmclock_update(vcpu);
10747 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10748 			r = kvm_guest_time_update(vcpu);
10749 			if (unlikely(r))
10750 				goto out;
10751 		}
10752 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10753 			kvm_mmu_sync_roots(vcpu);
10754 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10755 			kvm_mmu_load_pgd(vcpu);
10756 
10757 		/*
10758 		 * Note, the order matters here, as flushing "all" TLB entries
10759 		 * also flushes the "current" TLB entries, i.e. servicing the
10760 		 * flush "all" will clear any request to flush "current".
10761 		 */
10762 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
10763 			kvm_vcpu_flush_tlb_all(vcpu);
10764 
10765 		kvm_service_local_tlb_flush_requests(vcpu);
10766 
10767 		/*
10768 		 * Fall back to a "full" guest flush if Hyper-V's precise
10769 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
10770 		 * the flushes are considered "remote" and not "local" because
10771 		 * the requests can be initiated from other vCPUs.
10772 		 */
10773 #ifdef CONFIG_KVM_HYPERV
10774 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10775 		    kvm_hv_vcpu_flush_tlb(vcpu))
10776 			kvm_vcpu_flush_tlb_guest(vcpu);
10777 #endif
10778 
10779 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10780 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10781 			r = 0;
10782 			goto out;
10783 		}
10784 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10785 			if (is_guest_mode(vcpu))
10786 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
10787 
10788 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10789 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10790 				vcpu->mmio_needed = 0;
10791 				r = 0;
10792 				goto out;
10793 			}
10794 		}
10795 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10796 			/* Page is swapped out. Do synthetic halt */
10797 			vcpu->arch.apf.halted = true;
10798 			r = 1;
10799 			goto out;
10800 		}
10801 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10802 			record_steal_time(vcpu);
10803 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
10804 			kvm_pmu_handle_event(vcpu);
10805 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
10806 			kvm_pmu_deliver_pmi(vcpu);
10807 #ifdef CONFIG_KVM_SMM
10808 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
10809 			process_smi(vcpu);
10810 #endif
10811 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
10812 			process_nmi(vcpu);
10813 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10814 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10815 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
10816 				     vcpu->arch.ioapic_handled_vectors)) {
10817 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10818 				vcpu->run->eoi.vector =
10819 						vcpu->arch.pending_ioapic_eoi;
10820 				r = 0;
10821 				goto out;
10822 			}
10823 		}
10824 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10825 			vcpu_scan_ioapic(vcpu);
10826 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10827 			vcpu_load_eoi_exitmap(vcpu);
10828 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10829 			kvm_vcpu_reload_apic_access_page(vcpu);
10830 #ifdef CONFIG_KVM_HYPERV
10831 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10832 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10833 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10834 			vcpu->run->system_event.ndata = 0;
10835 			r = 0;
10836 			goto out;
10837 		}
10838 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10839 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10840 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10841 			vcpu->run->system_event.ndata = 0;
10842 			r = 0;
10843 			goto out;
10844 		}
10845 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10846 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10847 
10848 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10849 			vcpu->run->hyperv = hv_vcpu->exit;
10850 			r = 0;
10851 			goto out;
10852 		}
10853 
10854 		/*
10855 		 * KVM_REQ_HV_STIMER has to be processed after
10856 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10857 		 * depend on the guest clock being up-to-date
10858 		 */
10859 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10860 			kvm_hv_process_stimers(vcpu);
10861 #endif
10862 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10863 			kvm_vcpu_update_apicv(vcpu);
10864 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10865 			kvm_check_async_pf_completion(vcpu);
10866 		if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10867 			kvm_x86_call(msr_filter_changed)(vcpu);
10868 
10869 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10870 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
10871 
10872 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
10873 			kvm_vcpu_reset(vcpu, true);
10874 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
10875 				r = 1;
10876 				goto out;
10877 			}
10878 		}
10879 	}
10880 
10881 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10882 	    kvm_xen_has_interrupt(vcpu)) {
10883 		++vcpu->stat.req_event;
10884 		r = kvm_apic_accept_events(vcpu);
10885 		if (r < 0) {
10886 			r = 0;
10887 			goto out;
10888 		}
10889 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10890 			r = 1;
10891 			goto out;
10892 		}
10893 
10894 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10895 		if (r < 0) {
10896 			r = 0;
10897 			goto out;
10898 		}
10899 		if (req_int_win)
10900 			kvm_x86_call(enable_irq_window)(vcpu);
10901 
10902 		if (kvm_lapic_enabled(vcpu)) {
10903 			update_cr8_intercept(vcpu);
10904 			kvm_lapic_sync_to_vapic(vcpu);
10905 		}
10906 	}
10907 
10908 	r = kvm_mmu_reload(vcpu);
10909 	if (unlikely(r)) {
10910 		goto cancel_injection;
10911 	}
10912 
10913 	preempt_disable();
10914 
10915 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
10916 
10917 	/*
10918 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
10919 	 * IPI are then delayed after guest entry, which ensures that they
10920 	 * result in virtual interrupt delivery.
10921 	 */
10922 	local_irq_disable();
10923 
10924 	/* Store vcpu->apicv_active before vcpu->mode.  */
10925 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10926 
10927 	kvm_vcpu_srcu_read_unlock(vcpu);
10928 
10929 	/*
10930 	 * 1) We should set ->mode before checking ->requests.  Please see
10931 	 * the comment in kvm_vcpu_exiting_guest_mode().
10932 	 *
10933 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
10934 	 * pairs with the memory barrier implicit in pi_test_and_set_on
10935 	 * (see vmx_deliver_posted_interrupt).
10936 	 *
10937 	 * 3) This also orders the write to mode from any reads to the page
10938 	 * tables done while the VCPU is running.  Please see the comment
10939 	 * in kvm_flush_remote_tlbs.
10940 	 */
10941 	smp_mb__after_srcu_read_unlock();
10942 
10943 	/*
10944 	 * Process pending posted interrupts to handle the case where the
10945 	 * notification IRQ arrived in the host, or was never sent (because the
10946 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
10947 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
10948 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
10949 	 */
10950 	if (kvm_lapic_enabled(vcpu))
10951 		kvm_x86_call(sync_pir_to_irr)(vcpu);
10952 
10953 	if (kvm_vcpu_exit_request(vcpu)) {
10954 		vcpu->mode = OUTSIDE_GUEST_MODE;
10955 		smp_wmb();
10956 		local_irq_enable();
10957 		preempt_enable();
10958 		kvm_vcpu_srcu_read_lock(vcpu);
10959 		r = 1;
10960 		goto cancel_injection;
10961 	}
10962 
10963 	run_flags = 0;
10964 	if (req_immediate_exit) {
10965 		run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
10966 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10967 	}
10968 
10969 	fpregs_assert_state_consistent();
10970 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
10971 		switch_fpu_return();
10972 
10973 	if (vcpu->arch.guest_fpu.xfd_err)
10974 		wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10975 
10976 	if (unlikely(vcpu->arch.switch_db_regs)) {
10977 		set_debugreg(DR7_FIXED_1, 7);
10978 		set_debugreg(vcpu->arch.eff_db[0], 0);
10979 		set_debugreg(vcpu->arch.eff_db[1], 1);
10980 		set_debugreg(vcpu->arch.eff_db[2], 2);
10981 		set_debugreg(vcpu->arch.eff_db[3], 3);
10982 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
10983 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
10984 			run_flags |= KVM_RUN_LOAD_GUEST_DR6;
10985 	} else if (unlikely(hw_breakpoint_active())) {
10986 		set_debugreg(DR7_FIXED_1, 7);
10987 	}
10988 
10989 	/*
10990 	 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
10991 	 * can be modified in IRQ context, e.g. via SMP function calls.  Inform
10992 	 * vendor code if any host-owned bits were changed, e.g. so that the
10993 	 * value loaded into hardware while running the guest can be updated.
10994 	 */
10995 	debug_ctl = get_debugctlmsr();
10996 	if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
10997 	    !vcpu->arch.guest_state_protected)
10998 		run_flags |= KVM_RUN_LOAD_DEBUGCTL;
10999 	vcpu->arch.host_debugctl = debug_ctl;
11000 
11001 	guest_timing_enter_irqoff();
11002 
11003 	for (;;) {
11004 		/*
11005 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
11006 		 * update must kick and wait for all vCPUs before toggling the
11007 		 * per-VM state, and responding vCPUs must wait for the update
11008 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
11009 		 */
11010 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11011 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11012 
11013 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11014 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11015 			break;
11016 
11017 		if (kvm_lapic_enabled(vcpu))
11018 			kvm_x86_call(sync_pir_to_irr)(vcpu);
11019 
11020 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11021 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11022 			break;
11023 		}
11024 
11025 		run_flags = 0;
11026 
11027 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
11028 		++vcpu->stat.exits;
11029 	}
11030 
11031 	/*
11032 	 * Do this here before restoring debug registers on the host.  And
11033 	 * since we do this before handling the vmexit, a DR access vmexit
11034 	 * can (a) read the correct value of the debug registers, (b) set
11035 	 * KVM_DEBUGREG_WONT_EXIT again.
11036 	 */
11037 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11038 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11039 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11040 		kvm_update_dr0123(vcpu);
11041 		kvm_update_dr7(vcpu);
11042 	}
11043 
11044 	/*
11045 	 * If the guest has used debug registers, at least dr7
11046 	 * will be disabled while returning to the host.
11047 	 * If we don't have active breakpoints in the host, we don't
11048 	 * care about the messed up debug address registers. But if
11049 	 * we have some of them active, restore the old state.
11050 	 */
11051 	if (hw_breakpoint_active())
11052 		hw_breakpoint_restore();
11053 
11054 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11055 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11056 
11057 	vcpu->mode = OUTSIDE_GUEST_MODE;
11058 	smp_wmb();
11059 
11060 	/*
11061 	 * Sync xfd before calling handle_exit_irqoff() which may
11062 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11063 	 * in #NM irqoff handler).
11064 	 */
11065 	if (vcpu->arch.xfd_no_write_intercept)
11066 		fpu_sync_guest_vmexit_xfd_state();
11067 
11068 	kvm_x86_call(handle_exit_irqoff)(vcpu);
11069 
11070 	if (vcpu->arch.guest_fpu.xfd_err)
11071 		wrmsrl(MSR_IA32_XFD_ERR, 0);
11072 
11073 	/*
11074 	 * Mark this CPU as needing a branch predictor flush before running
11075 	 * userspace. Must be done before enabling preemption to ensure it gets
11076 	 * set for the CPU that actually ran the guest, and not the CPU that it
11077 	 * may migrate to.
11078 	 */
11079 	if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11080 		this_cpu_write(x86_ibpb_exit_to_user, true);
11081 
11082 	/*
11083 	 * Consume any pending interrupts, including the possible source of
11084 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11085 	 * An instruction is required after local_irq_enable() to fully unblock
11086 	 * interrupts on processors that implement an interrupt shadow, the
11087 	 * stat.exits increment will do nicely.
11088 	 */
11089 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11090 	local_irq_enable();
11091 	++vcpu->stat.exits;
11092 	local_irq_disable();
11093 	kvm_after_interrupt(vcpu);
11094 
11095 	/*
11096 	 * Wait until after servicing IRQs to account guest time so that any
11097 	 * ticks that occurred while running the guest are properly accounted
11098 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
11099 	 * of accounting via context tracking, but the loss of accuracy is
11100 	 * acceptable for all known use cases.
11101 	 */
11102 	guest_timing_exit_irqoff();
11103 
11104 	local_irq_enable();
11105 	preempt_enable();
11106 
11107 	kvm_vcpu_srcu_read_lock(vcpu);
11108 
11109 	/*
11110 	 * Call this to ensure WC buffers in guest are evicted after each VM
11111 	 * Exit, so that the evicted WC writes can be snooped across all cpus
11112 	 */
11113 	smp_mb__after_srcu_read_lock();
11114 
11115 	/*
11116 	 * Profile KVM exit RIPs:
11117 	 */
11118 	if (unlikely(prof_on == KVM_PROFILING)) {
11119 		unsigned long rip = kvm_rip_read(vcpu);
11120 		profile_hit(KVM_PROFILING, (void *)rip);
11121 	}
11122 
11123 	if (unlikely(vcpu->arch.tsc_always_catchup))
11124 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11125 
11126 	if (vcpu->arch.apic_attention)
11127 		kvm_lapic_sync_from_vapic(vcpu);
11128 
11129 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11130 		return 0;
11131 
11132 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11133 	return r;
11134 
11135 cancel_injection:
11136 	if (req_immediate_exit)
11137 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11138 	kvm_x86_call(cancel_injection)(vcpu);
11139 	if (unlikely(vcpu->arch.apic_attention))
11140 		kvm_lapic_sync_from_vapic(vcpu);
11141 out:
11142 	return r;
11143 }
11144 
kvm_vcpu_running(struct kvm_vcpu * vcpu)11145 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11146 {
11147 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11148 		!vcpu->arch.apf.halted);
11149 }
11150 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11151 static bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11152 {
11153 	if (!list_empty_careful(&vcpu->async_pf.done))
11154 		return true;
11155 
11156 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11157 	    kvm_apic_init_sipi_allowed(vcpu))
11158 		return true;
11159 
11160 	if (vcpu->arch.pv.pv_unhalted)
11161 		return true;
11162 
11163 	if (kvm_is_exception_pending(vcpu))
11164 		return true;
11165 
11166 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11167 	    (vcpu->arch.nmi_pending &&
11168 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
11169 		return true;
11170 
11171 #ifdef CONFIG_KVM_SMM
11172 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11173 	    (vcpu->arch.smi_pending &&
11174 	     kvm_x86_call(smi_allowed)(vcpu, false)))
11175 		return true;
11176 #endif
11177 
11178 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
11179 		return true;
11180 
11181 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11182 		return true;
11183 
11184 	if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11185 		return true;
11186 
11187 	if (kvm_hv_has_stimer_pending(vcpu))
11188 		return true;
11189 
11190 	if (is_guest_mode(vcpu) &&
11191 	    kvm_x86_ops.nested_ops->has_events &&
11192 	    kvm_x86_ops.nested_ops->has_events(vcpu, false))
11193 		return true;
11194 
11195 	if (kvm_xen_has_pending_events(vcpu))
11196 		return true;
11197 
11198 	return false;
11199 }
11200 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11201 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11202 {
11203 	return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
11204 }
11205 
11206 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)11207 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11208 {
11209 	bool hv_timer;
11210 
11211 	if (!kvm_arch_vcpu_runnable(vcpu)) {
11212 		/*
11213 		 * Switch to the software timer before halt-polling/blocking as
11214 		 * the guest's timer may be a break event for the vCPU, and the
11215 		 * hypervisor timer runs only when the CPU is in guest mode.
11216 		 * Switch before halt-polling so that KVM recognizes an expired
11217 		 * timer before blocking.
11218 		 */
11219 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11220 		if (hv_timer)
11221 			kvm_lapic_switch_to_sw_timer(vcpu);
11222 
11223 		kvm_vcpu_srcu_read_unlock(vcpu);
11224 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11225 			kvm_vcpu_halt(vcpu);
11226 		else
11227 			kvm_vcpu_block(vcpu);
11228 		kvm_vcpu_srcu_read_lock(vcpu);
11229 
11230 		if (hv_timer)
11231 			kvm_lapic_switch_to_hv_timer(vcpu);
11232 
11233 		/*
11234 		 * If the vCPU is not runnable, a signal or another host event
11235 		 * of some kind is pending; service it without changing the
11236 		 * vCPU's activity state.
11237 		 */
11238 		if (!kvm_arch_vcpu_runnable(vcpu))
11239 			return 1;
11240 	}
11241 
11242 	/*
11243 	 * Evaluate nested events before exiting the halted state.  This allows
11244 	 * the halt state to be recorded properly in the VMCS12's activity
11245 	 * state field (AMD does not have a similar field and a VM-Exit always
11246 	 * causes a spurious wakeup from HLT).
11247 	 */
11248 	if (is_guest_mode(vcpu)) {
11249 		int r = kvm_check_nested_events(vcpu);
11250 
11251 		WARN_ON_ONCE(r == -EBUSY);
11252 		if (r < 0)
11253 			return 0;
11254 	}
11255 
11256 	if (kvm_apic_accept_events(vcpu) < 0)
11257 		return 0;
11258 	switch(vcpu->arch.mp_state) {
11259 	case KVM_MP_STATE_HALTED:
11260 	case KVM_MP_STATE_AP_RESET_HOLD:
11261 		vcpu->arch.pv.pv_unhalted = false;
11262 		vcpu->arch.mp_state =
11263 			KVM_MP_STATE_RUNNABLE;
11264 		fallthrough;
11265 	case KVM_MP_STATE_RUNNABLE:
11266 		vcpu->arch.apf.halted = false;
11267 		break;
11268 	case KVM_MP_STATE_INIT_RECEIVED:
11269 		break;
11270 	default:
11271 		WARN_ON_ONCE(1);
11272 		break;
11273 	}
11274 	return 1;
11275 }
11276 
11277 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)11278 static int vcpu_run(struct kvm_vcpu *vcpu)
11279 {
11280 	int r;
11281 
11282 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11283 
11284 	for (;;) {
11285 		/*
11286 		 * If another guest vCPU requests a PV TLB flush in the middle
11287 		 * of instruction emulation, the rest of the emulation could
11288 		 * use a stale page translation. Assume that any code after
11289 		 * this point can start executing an instruction.
11290 		 */
11291 		vcpu->arch.at_instruction_boundary = false;
11292 		if (kvm_vcpu_running(vcpu)) {
11293 			r = vcpu_enter_guest(vcpu);
11294 		} else {
11295 			r = vcpu_block(vcpu);
11296 		}
11297 
11298 		if (r <= 0)
11299 			break;
11300 
11301 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11302 		if (kvm_xen_has_pending_events(vcpu))
11303 			kvm_xen_inject_pending_events(vcpu);
11304 
11305 		if (kvm_cpu_has_pending_timer(vcpu))
11306 			kvm_inject_pending_timer_irqs(vcpu);
11307 
11308 		if (dm_request_for_irq_injection(vcpu) &&
11309 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11310 			r = 0;
11311 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11312 			++vcpu->stat.request_irq_exits;
11313 			break;
11314 		}
11315 
11316 		if (__xfer_to_guest_mode_work_pending()) {
11317 			kvm_vcpu_srcu_read_unlock(vcpu);
11318 			r = xfer_to_guest_mode_handle_work(vcpu);
11319 			kvm_vcpu_srcu_read_lock(vcpu);
11320 			if (r)
11321 				return r;
11322 		}
11323 	}
11324 
11325 	return r;
11326 }
11327 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11328 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11329 {
11330 	/*
11331 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
11332 	 * local APIC is in-kernel, the run loop will detect the non-runnable
11333 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
11334 	 * managed by userspace, in which case userspace is responsible for
11335 	 * handling wake events.
11336 	 */
11337 	++vcpu->stat.halt_exits;
11338 	if (lapic_in_kernel(vcpu)) {
11339 		if (kvm_vcpu_has_events(vcpu))
11340 			vcpu->arch.pv.pv_unhalted = false;
11341 		else
11342 			vcpu->arch.mp_state = state;
11343 		return 1;
11344 	} else {
11345 		vcpu->run->exit_reason = reason;
11346 		return 0;
11347 	}
11348 }
11349 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11350 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11351 {
11352 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11353 }
11354 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
11355 
kvm_emulate_halt(struct kvm_vcpu * vcpu)11356 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11357 {
11358 	int ret = kvm_skip_emulated_instruction(vcpu);
11359 	/*
11360 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11361 	 * KVM_EXIT_DEBUG here.
11362 	 */
11363 	return kvm_emulate_halt_noskip(vcpu) && ret;
11364 }
11365 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
11366 
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11367 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11368 {
11369 	int ret;
11370 
11371 	kvm_vcpu_srcu_read_lock(vcpu);
11372 	ret = kvm_emulate_halt(vcpu);
11373 	kvm_vcpu_srcu_read_unlock(vcpu);
11374 
11375 	if (!ret)
11376 		return EXIT_FASTPATH_EXIT_USERSPACE;
11377 
11378 	if (kvm_vcpu_running(vcpu))
11379 		return EXIT_FASTPATH_REENTER_GUEST;
11380 
11381 	return EXIT_FASTPATH_EXIT_HANDLED;
11382 }
11383 EXPORT_SYMBOL_GPL(handle_fastpath_hlt);
11384 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11385 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11386 {
11387 	int ret = kvm_skip_emulated_instruction(vcpu);
11388 
11389 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11390 					KVM_EXIT_AP_RESET_HOLD) && ret;
11391 }
11392 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
11393 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11394 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11395 {
11396 	return kvm_vcpu_apicv_active(vcpu) &&
11397 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11398 }
11399 
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11400 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11401 {
11402 	return vcpu->arch.preempted_in_kernel;
11403 }
11404 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11405 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11406 {
11407 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11408 		return true;
11409 
11410 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11411 #ifdef CONFIG_KVM_SMM
11412 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
11413 #endif
11414 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
11415 		return true;
11416 
11417 	return kvm_arch_dy_has_pending_interrupt(vcpu);
11418 }
11419 
complete_emulated_io(struct kvm_vcpu * vcpu)11420 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11421 {
11422 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11423 }
11424 
complete_emulated_pio(struct kvm_vcpu * vcpu)11425 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11426 {
11427 	BUG_ON(!vcpu->arch.pio.count);
11428 
11429 	return complete_emulated_io(vcpu);
11430 }
11431 
11432 /*
11433  * Implements the following, as a state machine:
11434  *
11435  * read:
11436  *   for each fragment
11437  *     for each mmio piece in the fragment
11438  *       write gpa, len
11439  *       exit
11440  *       copy data
11441  *   execute insn
11442  *
11443  * write:
11444  *   for each fragment
11445  *     for each mmio piece in the fragment
11446  *       write gpa, len
11447  *       copy data
11448  *       exit
11449  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11450 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11451 {
11452 	struct kvm_run *run = vcpu->run;
11453 	struct kvm_mmio_fragment *frag;
11454 	unsigned len;
11455 
11456 	BUG_ON(!vcpu->mmio_needed);
11457 
11458 	/* Complete previous fragment */
11459 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11460 	len = min(8u, frag->len);
11461 	if (!vcpu->mmio_is_write)
11462 		memcpy(frag->data, run->mmio.data, len);
11463 
11464 	if (frag->len <= 8) {
11465 		/* Switch to the next fragment. */
11466 		frag++;
11467 		vcpu->mmio_cur_fragment++;
11468 	} else {
11469 		/* Go forward to the next mmio piece. */
11470 		frag->data += len;
11471 		frag->gpa += len;
11472 		frag->len -= len;
11473 	}
11474 
11475 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11476 		vcpu->mmio_needed = 0;
11477 
11478 		/* FIXME: return into emulator if single-stepping.  */
11479 		if (vcpu->mmio_is_write)
11480 			return 1;
11481 		vcpu->mmio_read_completed = 1;
11482 		return complete_emulated_io(vcpu);
11483 	}
11484 
11485 	run->exit_reason = KVM_EXIT_MMIO;
11486 	run->mmio.phys_addr = frag->gpa;
11487 	if (vcpu->mmio_is_write)
11488 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11489 	run->mmio.len = min(8u, frag->len);
11490 	run->mmio.is_write = vcpu->mmio_is_write;
11491 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11492 	return 0;
11493 }
11494 
11495 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11496 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11497 {
11498 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11499 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11500 	trace_kvm_fpu(1);
11501 }
11502 
11503 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11504 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11505 {
11506 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11507 	++vcpu->stat.fpu_reload;
11508 	trace_kvm_fpu(0);
11509 }
11510 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11511 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11512 {
11513 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
11514 	struct kvm_run *kvm_run = vcpu->run;
11515 	u32 sync_valid_fields;
11516 	int r;
11517 
11518 	r = kvm_mmu_post_init_vm(vcpu->kvm);
11519 	if (r)
11520 		return r;
11521 
11522 	vcpu_load(vcpu);
11523 	kvm_sigset_activate(vcpu);
11524 	kvm_run->flags = 0;
11525 	kvm_load_guest_fpu(vcpu);
11526 
11527 	kvm_vcpu_srcu_read_lock(vcpu);
11528 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11529 		if (!vcpu->wants_to_run) {
11530 			r = -EINTR;
11531 			goto out;
11532 		}
11533 
11534 		/*
11535 		 * Don't bother switching APIC timer emulation from the
11536 		 * hypervisor timer to the software timer, the only way for the
11537 		 * APIC timer to be active is if userspace stuffed vCPU state,
11538 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
11539 		 * will transition the vCPU out of UNINITIALIZED (without more
11540 		 * state stuffing from userspace), which will reset the local
11541 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
11542 		 * already expired).
11543 		 */
11544 		kvm_vcpu_srcu_read_unlock(vcpu);
11545 		kvm_vcpu_block(vcpu);
11546 		kvm_vcpu_srcu_read_lock(vcpu);
11547 
11548 		if (kvm_apic_accept_events(vcpu) < 0) {
11549 			r = 0;
11550 			goto out;
11551 		}
11552 		r = -EAGAIN;
11553 		if (signal_pending(current)) {
11554 			r = -EINTR;
11555 			kvm_run->exit_reason = KVM_EXIT_INTR;
11556 			++vcpu->stat.signal_exits;
11557 		}
11558 		goto out;
11559 	}
11560 
11561 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11562 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11563 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11564 		r = -EINVAL;
11565 		goto out;
11566 	}
11567 
11568 	if (kvm_run->kvm_dirty_regs) {
11569 		r = sync_regs(vcpu);
11570 		if (r != 0)
11571 			goto out;
11572 	}
11573 
11574 	/* re-sync apic's tpr */
11575 	if (!lapic_in_kernel(vcpu)) {
11576 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11577 			r = -EINVAL;
11578 			goto out;
11579 		}
11580 	}
11581 
11582 	/*
11583 	 * If userspace set a pending exception and L2 is active, convert it to
11584 	 * a pending VM-Exit if L1 wants to intercept the exception.
11585 	 */
11586 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11587 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11588 							ex->error_code)) {
11589 		kvm_queue_exception_vmexit(vcpu, ex->vector,
11590 					   ex->has_error_code, ex->error_code,
11591 					   ex->has_payload, ex->payload);
11592 		ex->injected = false;
11593 		ex->pending = false;
11594 	}
11595 	vcpu->arch.exception_from_userspace = false;
11596 
11597 	if (unlikely(vcpu->arch.complete_userspace_io)) {
11598 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11599 		vcpu->arch.complete_userspace_io = NULL;
11600 		r = cui(vcpu);
11601 		if (r <= 0)
11602 			goto out;
11603 	} else {
11604 		WARN_ON_ONCE(vcpu->arch.pio.count);
11605 		WARN_ON_ONCE(vcpu->mmio_needed);
11606 	}
11607 
11608 	if (!vcpu->wants_to_run) {
11609 		r = -EINTR;
11610 		goto out;
11611 	}
11612 
11613 	r = kvm_x86_call(vcpu_pre_run)(vcpu);
11614 	if (r <= 0)
11615 		goto out;
11616 
11617 	r = vcpu_run(vcpu);
11618 
11619 out:
11620 	kvm_put_guest_fpu(vcpu);
11621 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11622 		store_regs(vcpu);
11623 	post_kvm_run_save(vcpu);
11624 	kvm_vcpu_srcu_read_unlock(vcpu);
11625 
11626 	kvm_sigset_deactivate(vcpu);
11627 	vcpu_put(vcpu);
11628 	return r;
11629 }
11630 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11631 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11632 {
11633 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11634 		/*
11635 		 * We are here if userspace calls get_regs() in the middle of
11636 		 * instruction emulation. Registers state needs to be copied
11637 		 * back from emulation context to vcpu. Userspace shouldn't do
11638 		 * that usually, but some bad designed PV devices (vmware
11639 		 * backdoor interface) need this to work
11640 		 */
11641 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11642 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11643 	}
11644 	regs->rax = kvm_rax_read(vcpu);
11645 	regs->rbx = kvm_rbx_read(vcpu);
11646 	regs->rcx = kvm_rcx_read(vcpu);
11647 	regs->rdx = kvm_rdx_read(vcpu);
11648 	regs->rsi = kvm_rsi_read(vcpu);
11649 	regs->rdi = kvm_rdi_read(vcpu);
11650 	regs->rsp = kvm_rsp_read(vcpu);
11651 	regs->rbp = kvm_rbp_read(vcpu);
11652 #ifdef CONFIG_X86_64
11653 	regs->r8 = kvm_r8_read(vcpu);
11654 	regs->r9 = kvm_r9_read(vcpu);
11655 	regs->r10 = kvm_r10_read(vcpu);
11656 	regs->r11 = kvm_r11_read(vcpu);
11657 	regs->r12 = kvm_r12_read(vcpu);
11658 	regs->r13 = kvm_r13_read(vcpu);
11659 	regs->r14 = kvm_r14_read(vcpu);
11660 	regs->r15 = kvm_r15_read(vcpu);
11661 #endif
11662 
11663 	regs->rip = kvm_rip_read(vcpu);
11664 	regs->rflags = kvm_get_rflags(vcpu);
11665 }
11666 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11667 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11668 {
11669 	if (vcpu->kvm->arch.has_protected_state &&
11670 	    vcpu->arch.guest_state_protected)
11671 		return -EINVAL;
11672 
11673 	vcpu_load(vcpu);
11674 	__get_regs(vcpu, regs);
11675 	vcpu_put(vcpu);
11676 	return 0;
11677 }
11678 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11679 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11680 {
11681 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11682 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11683 
11684 	kvm_rax_write(vcpu, regs->rax);
11685 	kvm_rbx_write(vcpu, regs->rbx);
11686 	kvm_rcx_write(vcpu, regs->rcx);
11687 	kvm_rdx_write(vcpu, regs->rdx);
11688 	kvm_rsi_write(vcpu, regs->rsi);
11689 	kvm_rdi_write(vcpu, regs->rdi);
11690 	kvm_rsp_write(vcpu, regs->rsp);
11691 	kvm_rbp_write(vcpu, regs->rbp);
11692 #ifdef CONFIG_X86_64
11693 	kvm_r8_write(vcpu, regs->r8);
11694 	kvm_r9_write(vcpu, regs->r9);
11695 	kvm_r10_write(vcpu, regs->r10);
11696 	kvm_r11_write(vcpu, regs->r11);
11697 	kvm_r12_write(vcpu, regs->r12);
11698 	kvm_r13_write(vcpu, regs->r13);
11699 	kvm_r14_write(vcpu, regs->r14);
11700 	kvm_r15_write(vcpu, regs->r15);
11701 #endif
11702 
11703 	kvm_rip_write(vcpu, regs->rip);
11704 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11705 
11706 	vcpu->arch.exception.pending = false;
11707 	vcpu->arch.exception_vmexit.pending = false;
11708 
11709 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11710 }
11711 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11712 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11713 {
11714 	if (vcpu->kvm->arch.has_protected_state &&
11715 	    vcpu->arch.guest_state_protected)
11716 		return -EINVAL;
11717 
11718 	vcpu_load(vcpu);
11719 	__set_regs(vcpu, regs);
11720 	vcpu_put(vcpu);
11721 	return 0;
11722 }
11723 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11724 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11725 {
11726 	struct desc_ptr dt;
11727 
11728 	if (vcpu->arch.guest_state_protected)
11729 		goto skip_protected_regs;
11730 
11731 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11732 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11733 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11734 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11735 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11736 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11737 
11738 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11739 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11740 
11741 	kvm_x86_call(get_idt)(vcpu, &dt);
11742 	sregs->idt.limit = dt.size;
11743 	sregs->idt.base = dt.address;
11744 	kvm_x86_call(get_gdt)(vcpu, &dt);
11745 	sregs->gdt.limit = dt.size;
11746 	sregs->gdt.base = dt.address;
11747 
11748 	sregs->cr2 = vcpu->arch.cr2;
11749 	sregs->cr3 = kvm_read_cr3(vcpu);
11750 
11751 skip_protected_regs:
11752 	sregs->cr0 = kvm_read_cr0(vcpu);
11753 	sregs->cr4 = kvm_read_cr4(vcpu);
11754 	sregs->cr8 = kvm_get_cr8(vcpu);
11755 	sregs->efer = vcpu->arch.efer;
11756 	sregs->apic_base = vcpu->arch.apic_base;
11757 }
11758 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11759 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11760 {
11761 	__get_sregs_common(vcpu, sregs);
11762 
11763 	if (vcpu->arch.guest_state_protected)
11764 		return;
11765 
11766 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11767 		set_bit(vcpu->arch.interrupt.nr,
11768 			(unsigned long *)sregs->interrupt_bitmap);
11769 }
11770 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)11771 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11772 {
11773 	int i;
11774 
11775 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11776 
11777 	if (vcpu->arch.guest_state_protected)
11778 		return;
11779 
11780 	if (is_pae_paging(vcpu)) {
11781 		for (i = 0 ; i < 4 ; i++)
11782 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11783 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11784 	}
11785 }
11786 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11787 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11788 				  struct kvm_sregs *sregs)
11789 {
11790 	if (vcpu->kvm->arch.has_protected_state &&
11791 	    vcpu->arch.guest_state_protected)
11792 		return -EINVAL;
11793 
11794 	vcpu_load(vcpu);
11795 	__get_sregs(vcpu, sregs);
11796 	vcpu_put(vcpu);
11797 	return 0;
11798 }
11799 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11800 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11801 				    struct kvm_mp_state *mp_state)
11802 {
11803 	int r;
11804 
11805 	vcpu_load(vcpu);
11806 	if (kvm_mpx_supported())
11807 		kvm_load_guest_fpu(vcpu);
11808 
11809 	kvm_vcpu_srcu_read_lock(vcpu);
11810 
11811 	r = kvm_apic_accept_events(vcpu);
11812 	if (r < 0)
11813 		goto out;
11814 	r = 0;
11815 
11816 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11817 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11818 	    vcpu->arch.pv.pv_unhalted)
11819 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11820 	else
11821 		mp_state->mp_state = vcpu->arch.mp_state;
11822 
11823 out:
11824 	kvm_vcpu_srcu_read_unlock(vcpu);
11825 
11826 	if (kvm_mpx_supported())
11827 		kvm_put_guest_fpu(vcpu);
11828 	vcpu_put(vcpu);
11829 	return r;
11830 }
11831 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11832 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11833 				    struct kvm_mp_state *mp_state)
11834 {
11835 	int ret = -EINVAL;
11836 
11837 	vcpu_load(vcpu);
11838 
11839 	switch (mp_state->mp_state) {
11840 	case KVM_MP_STATE_UNINITIALIZED:
11841 	case KVM_MP_STATE_HALTED:
11842 	case KVM_MP_STATE_AP_RESET_HOLD:
11843 	case KVM_MP_STATE_INIT_RECEIVED:
11844 	case KVM_MP_STATE_SIPI_RECEIVED:
11845 		if (!lapic_in_kernel(vcpu))
11846 			goto out;
11847 		break;
11848 
11849 	case KVM_MP_STATE_RUNNABLE:
11850 		break;
11851 
11852 	default:
11853 		goto out;
11854 	}
11855 
11856 	/*
11857 	 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11858 	 * forcing the guest into INIT/SIPI if those events are supposed to be
11859 	 * blocked.  KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11860 	 * if an SMI is pending as well.
11861 	 */
11862 	if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11863 	    (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11864 	     mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11865 		goto out;
11866 
11867 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11868 		vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
11869 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11870 	} else
11871 		vcpu->arch.mp_state = mp_state->mp_state;
11872 	kvm_make_request(KVM_REQ_EVENT, vcpu);
11873 
11874 	ret = 0;
11875 out:
11876 	vcpu_put(vcpu);
11877 	return ret;
11878 }
11879 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)11880 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11881 		    int reason, bool has_error_code, u32 error_code)
11882 {
11883 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11884 	int ret;
11885 
11886 	init_emulate_ctxt(vcpu);
11887 
11888 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11889 				   has_error_code, error_code);
11890 
11891 	/*
11892 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
11893 	 * MMIO during a task switch (or any other complex operation).
11894 	 */
11895 	if (ret || vcpu->mmio_needed) {
11896 		vcpu->mmio_needed = false;
11897 		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11898 		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11899 		vcpu->run->internal.ndata = 0;
11900 		return 0;
11901 	}
11902 
11903 	kvm_rip_write(vcpu, ctxt->eip);
11904 	kvm_set_rflags(vcpu, ctxt->eflags);
11905 	return 1;
11906 }
11907 EXPORT_SYMBOL_GPL(kvm_task_switch);
11908 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11909 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11910 {
11911 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11912 		/*
11913 		 * When EFER.LME and CR0.PG are set, the processor is in
11914 		 * 64-bit mode (though maybe in a 32-bit code segment).
11915 		 * CR4.PAE and EFER.LMA must be set.
11916 		 */
11917 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11918 			return false;
11919 		if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
11920 			return false;
11921 	} else {
11922 		/*
11923 		 * Not in 64-bit mode: EFER.LMA is clear and the code
11924 		 * segment cannot be 64-bit.
11925 		 */
11926 		if (sregs->efer & EFER_LMA || sregs->cs.l)
11927 			return false;
11928 	}
11929 
11930 	return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11931 	       kvm_is_valid_cr0(vcpu, sregs->cr0);
11932 }
11933 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)11934 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11935 		int *mmu_reset_needed, bool update_pdptrs)
11936 {
11937 	struct msr_data apic_base_msr;
11938 	int idx;
11939 	struct desc_ptr dt;
11940 
11941 	if (!kvm_is_valid_sregs(vcpu, sregs))
11942 		return -EINVAL;
11943 
11944 	apic_base_msr.data = sregs->apic_base;
11945 	apic_base_msr.host_initiated = true;
11946 	if (kvm_set_apic_base(vcpu, &apic_base_msr))
11947 		return -EINVAL;
11948 
11949 	if (vcpu->arch.guest_state_protected)
11950 		return 0;
11951 
11952 	dt.size = sregs->idt.limit;
11953 	dt.address = sregs->idt.base;
11954 	kvm_x86_call(set_idt)(vcpu, &dt);
11955 	dt.size = sregs->gdt.limit;
11956 	dt.address = sregs->gdt.base;
11957 	kvm_x86_call(set_gdt)(vcpu, &dt);
11958 
11959 	vcpu->arch.cr2 = sregs->cr2;
11960 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11961 	vcpu->arch.cr3 = sregs->cr3;
11962 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11963 	kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
11964 
11965 	kvm_set_cr8(vcpu, sregs->cr8);
11966 
11967 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
11968 	kvm_x86_call(set_efer)(vcpu, sregs->efer);
11969 
11970 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
11971 	kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
11972 
11973 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
11974 	kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
11975 
11976 	if (update_pdptrs) {
11977 		idx = srcu_read_lock(&vcpu->kvm->srcu);
11978 		if (is_pae_paging(vcpu)) {
11979 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
11980 			*mmu_reset_needed = 1;
11981 		}
11982 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
11983 	}
11984 
11985 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11986 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11987 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11988 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11989 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11990 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11991 
11992 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11993 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11994 
11995 	update_cr8_intercept(vcpu);
11996 
11997 	/* Older userspace won't unhalt the vcpu on reset. */
11998 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
11999 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12000 	    !is_protmode(vcpu))
12001 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12002 
12003 	return 0;
12004 }
12005 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12006 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12007 {
12008 	int pending_vec, max_bits;
12009 	int mmu_reset_needed = 0;
12010 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12011 
12012 	if (ret)
12013 		return ret;
12014 
12015 	if (mmu_reset_needed) {
12016 		kvm_mmu_reset_context(vcpu);
12017 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12018 	}
12019 
12020 	max_bits = KVM_NR_INTERRUPTS;
12021 	pending_vec = find_first_bit(
12022 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
12023 
12024 	if (pending_vec < max_bits) {
12025 		kvm_queue_interrupt(vcpu, pending_vec, false);
12026 		pr_debug("Set back pending irq %d\n", pending_vec);
12027 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12028 	}
12029 	return 0;
12030 }
12031 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12032 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12033 {
12034 	int mmu_reset_needed = 0;
12035 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12036 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12037 		!(sregs2->efer & EFER_LMA);
12038 	int i, ret;
12039 
12040 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12041 		return -EINVAL;
12042 
12043 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12044 		return -EINVAL;
12045 
12046 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12047 				 &mmu_reset_needed, !valid_pdptrs);
12048 	if (ret)
12049 		return ret;
12050 
12051 	if (valid_pdptrs) {
12052 		for (i = 0; i < 4 ; i++)
12053 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12054 
12055 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12056 		mmu_reset_needed = 1;
12057 		vcpu->arch.pdptrs_from_userspace = true;
12058 	}
12059 	if (mmu_reset_needed) {
12060 		kvm_mmu_reset_context(vcpu);
12061 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12062 	}
12063 	return 0;
12064 }
12065 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12066 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12067 				  struct kvm_sregs *sregs)
12068 {
12069 	int ret;
12070 
12071 	if (vcpu->kvm->arch.has_protected_state &&
12072 	    vcpu->arch.guest_state_protected)
12073 		return -EINVAL;
12074 
12075 	vcpu_load(vcpu);
12076 	ret = __set_sregs(vcpu, sregs);
12077 	vcpu_put(vcpu);
12078 	return ret;
12079 }
12080 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12081 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12082 {
12083 	bool set = false;
12084 	struct kvm_vcpu *vcpu;
12085 	unsigned long i;
12086 
12087 	if (!enable_apicv)
12088 		return;
12089 
12090 	down_write(&kvm->arch.apicv_update_lock);
12091 
12092 	kvm_for_each_vcpu(i, vcpu, kvm) {
12093 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12094 			set = true;
12095 			break;
12096 		}
12097 	}
12098 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12099 	up_write(&kvm->arch.apicv_update_lock);
12100 }
12101 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12102 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12103 					struct kvm_guest_debug *dbg)
12104 {
12105 	unsigned long rflags;
12106 	int i, r;
12107 
12108 	if (vcpu->arch.guest_state_protected)
12109 		return -EINVAL;
12110 
12111 	vcpu_load(vcpu);
12112 
12113 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12114 		r = -EBUSY;
12115 		if (kvm_is_exception_pending(vcpu))
12116 			goto out;
12117 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12118 			kvm_queue_exception(vcpu, DB_VECTOR);
12119 		else
12120 			kvm_queue_exception(vcpu, BP_VECTOR);
12121 	}
12122 
12123 	/*
12124 	 * Read rflags as long as potentially injected trace flags are still
12125 	 * filtered out.
12126 	 */
12127 	rflags = kvm_get_rflags(vcpu);
12128 
12129 	vcpu->guest_debug = dbg->control;
12130 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12131 		vcpu->guest_debug = 0;
12132 
12133 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12134 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
12135 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12136 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12137 	} else {
12138 		for (i = 0; i < KVM_NR_DB_REGS; i++)
12139 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12140 	}
12141 	kvm_update_dr7(vcpu);
12142 
12143 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12144 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12145 
12146 	/*
12147 	 * Trigger an rflags update that will inject or remove the trace
12148 	 * flags.
12149 	 */
12150 	kvm_set_rflags(vcpu, rflags);
12151 
12152 	kvm_x86_call(update_exception_bitmap)(vcpu);
12153 
12154 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12155 
12156 	r = 0;
12157 
12158 out:
12159 	vcpu_put(vcpu);
12160 	return r;
12161 }
12162 
12163 /*
12164  * Translate a guest virtual address to a guest physical address.
12165  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12166 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12167 				    struct kvm_translation *tr)
12168 {
12169 	unsigned long vaddr = tr->linear_address;
12170 	gpa_t gpa;
12171 	int idx;
12172 
12173 	vcpu_load(vcpu);
12174 
12175 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12176 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12177 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12178 	tr->physical_address = gpa;
12179 	tr->valid = gpa != INVALID_GPA;
12180 	tr->writeable = 1;
12181 	tr->usermode = 0;
12182 
12183 	vcpu_put(vcpu);
12184 	return 0;
12185 }
12186 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12187 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12188 {
12189 	struct fxregs_state *fxsave;
12190 
12191 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12192 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12193 
12194 	vcpu_load(vcpu);
12195 
12196 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12197 	memcpy(fpu->fpr, fxsave->st_space, 128);
12198 	fpu->fcw = fxsave->cwd;
12199 	fpu->fsw = fxsave->swd;
12200 	fpu->ftwx = fxsave->twd;
12201 	fpu->last_opcode = fxsave->fop;
12202 	fpu->last_ip = fxsave->rip;
12203 	fpu->last_dp = fxsave->rdp;
12204 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12205 
12206 	vcpu_put(vcpu);
12207 	return 0;
12208 }
12209 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12210 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12211 {
12212 	struct fxregs_state *fxsave;
12213 
12214 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12215 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12216 
12217 	vcpu_load(vcpu);
12218 
12219 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12220 
12221 	memcpy(fxsave->st_space, fpu->fpr, 128);
12222 	fxsave->cwd = fpu->fcw;
12223 	fxsave->swd = fpu->fsw;
12224 	fxsave->twd = fpu->ftwx;
12225 	fxsave->fop = fpu->last_opcode;
12226 	fxsave->rip = fpu->last_ip;
12227 	fxsave->rdp = fpu->last_dp;
12228 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12229 
12230 	vcpu_put(vcpu);
12231 	return 0;
12232 }
12233 
store_regs(struct kvm_vcpu * vcpu)12234 static void store_regs(struct kvm_vcpu *vcpu)
12235 {
12236 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12237 
12238 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12239 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
12240 
12241 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12242 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12243 
12244 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12245 		kvm_vcpu_ioctl_x86_get_vcpu_events(
12246 				vcpu, &vcpu->run->s.regs.events);
12247 }
12248 
sync_regs(struct kvm_vcpu * vcpu)12249 static int sync_regs(struct kvm_vcpu *vcpu)
12250 {
12251 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12252 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
12253 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12254 	}
12255 
12256 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12257 		struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12258 
12259 		if (__set_sregs(vcpu, &sregs))
12260 			return -EINVAL;
12261 
12262 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12263 	}
12264 
12265 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12266 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12267 
12268 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12269 			return -EINVAL;
12270 
12271 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12272 	}
12273 
12274 	return 0;
12275 }
12276 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12277 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12278 {
12279 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12280 		pr_warn_once("SMP vm created on host with unstable TSC; "
12281 			     "guest TSC will not be reliable\n");
12282 
12283 	if (!kvm->arch.max_vcpu_ids)
12284 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12285 
12286 	if (id >= kvm->arch.max_vcpu_ids)
12287 		return -EINVAL;
12288 
12289 	return kvm_x86_call(vcpu_precreate)(kvm);
12290 }
12291 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12292 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12293 {
12294 	struct page *page;
12295 	int r;
12296 
12297 	vcpu->arch.last_vmentry_cpu = -1;
12298 	vcpu->arch.regs_avail = ~0;
12299 	vcpu->arch.regs_dirty = ~0;
12300 
12301 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12302 
12303 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12304 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12305 	else
12306 		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
12307 
12308 	r = kvm_mmu_create(vcpu);
12309 	if (r < 0)
12310 		return r;
12311 
12312 	r = kvm_create_lapic(vcpu);
12313 	if (r < 0)
12314 		goto fail_mmu_destroy;
12315 
12316 	r = -ENOMEM;
12317 
12318 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12319 	if (!page)
12320 		goto fail_free_lapic;
12321 	vcpu->arch.pio_data = page_address(page);
12322 
12323 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12324 				       GFP_KERNEL_ACCOUNT);
12325 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12326 					    GFP_KERNEL_ACCOUNT);
12327 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12328 		goto fail_free_mce_banks;
12329 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12330 
12331 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12332 				GFP_KERNEL_ACCOUNT))
12333 		goto fail_free_mce_banks;
12334 
12335 	if (!alloc_emulate_ctxt(vcpu))
12336 		goto free_wbinvd_dirty_mask;
12337 
12338 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12339 		pr_err("failed to allocate vcpu's fpu\n");
12340 		goto free_emulate_ctxt;
12341 	}
12342 
12343 	vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
12344 	vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
12345 
12346 	kvm_async_pf_hash_reset(vcpu);
12347 
12348 	vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12349 	kvm_pmu_init(vcpu);
12350 
12351 	vcpu->arch.pending_external_vector = -1;
12352 	vcpu->arch.preempted_in_kernel = false;
12353 
12354 #if IS_ENABLED(CONFIG_HYPERV)
12355 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
12356 #endif
12357 
12358 	r = kvm_x86_call(vcpu_create)(vcpu);
12359 	if (r)
12360 		goto free_guest_fpu;
12361 
12362 	vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12363 	vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12364 	kvm_xen_init_vcpu(vcpu);
12365 	vcpu_load(vcpu);
12366 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12367 	kvm_vcpu_reset(vcpu, false);
12368 	kvm_init_mmu(vcpu);
12369 	vcpu_put(vcpu);
12370 	return 0;
12371 
12372 free_guest_fpu:
12373 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12374 free_emulate_ctxt:
12375 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12376 free_wbinvd_dirty_mask:
12377 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12378 fail_free_mce_banks:
12379 	kfree(vcpu->arch.mce_banks);
12380 	kfree(vcpu->arch.mci_ctl2_banks);
12381 	free_page((unsigned long)vcpu->arch.pio_data);
12382 fail_free_lapic:
12383 	kvm_free_lapic(vcpu);
12384 fail_mmu_destroy:
12385 	kvm_mmu_destroy(vcpu);
12386 	return r;
12387 }
12388 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12389 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12390 {
12391 	struct kvm *kvm = vcpu->kvm;
12392 
12393 	if (mutex_lock_killable(&vcpu->mutex))
12394 		return;
12395 	vcpu_load(vcpu);
12396 	kvm_synchronize_tsc(vcpu, NULL);
12397 	vcpu_put(vcpu);
12398 
12399 	/* poll control enabled by default */
12400 	vcpu->arch.msr_kvm_poll_control = 1;
12401 
12402 	mutex_unlock(&vcpu->mutex);
12403 
12404 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12405 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12406 						KVMCLOCK_SYNC_PERIOD);
12407 }
12408 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12409 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12410 {
12411 	int idx;
12412 
12413 	kvmclock_reset(vcpu);
12414 
12415 	kvm_x86_call(vcpu_free)(vcpu);
12416 
12417 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12418 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12419 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12420 
12421 	kvm_xen_destroy_vcpu(vcpu);
12422 	kvm_hv_vcpu_uninit(vcpu);
12423 	kvm_pmu_destroy(vcpu);
12424 	kfree(vcpu->arch.mce_banks);
12425 	kfree(vcpu->arch.mci_ctl2_banks);
12426 	kvm_free_lapic(vcpu);
12427 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12428 	kvm_mmu_destroy(vcpu);
12429 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12430 	free_page((unsigned long)vcpu->arch.pio_data);
12431 	kvfree(vcpu->arch.cpuid_entries);
12432 }
12433 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12434 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12435 {
12436 	struct kvm_cpuid_entry2 *cpuid_0x1;
12437 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
12438 	unsigned long new_cr0;
12439 
12440 	/*
12441 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12442 	 * to handle side effects.  RESET emulation hits those flows and relies
12443 	 * on emulated/virtualized registers, including those that are loaded
12444 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
12445 	 * to detect improper or missing initialization.
12446 	 */
12447 	WARN_ON_ONCE(!init_event &&
12448 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12449 
12450 	/*
12451 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12452 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
12453 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12454 	 * bits), i.e. virtualization is disabled.
12455 	 */
12456 	if (is_guest_mode(vcpu))
12457 		kvm_leave_nested(vcpu);
12458 
12459 	kvm_lapic_reset(vcpu, init_event);
12460 
12461 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12462 	vcpu->arch.hflags = 0;
12463 
12464 	vcpu->arch.smi_pending = 0;
12465 	vcpu->arch.smi_count = 0;
12466 	atomic_set(&vcpu->arch.nmi_queued, 0);
12467 	vcpu->arch.nmi_pending = 0;
12468 	vcpu->arch.nmi_injected = false;
12469 	kvm_clear_interrupt_queue(vcpu);
12470 	kvm_clear_exception_queue(vcpu);
12471 
12472 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12473 	kvm_update_dr0123(vcpu);
12474 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12475 	vcpu->arch.dr7 = DR7_FIXED_1;
12476 	kvm_update_dr7(vcpu);
12477 
12478 	vcpu->arch.cr2 = 0;
12479 
12480 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12481 	vcpu->arch.apf.msr_en_val = 0;
12482 	vcpu->arch.apf.msr_int_val = 0;
12483 	vcpu->arch.st.msr_val = 0;
12484 
12485 	kvmclock_reset(vcpu);
12486 
12487 	kvm_clear_async_pf_completion_queue(vcpu);
12488 	kvm_async_pf_hash_reset(vcpu);
12489 	vcpu->arch.apf.halted = false;
12490 
12491 	if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12492 		struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12493 
12494 		/*
12495 		 * All paths that lead to INIT are required to load the guest's
12496 		 * FPU state (because most paths are buried in KVM_RUN).
12497 		 */
12498 		if (init_event)
12499 			kvm_put_guest_fpu(vcpu);
12500 
12501 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12502 		fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12503 
12504 		if (init_event)
12505 			kvm_load_guest_fpu(vcpu);
12506 	}
12507 
12508 	if (!init_event) {
12509 		vcpu->arch.smbase = 0x30000;
12510 
12511 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12512 
12513 		vcpu->arch.msr_misc_features_enables = 0;
12514 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12515 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12516 
12517 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12518 		__kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12519 	}
12520 
12521 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12522 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12523 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12524 
12525 	/*
12526 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12527 	 * if no CPUID match is found.  Note, it's impossible to get a match at
12528 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12529 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12530 	 * on RESET.  But, go through the motions in case that's ever remedied.
12531 	 */
12532 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12533 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12534 
12535 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
12536 
12537 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12538 	kvm_rip_write(vcpu, 0xfff0);
12539 
12540 	vcpu->arch.cr3 = 0;
12541 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12542 
12543 	/*
12544 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
12545 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12546 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
12547 	 */
12548 	new_cr0 = X86_CR0_ET;
12549 	if (init_event)
12550 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12551 	else
12552 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12553 
12554 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
12555 	kvm_x86_call(set_cr4)(vcpu, 0);
12556 	kvm_x86_call(set_efer)(vcpu, 0);
12557 	kvm_x86_call(update_exception_bitmap)(vcpu);
12558 
12559 	/*
12560 	 * On the standard CR0/CR4/EFER modification paths, there are several
12561 	 * complex conditions determining whether the MMU has to be reset and/or
12562 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
12563 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12564 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12565 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
12566 	 */
12567 	if (old_cr0 & X86_CR0_PG) {
12568 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12569 		kvm_mmu_reset_context(vcpu);
12570 	}
12571 
12572 	/*
12573 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
12574 	 * APM states the TLBs are untouched by INIT, but it also states that
12575 	 * the TLBs are flushed on "External initialization of the processor."
12576 	 * Flush the guest TLB regardless of vendor, there is no meaningful
12577 	 * benefit in relying on the guest to flush the TLB immediately after
12578 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
12579 	 * performance perspective.
12580 	 */
12581 	if (init_event)
12582 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12583 }
12584 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12585 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12586 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12587 {
12588 	struct kvm_segment cs;
12589 
12590 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12591 	cs.selector = vector << 8;
12592 	cs.base = vector << 12;
12593 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12594 	kvm_rip_write(vcpu, 0);
12595 }
12596 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12597 
kvm_arch_enable_virtualization(void)12598 void kvm_arch_enable_virtualization(void)
12599 {
12600 	cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12601 }
12602 
kvm_arch_disable_virtualization(void)12603 void kvm_arch_disable_virtualization(void)
12604 {
12605 	cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12606 }
12607 
kvm_arch_enable_virtualization_cpu(void)12608 int kvm_arch_enable_virtualization_cpu(void)
12609 {
12610 	struct kvm *kvm;
12611 	struct kvm_vcpu *vcpu;
12612 	unsigned long i;
12613 	int ret;
12614 	u64 local_tsc;
12615 	u64 max_tsc = 0;
12616 	bool stable, backwards_tsc = false;
12617 
12618 	kvm_user_return_msr_cpu_online();
12619 
12620 	ret = kvm_x86_check_processor_compatibility();
12621 	if (ret)
12622 		return ret;
12623 
12624 	ret = kvm_x86_call(enable_virtualization_cpu)();
12625 	if (ret != 0)
12626 		return ret;
12627 
12628 	local_tsc = rdtsc();
12629 	stable = !kvm_check_tsc_unstable();
12630 	list_for_each_entry(kvm, &vm_list, vm_list) {
12631 		kvm_for_each_vcpu(i, vcpu, kvm) {
12632 			if (!stable && vcpu->cpu == smp_processor_id())
12633 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12634 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12635 				backwards_tsc = true;
12636 				if (vcpu->arch.last_host_tsc > max_tsc)
12637 					max_tsc = vcpu->arch.last_host_tsc;
12638 			}
12639 		}
12640 	}
12641 
12642 	/*
12643 	 * Sometimes, even reliable TSCs go backwards.  This happens on
12644 	 * platforms that reset TSC during suspend or hibernate actions, but
12645 	 * maintain synchronization.  We must compensate.  Fortunately, we can
12646 	 * detect that condition here, which happens early in CPU bringup,
12647 	 * before any KVM threads can be running.  Unfortunately, we can't
12648 	 * bring the TSCs fully up to date with real time, as we aren't yet far
12649 	 * enough into CPU bringup that we know how much real time has actually
12650 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12651 	 * variables that haven't been updated yet.
12652 	 *
12653 	 * So we simply find the maximum observed TSC above, then record the
12654 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
12655 	 * the adjustment will be applied.  Note that we accumulate
12656 	 * adjustments, in case multiple suspend cycles happen before some VCPU
12657 	 * gets a chance to run again.  In the event that no KVM threads get a
12658 	 * chance to run, we will miss the entire elapsed period, as we'll have
12659 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12660 	 * loose cycle time.  This isn't too big a deal, since the loss will be
12661 	 * uniform across all VCPUs (not to mention the scenario is extremely
12662 	 * unlikely). It is possible that a second hibernate recovery happens
12663 	 * much faster than a first, causing the observed TSC here to be
12664 	 * smaller; this would require additional padding adjustment, which is
12665 	 * why we set last_host_tsc to the local tsc observed here.
12666 	 *
12667 	 * N.B. - this code below runs only on platforms with reliable TSC,
12668 	 * as that is the only way backwards_tsc is set above.  Also note
12669 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12670 	 * have the same delta_cyc adjustment applied if backwards_tsc
12671 	 * is detected.  Note further, this adjustment is only done once,
12672 	 * as we reset last_host_tsc on all VCPUs to stop this from being
12673 	 * called multiple times (one for each physical CPU bringup).
12674 	 *
12675 	 * Platforms with unreliable TSCs don't have to deal with this, they
12676 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
12677 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
12678 	 * guarantee that they stay in perfect synchronization.
12679 	 */
12680 	if (backwards_tsc) {
12681 		u64 delta_cyc = max_tsc - local_tsc;
12682 		list_for_each_entry(kvm, &vm_list, vm_list) {
12683 			kvm->arch.backwards_tsc_observed = true;
12684 			kvm_for_each_vcpu(i, vcpu, kvm) {
12685 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
12686 				vcpu->arch.last_host_tsc = local_tsc;
12687 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12688 			}
12689 
12690 			/*
12691 			 * We have to disable TSC offset matching.. if you were
12692 			 * booting a VM while issuing an S4 host suspend....
12693 			 * you may have some problem.  Solving this issue is
12694 			 * left as an exercise to the reader.
12695 			 */
12696 			kvm->arch.last_tsc_nsec = 0;
12697 			kvm->arch.last_tsc_write = 0;
12698 		}
12699 
12700 	}
12701 	return 0;
12702 }
12703 
kvm_arch_disable_virtualization_cpu(void)12704 void kvm_arch_disable_virtualization_cpu(void)
12705 {
12706 	kvm_x86_call(disable_virtualization_cpu)();
12707 	drop_user_return_notifiers();
12708 }
12709 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)12710 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12711 {
12712 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12713 }
12714 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)12715 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12716 {
12717 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12718 }
12719 
kvm_arch_free_vm(struct kvm * kvm)12720 void kvm_arch_free_vm(struct kvm *kvm)
12721 {
12722 #if IS_ENABLED(CONFIG_HYPERV)
12723 	kfree(kvm->arch.hv_pa_pg);
12724 #endif
12725 	__kvm_arch_free_vm(kvm);
12726 }
12727 
12728 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)12729 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12730 {
12731 	int ret;
12732 	unsigned long flags;
12733 
12734 	if (!kvm_is_vm_type_supported(type))
12735 		return -EINVAL;
12736 
12737 	kvm->arch.vm_type = type;
12738 	kvm->arch.has_private_mem =
12739 		(type == KVM_X86_SW_PROTECTED_VM);
12740 	/* Decided by the vendor code for other VM types.  */
12741 	kvm->arch.pre_fault_allowed =
12742 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
12743 
12744 	ret = kvm_page_track_init(kvm);
12745 	if (ret)
12746 		goto out;
12747 
12748 	kvm_mmu_init_vm(kvm);
12749 
12750 	ret = kvm_x86_call(vm_init)(kvm);
12751 	if (ret)
12752 		goto out_uninit_mmu;
12753 
12754 	INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12755 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12756 
12757 	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12758 	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12759 	/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12760 	set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12761 		&kvm->arch.irq_sources_bitmap);
12762 
12763 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12764 	mutex_init(&kvm->arch.apic_map_lock);
12765 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12766 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12767 
12768 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12769 	pvclock_update_vm_gtod_copy(kvm);
12770 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12771 
12772 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12773 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
12774 	kvm->arch.guest_can_read_msr_platform_info = true;
12775 	kvm->arch.enable_pmu = enable_pmu;
12776 
12777 #if IS_ENABLED(CONFIG_HYPERV)
12778 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12779 	kvm->arch.hv_root_tdp = INVALID_PAGE;
12780 #endif
12781 
12782 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12783 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12784 
12785 	kvm_apicv_init(kvm);
12786 	kvm_hv_init_vm(kvm);
12787 	kvm_xen_init_vm(kvm);
12788 
12789 	return 0;
12790 
12791 out_uninit_mmu:
12792 	kvm_mmu_uninit_vm(kvm);
12793 	kvm_page_track_cleanup(kvm);
12794 out:
12795 	return ret;
12796 }
12797 
kvm_arch_post_init_vm(struct kvm * kvm)12798 int kvm_arch_post_init_vm(struct kvm *kvm)
12799 {
12800 	once_init(&kvm->arch.nx_once);
12801 	return 0;
12802 }
12803 
kvm_unload_vcpu_mmu(struct kvm_vcpu * vcpu)12804 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
12805 {
12806 	vcpu_load(vcpu);
12807 	kvm_mmu_unload(vcpu);
12808 	vcpu_put(vcpu);
12809 }
12810 
kvm_unload_vcpu_mmus(struct kvm * kvm)12811 static void kvm_unload_vcpu_mmus(struct kvm *kvm)
12812 {
12813 	unsigned long i;
12814 	struct kvm_vcpu *vcpu;
12815 
12816 	kvm_for_each_vcpu(i, vcpu, kvm) {
12817 		kvm_clear_async_pf_completion_queue(vcpu);
12818 		kvm_unload_vcpu_mmu(vcpu);
12819 	}
12820 }
12821 
kvm_arch_sync_events(struct kvm * kvm)12822 void kvm_arch_sync_events(struct kvm *kvm)
12823 {
12824 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12825 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12826 	kvm_free_pit(kvm);
12827 }
12828 
12829 /**
12830  * __x86_set_memory_region: Setup KVM internal memory slot
12831  *
12832  * @kvm: the kvm pointer to the VM.
12833  * @id: the slot ID to setup.
12834  * @gpa: the GPA to install the slot (unused when @size == 0).
12835  * @size: the size of the slot. Set to zero to uninstall a slot.
12836  *
12837  * This function helps to setup a KVM internal memory slot.  Specify
12838  * @size > 0 to install a new slot, while @size == 0 to uninstall a
12839  * slot.  The return code can be one of the following:
12840  *
12841  *   HVA:           on success (uninstall will return a bogus HVA)
12842  *   -errno:        on error
12843  *
12844  * The caller should always use IS_ERR() to check the return value
12845  * before use.  Note, the KVM internal memory slots are guaranteed to
12846  * remain valid and unchanged until the VM is destroyed, i.e., the
12847  * GPA->HVA translation will not change.  However, the HVA is a user
12848  * address, i.e. its accessibility is not guaranteed, and must be
12849  * accessed via __copy_{to,from}_user().
12850  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)12851 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12852 				      u32 size)
12853 {
12854 	int i, r;
12855 	unsigned long hva, old_npages;
12856 	struct kvm_memslots *slots = kvm_memslots(kvm);
12857 	struct kvm_memory_slot *slot;
12858 
12859 	/* Called with kvm->slots_lock held.  */
12860 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12861 		return ERR_PTR_USR(-EINVAL);
12862 
12863 	slot = id_to_memslot(slots, id);
12864 	if (size) {
12865 		if (slot && slot->npages)
12866 			return ERR_PTR_USR(-EEXIST);
12867 
12868 		/*
12869 		 * MAP_SHARED to prevent internal slot pages from being moved
12870 		 * by fork()/COW.
12871 		 */
12872 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12873 			      MAP_SHARED | MAP_ANONYMOUS, 0);
12874 		if (IS_ERR_VALUE(hva))
12875 			return (void __user *)hva;
12876 	} else {
12877 		if (!slot || !slot->npages)
12878 			return NULL;
12879 
12880 		old_npages = slot->npages;
12881 		hva = slot->userspace_addr;
12882 	}
12883 
12884 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
12885 		struct kvm_userspace_memory_region2 m;
12886 
12887 		m.slot = id | (i << 16);
12888 		m.flags = 0;
12889 		m.guest_phys_addr = gpa;
12890 		m.userspace_addr = hva;
12891 		m.memory_size = size;
12892 		r = __kvm_set_memory_region(kvm, &m);
12893 		if (r < 0)
12894 			return ERR_PTR_USR(r);
12895 	}
12896 
12897 	if (!size)
12898 		vm_munmap(hva, old_npages * PAGE_SIZE);
12899 
12900 	return (void __user *)hva;
12901 }
12902 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12903 
kvm_arch_pre_destroy_vm(struct kvm * kvm)12904 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12905 {
12906 	kvm_mmu_pre_destroy_vm(kvm);
12907 }
12908 
kvm_arch_destroy_vm(struct kvm * kvm)12909 void kvm_arch_destroy_vm(struct kvm *kvm)
12910 {
12911 	if (current->mm == kvm->mm) {
12912 		/*
12913 		 * Free memory regions allocated on behalf of userspace,
12914 		 * unless the memory map has changed due to process exit
12915 		 * or fd copying.
12916 		 */
12917 		mutex_lock(&kvm->slots_lock);
12918 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12919 					0, 0);
12920 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12921 					0, 0);
12922 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12923 		mutex_unlock(&kvm->slots_lock);
12924 	}
12925 	kvm_unload_vcpu_mmus(kvm);
12926 	kvm_destroy_vcpus(kvm);
12927 	kvm_x86_call(vm_destroy)(kvm);
12928 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12929 	kvm_pic_destroy(kvm);
12930 	kvm_ioapic_destroy(kvm);
12931 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12932 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12933 	kvm_mmu_uninit_vm(kvm);
12934 	kvm_page_track_cleanup(kvm);
12935 	kvm_xen_destroy_vm(kvm);
12936 	kvm_hv_destroy_vm(kvm);
12937 }
12938 
memslot_rmap_free(struct kvm_memory_slot * slot)12939 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12940 {
12941 	int i;
12942 
12943 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12944 		vfree(slot->arch.rmap[i]);
12945 		slot->arch.rmap[i] = NULL;
12946 	}
12947 }
12948 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12949 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12950 {
12951 	int i;
12952 
12953 	memslot_rmap_free(slot);
12954 
12955 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12956 		vfree(slot->arch.lpage_info[i - 1]);
12957 		slot->arch.lpage_info[i - 1] = NULL;
12958 	}
12959 
12960 	kvm_page_track_free_memslot(slot);
12961 }
12962 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)12963 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12964 {
12965 	const int sz = sizeof(*slot->arch.rmap[0]);
12966 	int i;
12967 
12968 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12969 		int level = i + 1;
12970 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
12971 
12972 		if (slot->arch.rmap[i])
12973 			continue;
12974 
12975 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
12976 		if (!slot->arch.rmap[i]) {
12977 			memslot_rmap_free(slot);
12978 			return -ENOMEM;
12979 		}
12980 	}
12981 
12982 	return 0;
12983 }
12984 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)12985 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
12986 				      struct kvm_memory_slot *slot)
12987 {
12988 	unsigned long npages = slot->npages;
12989 	int i, r;
12990 
12991 	/*
12992 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
12993 	 * old arrays will be freed by __kvm_set_memory_region() if installing
12994 	 * the new memslot is successful.
12995 	 */
12996 	memset(&slot->arch, 0, sizeof(slot->arch));
12997 
12998 	if (kvm_memslots_have_rmaps(kvm)) {
12999 		r = memslot_rmap_alloc(slot, npages);
13000 		if (r)
13001 			return r;
13002 	}
13003 
13004 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13005 		struct kvm_lpage_info *linfo;
13006 		unsigned long ugfn;
13007 		int lpages;
13008 		int level = i + 1;
13009 
13010 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13011 
13012 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13013 		if (!linfo)
13014 			goto out_free;
13015 
13016 		slot->arch.lpage_info[i - 1] = linfo;
13017 
13018 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13019 			linfo[0].disallow_lpage = 1;
13020 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13021 			linfo[lpages - 1].disallow_lpage = 1;
13022 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
13023 		/*
13024 		 * If the gfn and userspace address are not aligned wrt each
13025 		 * other, disable large page support for this slot.
13026 		 */
13027 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13028 			unsigned long j;
13029 
13030 			for (j = 0; j < lpages; ++j)
13031 				linfo[j].disallow_lpage = 1;
13032 		}
13033 	}
13034 
13035 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13036 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13037 #endif
13038 
13039 	if (kvm_page_track_create_memslot(kvm, slot, npages))
13040 		goto out_free;
13041 
13042 	return 0;
13043 
13044 out_free:
13045 	memslot_rmap_free(slot);
13046 
13047 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13048 		vfree(slot->arch.lpage_info[i - 1]);
13049 		slot->arch.lpage_info[i - 1] = NULL;
13050 	}
13051 	return -ENOMEM;
13052 }
13053 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13054 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13055 {
13056 	struct kvm_vcpu *vcpu;
13057 	unsigned long i;
13058 
13059 	/*
13060 	 * memslots->generation has been incremented.
13061 	 * mmio generation may have reached its maximum value.
13062 	 */
13063 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13064 
13065 	/* Force re-initialization of steal_time cache */
13066 	kvm_for_each_vcpu(i, vcpu, kvm)
13067 		kvm_vcpu_kick(vcpu);
13068 }
13069 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13070 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13071 				   const struct kvm_memory_slot *old,
13072 				   struct kvm_memory_slot *new,
13073 				   enum kvm_mr_change change)
13074 {
13075 	/*
13076 	 * KVM doesn't support moving memslots when there are external page
13077 	 * trackers attached to the VM, i.e. if KVMGT is in use.
13078 	 */
13079 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13080 		return -EINVAL;
13081 
13082 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13083 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13084 			return -EINVAL;
13085 
13086 		return kvm_alloc_memslot_metadata(kvm, new);
13087 	}
13088 
13089 	if (change == KVM_MR_FLAGS_ONLY)
13090 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
13091 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13092 		return -EIO;
13093 
13094 	return 0;
13095 }
13096 
13097 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13098 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13099 {
13100 	int nr_slots;
13101 
13102 	if (!kvm_x86_ops.cpu_dirty_log_size)
13103 		return;
13104 
13105 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13106 	if ((enable && nr_slots == 1) || !nr_slots)
13107 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13108 }
13109 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13110 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13111 				     struct kvm_memory_slot *old,
13112 				     const struct kvm_memory_slot *new,
13113 				     enum kvm_mr_change change)
13114 {
13115 	u32 old_flags = old ? old->flags : 0;
13116 	u32 new_flags = new ? new->flags : 0;
13117 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13118 
13119 	/*
13120 	 * Update CPU dirty logging if dirty logging is being toggled.  This
13121 	 * applies to all operations.
13122 	 */
13123 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13124 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13125 
13126 	/*
13127 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
13128 	 * made writable) or CREATE/MOVE/DELETE of a slot.
13129 	 *
13130 	 * For a memslot with dirty logging disabled:
13131 	 * CREATE:      No dirty mappings will already exist.
13132 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13133 	 *		kvm_arch_flush_shadow_memslot()
13134 	 *
13135 	 * For a memslot with dirty logging enabled:
13136 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
13137 	 *		and no dirty bits to clear.
13138 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13139 	 *		kvm_arch_flush_shadow_memslot().
13140 	 */
13141 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13142 		return;
13143 
13144 	/*
13145 	 * READONLY and non-flags changes were filtered out above, and the only
13146 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13147 	 * logging isn't being toggled on or off.
13148 	 */
13149 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13150 		return;
13151 
13152 	if (!log_dirty_pages) {
13153 		/*
13154 		 * Dirty logging tracks sptes in 4k granularity, meaning that
13155 		 * large sptes have to be split.  If live migration succeeds,
13156 		 * the guest in the source machine will be destroyed and large
13157 		 * sptes will be created in the destination.  However, if the
13158 		 * guest continues to run in the source machine (for example if
13159 		 * live migration fails), small sptes will remain around and
13160 		 * cause bad performance.
13161 		 *
13162 		 * Scan sptes if dirty logging has been stopped, dropping those
13163 		 * which can be collapsed into a single large-page spte.  Later
13164 		 * page faults will create the large-page sptes.
13165 		 */
13166 		kvm_mmu_zap_collapsible_sptes(kvm, new);
13167 	} else {
13168 		/*
13169 		 * Initially-all-set does not require write protecting any page,
13170 		 * because they're all assumed to be dirty.
13171 		 */
13172 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13173 			return;
13174 
13175 		if (READ_ONCE(eager_page_split))
13176 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13177 
13178 		if (kvm_x86_ops.cpu_dirty_log_size) {
13179 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13180 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13181 		} else {
13182 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13183 		}
13184 
13185 		/*
13186 		 * Unconditionally flush the TLBs after enabling dirty logging.
13187 		 * A flush is almost always going to be necessary (see below),
13188 		 * and unconditionally flushing allows the helpers to omit
13189 		 * the subtly complex checks when removing write access.
13190 		 *
13191 		 * Do the flush outside of mmu_lock to reduce the amount of
13192 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
13193 		 * safe as KVM only needs to guarantee the slot is fully
13194 		 * write-protected before returning to userspace, i.e. before
13195 		 * userspace can consume the dirty status.
13196 		 *
13197 		 * Flushing outside of mmu_lock requires KVM to be careful when
13198 		 * making decisions based on writable status of an SPTE, e.g. a
13199 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13200 		 *
13201 		 * Specifically, KVM also write-protects guest page tables to
13202 		 * monitor changes when using shadow paging, and must guarantee
13203 		 * no CPUs can write to those page before mmu_lock is dropped.
13204 		 * Because CPUs may have stale TLB entries at this point, a
13205 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13206 		 *
13207 		 * KVM also allows making SPTES writable outside of mmu_lock,
13208 		 * e.g. to allow dirty logging without taking mmu_lock.
13209 		 *
13210 		 * To handle these scenarios, KVM uses a separate software-only
13211 		 * bit (MMU-writable) to track if a SPTE is !writable due to
13212 		 * a guest page table being write-protected (KVM clears the
13213 		 * MMU-writable flag when write-protecting for shadow paging).
13214 		 *
13215 		 * The use of MMU-writable is also the primary motivation for
13216 		 * the unconditional flush.  Because KVM must guarantee that a
13217 		 * CPU doesn't contain stale, writable TLB entries for a
13218 		 * !MMU-writable SPTE, KVM must flush if it encounters any
13219 		 * MMU-writable SPTE regardless of whether the actual hardware
13220 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
13221 		 * to flush, while unconditionally flushing allows the "remove
13222 		 * write access" helpers to ignore MMU-writable entirely.
13223 		 *
13224 		 * See is_writable_pte() for more details (the case involving
13225 		 * access-tracked SPTEs is particularly relevant).
13226 		 */
13227 		kvm_flush_remote_tlbs_memslot(kvm, new);
13228 	}
13229 }
13230 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13231 void kvm_arch_commit_memory_region(struct kvm *kvm,
13232 				struct kvm_memory_slot *old,
13233 				const struct kvm_memory_slot *new,
13234 				enum kvm_mr_change change)
13235 {
13236 	if (change == KVM_MR_DELETE)
13237 		kvm_page_track_delete_slot(kvm, old);
13238 
13239 	if (!kvm->arch.n_requested_mmu_pages &&
13240 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13241 		unsigned long nr_mmu_pages;
13242 
13243 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13244 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13245 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13246 	}
13247 
13248 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
13249 
13250 	/* Free the arrays associated with the old memslot. */
13251 	if (change == KVM_MR_MOVE)
13252 		kvm_arch_free_memslot(kvm, old);
13253 }
13254 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13255 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13256 {
13257 	if (vcpu->arch.guest_state_protected)
13258 		return true;
13259 
13260 	return kvm_x86_call(get_cpl)(vcpu) == 0;
13261 }
13262 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13263 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13264 {
13265 	return kvm_rip_read(vcpu);
13266 }
13267 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13268 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13269 {
13270 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13271 }
13272 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13273 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13274 {
13275 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
13276 }
13277 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13278 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13279 {
13280 	/* Can't read the RIP when guest state is protected, just return 0 */
13281 	if (vcpu->arch.guest_state_protected)
13282 		return 0;
13283 
13284 	if (is_64_bit_mode(vcpu))
13285 		return kvm_rip_read(vcpu);
13286 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13287 		     kvm_rip_read(vcpu));
13288 }
13289 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13290 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13291 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13292 {
13293 	return kvm_get_linear_rip(vcpu) == linear_rip;
13294 }
13295 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13296 
kvm_get_rflags(struct kvm_vcpu * vcpu)13297 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13298 {
13299 	unsigned long rflags;
13300 
13301 	rflags = kvm_x86_call(get_rflags)(vcpu);
13302 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13303 		rflags &= ~X86_EFLAGS_TF;
13304 	return rflags;
13305 }
13306 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13307 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13308 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13309 {
13310 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13311 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13312 		rflags |= X86_EFLAGS_TF;
13313 	kvm_x86_call(set_rflags)(vcpu, rflags);
13314 }
13315 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13316 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13317 {
13318 	__kvm_set_rflags(vcpu, rflags);
13319 	kvm_make_request(KVM_REQ_EVENT, vcpu);
13320 }
13321 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13322 
kvm_async_pf_hash_fn(gfn_t gfn)13323 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13324 {
13325 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13326 
13327 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13328 }
13329 
kvm_async_pf_next_probe(u32 key)13330 static inline u32 kvm_async_pf_next_probe(u32 key)
13331 {
13332 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13333 }
13334 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13335 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13336 {
13337 	u32 key = kvm_async_pf_hash_fn(gfn);
13338 
13339 	while (vcpu->arch.apf.gfns[key] != ~0)
13340 		key = kvm_async_pf_next_probe(key);
13341 
13342 	vcpu->arch.apf.gfns[key] = gfn;
13343 }
13344 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13345 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13346 {
13347 	int i;
13348 	u32 key = kvm_async_pf_hash_fn(gfn);
13349 
13350 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
13351 		     (vcpu->arch.apf.gfns[key] != gfn &&
13352 		      vcpu->arch.apf.gfns[key] != ~0); i++)
13353 		key = kvm_async_pf_next_probe(key);
13354 
13355 	return key;
13356 }
13357 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13358 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13359 {
13360 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13361 }
13362 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13363 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13364 {
13365 	u32 i, j, k;
13366 
13367 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13368 
13369 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13370 		return;
13371 
13372 	while (true) {
13373 		vcpu->arch.apf.gfns[i] = ~0;
13374 		do {
13375 			j = kvm_async_pf_next_probe(j);
13376 			if (vcpu->arch.apf.gfns[j] == ~0)
13377 				return;
13378 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13379 			/*
13380 			 * k lies cyclically in ]i,j]
13381 			 * |    i.k.j |
13382 			 * |....j i.k.| or  |.k..j i...|
13383 			 */
13384 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13385 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13386 		i = j;
13387 	}
13388 }
13389 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13390 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13391 {
13392 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13393 
13394 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13395 				      sizeof(reason));
13396 }
13397 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13398 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13399 {
13400 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13401 
13402 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13403 					     &token, offset, sizeof(token));
13404 }
13405 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13406 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13407 {
13408 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13409 	u32 val;
13410 
13411 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13412 					 &val, offset, sizeof(val)))
13413 		return false;
13414 
13415 	return !val;
13416 }
13417 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13418 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13419 {
13420 
13421 	if (!kvm_pv_async_pf_enabled(vcpu))
13422 		return false;
13423 
13424 	if (vcpu->arch.apf.send_user_only &&
13425 	    kvm_x86_call(get_cpl)(vcpu) == 0)
13426 		return false;
13427 
13428 	if (is_guest_mode(vcpu)) {
13429 		/*
13430 		 * L1 needs to opt into the special #PF vmexits that are
13431 		 * used to deliver async page faults.
13432 		 */
13433 		return vcpu->arch.apf.delivery_as_pf_vmexit;
13434 	} else {
13435 		/*
13436 		 * Play it safe in case the guest temporarily disables paging.
13437 		 * The real mode IDT in particular is unlikely to have a #PF
13438 		 * exception setup.
13439 		 */
13440 		return is_paging(vcpu);
13441 	}
13442 }
13443 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13444 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13445 {
13446 	if (unlikely(!lapic_in_kernel(vcpu) ||
13447 		     kvm_event_needs_reinjection(vcpu) ||
13448 		     kvm_is_exception_pending(vcpu)))
13449 		return false;
13450 
13451 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13452 		return false;
13453 
13454 	/*
13455 	 * If interrupts are off we cannot even use an artificial
13456 	 * halt state.
13457 	 */
13458 	return kvm_arch_interrupt_allowed(vcpu);
13459 }
13460 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13461 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13462 				     struct kvm_async_pf *work)
13463 {
13464 	struct x86_exception fault;
13465 
13466 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13467 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13468 
13469 	if (kvm_can_deliver_async_pf(vcpu) &&
13470 	    !apf_put_user_notpresent(vcpu)) {
13471 		fault.vector = PF_VECTOR;
13472 		fault.error_code_valid = true;
13473 		fault.error_code = 0;
13474 		fault.nested_page_fault = false;
13475 		fault.address = work->arch.token;
13476 		fault.async_page_fault = true;
13477 		kvm_inject_page_fault(vcpu, &fault);
13478 		return true;
13479 	} else {
13480 		/*
13481 		 * It is not possible to deliver a paravirtualized asynchronous
13482 		 * page fault, but putting the guest in an artificial halt state
13483 		 * can be beneficial nevertheless: if an interrupt arrives, we
13484 		 * can deliver it timely and perhaps the guest will schedule
13485 		 * another process.  When the instruction that triggered a page
13486 		 * fault is retried, hopefully the page will be ready in the host.
13487 		 */
13488 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13489 		return false;
13490 	}
13491 }
13492 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13493 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13494 				 struct kvm_async_pf *work)
13495 {
13496 	struct kvm_lapic_irq irq = {
13497 		.delivery_mode = APIC_DM_FIXED,
13498 		.vector = vcpu->arch.apf.vec
13499 	};
13500 
13501 	if (work->wakeup_all)
13502 		work->arch.token = ~0; /* broadcast wakeup */
13503 	else
13504 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13505 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13506 
13507 	if ((work->wakeup_all || work->notpresent_injected) &&
13508 	    kvm_pv_async_pf_enabled(vcpu) &&
13509 	    !apf_put_user_ready(vcpu, work->arch.token)) {
13510 		vcpu->arch.apf.pageready_pending = true;
13511 		kvm_apic_set_irq(vcpu, &irq, NULL);
13512 	}
13513 
13514 	vcpu->arch.apf.halted = false;
13515 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13516 }
13517 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13518 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13519 {
13520 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
13521 	if (!vcpu->arch.apf.pageready_pending)
13522 		kvm_vcpu_kick(vcpu);
13523 }
13524 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13525 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13526 {
13527 	if (!kvm_pv_async_pf_enabled(vcpu))
13528 		return true;
13529 	else
13530 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13531 }
13532 
kvm_arch_start_assignment(struct kvm * kvm)13533 void kvm_arch_start_assignment(struct kvm *kvm)
13534 {
13535 	if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13536 		kvm_x86_call(pi_start_assignment)(kvm);
13537 }
13538 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13539 
kvm_arch_end_assignment(struct kvm * kvm)13540 void kvm_arch_end_assignment(struct kvm *kvm)
13541 {
13542 	atomic_dec(&kvm->arch.assigned_device_count);
13543 }
13544 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13545 
kvm_arch_has_assigned_device(struct kvm * kvm)13546 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13547 {
13548 	return raw_atomic_read(&kvm->arch.assigned_device_count);
13549 }
13550 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13551 
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13552 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13553 {
13554 	/*
13555 	 * Non-coherent DMA assignment and de-assignment may affect whether or
13556 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13557 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
13558 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
13559 	 * with the correct "ignore guest PAT" setting are created.
13560 	 */
13561 	if (kvm_mmu_may_ignore_guest_pat())
13562 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13563 }
13564 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13565 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13566 {
13567 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13568 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13569 }
13570 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13571 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13572 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13573 {
13574 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13575 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13576 }
13577 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13578 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13579 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13580 {
13581 	return atomic_read(&kvm->arch.noncoherent_dma_count);
13582 }
13583 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13584 
kvm_arch_has_irq_bypass(void)13585 bool kvm_arch_has_irq_bypass(void)
13586 {
13587 	return enable_apicv && irq_remapping_cap(IRQ_POSTING_CAP);
13588 }
13589 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13590 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13591 				      struct irq_bypass_producer *prod)
13592 {
13593 	struct kvm_kernel_irqfd *irqfd =
13594 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13595 	struct kvm *kvm = irqfd->kvm;
13596 	int ret;
13597 
13598 	kvm_arch_start_assignment(irqfd->kvm);
13599 
13600 	spin_lock_irq(&kvm->irqfds.lock);
13601 	irqfd->producer = prod;
13602 
13603 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13604 					   prod->irq, irqfd->gsi, 1);
13605 	if (ret)
13606 		kvm_arch_end_assignment(irqfd->kvm);
13607 
13608 	spin_unlock_irq(&kvm->irqfds.lock);
13609 
13610 
13611 	return ret;
13612 }
13613 
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13614 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13615 				      struct irq_bypass_producer *prod)
13616 {
13617 	int ret;
13618 	struct kvm_kernel_irqfd *irqfd =
13619 		container_of(cons, struct kvm_kernel_irqfd, consumer);
13620 	struct kvm *kvm = irqfd->kvm;
13621 
13622 	WARN_ON(irqfd->producer != prod);
13623 
13624 	/*
13625 	 * When producer of consumer is unregistered, we change back to
13626 	 * remapped mode, so we can re-use the current implementation
13627 	 * when the irq is masked/disabled or the consumer side (KVM
13628 	 * int this case doesn't want to receive the interrupts.
13629 	*/
13630 	spin_lock_irq(&kvm->irqfds.lock);
13631 	irqfd->producer = NULL;
13632 
13633 	ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13634 					   prod->irq, irqfd->gsi, 0);
13635 	if (ret)
13636 		printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13637 		       " fails: %d\n", irqfd->consumer.token, ret);
13638 
13639 	spin_unlock_irq(&kvm->irqfds.lock);
13640 
13641 
13642 	kvm_arch_end_assignment(irqfd->kvm);
13643 }
13644 
kvm_arch_update_irqfd_routing(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)13645 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13646 				   uint32_t guest_irq, bool set)
13647 {
13648 	return kvm_x86_call(pi_update_irte)(kvm, host_irq, guest_irq, set);
13649 }
13650 
kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)13651 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13652 				  struct kvm_kernel_irq_routing_entry *new)
13653 {
13654 	if (old->type != KVM_IRQ_ROUTING_MSI ||
13655 	    new->type != KVM_IRQ_ROUTING_MSI)
13656 		return true;
13657 
13658 	return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13659 }
13660 
kvm_vector_hashing_enabled(void)13661 bool kvm_vector_hashing_enabled(void)
13662 {
13663 	return vector_hashing;
13664 }
13665 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13666 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13667 {
13668 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13669 }
13670 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13671 
13672 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13673 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13674 {
13675 	return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13676 }
13677 #endif
13678 
13679 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13680 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13681 {
13682 	kvm_x86_call(gmem_invalidate)(start, end);
13683 }
13684 #endif
13685 
kvm_spec_ctrl_test_value(u64 value)13686 int kvm_spec_ctrl_test_value(u64 value)
13687 {
13688 	/*
13689 	 * test that setting IA32_SPEC_CTRL to given value
13690 	 * is allowed by the host processor
13691 	 */
13692 
13693 	u64 saved_value;
13694 	unsigned long flags;
13695 	int ret = 0;
13696 
13697 	local_irq_save(flags);
13698 
13699 	if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13700 		ret = 1;
13701 	else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13702 		ret = 1;
13703 	else
13704 		wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
13705 
13706 	local_irq_restore(flags);
13707 
13708 	return ret;
13709 }
13710 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13711 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)13712 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13713 {
13714 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13715 	struct x86_exception fault;
13716 	u64 access = error_code &
13717 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13718 
13719 	if (!(error_code & PFERR_PRESENT_MASK) ||
13720 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13721 		/*
13722 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13723 		 * tables probably do not match the TLB.  Just proceed
13724 		 * with the error code that the processor gave.
13725 		 */
13726 		fault.vector = PF_VECTOR;
13727 		fault.error_code_valid = true;
13728 		fault.error_code = error_code;
13729 		fault.nested_page_fault = false;
13730 		fault.address = gva;
13731 		fault.async_page_fault = false;
13732 	}
13733 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13734 }
13735 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13736 
13737 /*
13738  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13739  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13740  * indicates whether exit to userspace is needed.
13741  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)13742 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13743 			      struct x86_exception *e)
13744 {
13745 	if (r == X86EMUL_PROPAGATE_FAULT) {
13746 		if (KVM_BUG_ON(!e, vcpu->kvm))
13747 			return -EIO;
13748 
13749 		kvm_inject_emulated_page_fault(vcpu, e);
13750 		return 1;
13751 	}
13752 
13753 	/*
13754 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13755 	 * while handling a VMX instruction KVM could've handled the request
13756 	 * correctly by exiting to userspace and performing I/O but there
13757 	 * doesn't seem to be a real use-case behind such requests, just return
13758 	 * KVM_EXIT_INTERNAL_ERROR for now.
13759 	 */
13760 	kvm_prepare_emulation_failure_exit(vcpu);
13761 
13762 	return 0;
13763 }
13764 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13765 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)13766 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13767 {
13768 	bool pcid_enabled;
13769 	struct x86_exception e;
13770 	struct {
13771 		u64 pcid;
13772 		u64 gla;
13773 	} operand;
13774 	int r;
13775 
13776 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13777 	if (r != X86EMUL_CONTINUE)
13778 		return kvm_handle_memory_failure(vcpu, r, &e);
13779 
13780 	if (operand.pcid >> 12 != 0) {
13781 		kvm_inject_gp(vcpu, 0);
13782 		return 1;
13783 	}
13784 
13785 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
13786 
13787 	switch (type) {
13788 	case INVPCID_TYPE_INDIV_ADDR:
13789 		/*
13790 		 * LAM doesn't apply to addresses that are inputs to TLB
13791 		 * invalidation.
13792 		 */
13793 		if ((!pcid_enabled && (operand.pcid != 0)) ||
13794 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
13795 			kvm_inject_gp(vcpu, 0);
13796 			return 1;
13797 		}
13798 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13799 		return kvm_skip_emulated_instruction(vcpu);
13800 
13801 	case INVPCID_TYPE_SINGLE_CTXT:
13802 		if (!pcid_enabled && (operand.pcid != 0)) {
13803 			kvm_inject_gp(vcpu, 0);
13804 			return 1;
13805 		}
13806 
13807 		kvm_invalidate_pcid(vcpu, operand.pcid);
13808 		return kvm_skip_emulated_instruction(vcpu);
13809 
13810 	case INVPCID_TYPE_ALL_NON_GLOBAL:
13811 		/*
13812 		 * Currently, KVM doesn't mark global entries in the shadow
13813 		 * page tables, so a non-global flush just degenerates to a
13814 		 * global flush. If needed, we could optimize this later by
13815 		 * keeping track of global entries in shadow page tables.
13816 		 */
13817 
13818 		fallthrough;
13819 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
13820 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13821 		return kvm_skip_emulated_instruction(vcpu);
13822 
13823 	default:
13824 		kvm_inject_gp(vcpu, 0);
13825 		return 1;
13826 	}
13827 }
13828 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13829 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)13830 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13831 {
13832 	struct kvm_run *run = vcpu->run;
13833 	struct kvm_mmio_fragment *frag;
13834 	unsigned int len;
13835 
13836 	BUG_ON(!vcpu->mmio_needed);
13837 
13838 	/* Complete previous fragment */
13839 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13840 	len = min(8u, frag->len);
13841 	if (!vcpu->mmio_is_write)
13842 		memcpy(frag->data, run->mmio.data, len);
13843 
13844 	if (frag->len <= 8) {
13845 		/* Switch to the next fragment. */
13846 		frag++;
13847 		vcpu->mmio_cur_fragment++;
13848 	} else {
13849 		/* Go forward to the next mmio piece. */
13850 		frag->data += len;
13851 		frag->gpa += len;
13852 		frag->len -= len;
13853 	}
13854 
13855 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13856 		vcpu->mmio_needed = 0;
13857 
13858 		// VMG change, at this point, we're always done
13859 		// RIP has already been advanced
13860 		return 1;
13861 	}
13862 
13863 	// More MMIO is needed
13864 	run->mmio.phys_addr = frag->gpa;
13865 	run->mmio.len = min(8u, frag->len);
13866 	run->mmio.is_write = vcpu->mmio_is_write;
13867 	if (run->mmio.is_write)
13868 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13869 	run->exit_reason = KVM_EXIT_MMIO;
13870 
13871 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13872 
13873 	return 0;
13874 }
13875 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13876 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13877 			  void *data)
13878 {
13879 	int handled;
13880 	struct kvm_mmio_fragment *frag;
13881 
13882 	if (!data)
13883 		return -EINVAL;
13884 
13885 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13886 	if (handled == bytes)
13887 		return 1;
13888 
13889 	bytes -= handled;
13890 	gpa += handled;
13891 	data += handled;
13892 
13893 	/*TODO: Check if need to increment number of frags */
13894 	frag = vcpu->mmio_fragments;
13895 	vcpu->mmio_nr_fragments = 1;
13896 	frag->len = bytes;
13897 	frag->gpa = gpa;
13898 	frag->data = data;
13899 
13900 	vcpu->mmio_needed = 1;
13901 	vcpu->mmio_cur_fragment = 0;
13902 
13903 	vcpu->run->mmio.phys_addr = gpa;
13904 	vcpu->run->mmio.len = min(8u, frag->len);
13905 	vcpu->run->mmio.is_write = 1;
13906 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13907 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13908 
13909 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13910 
13911 	return 0;
13912 }
13913 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13914 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13915 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13916 			 void *data)
13917 {
13918 	int handled;
13919 	struct kvm_mmio_fragment *frag;
13920 
13921 	if (!data)
13922 		return -EINVAL;
13923 
13924 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13925 	if (handled == bytes)
13926 		return 1;
13927 
13928 	bytes -= handled;
13929 	gpa += handled;
13930 	data += handled;
13931 
13932 	/*TODO: Check if need to increment number of frags */
13933 	frag = vcpu->mmio_fragments;
13934 	vcpu->mmio_nr_fragments = 1;
13935 	frag->len = bytes;
13936 	frag->gpa = gpa;
13937 	frag->data = data;
13938 
13939 	vcpu->mmio_needed = 1;
13940 	vcpu->mmio_cur_fragment = 0;
13941 
13942 	vcpu->run->mmio.phys_addr = gpa;
13943 	vcpu->run->mmio.len = min(8u, frag->len);
13944 	vcpu->run->mmio.is_write = 0;
13945 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
13946 
13947 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13948 
13949 	return 0;
13950 }
13951 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13952 
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)13953 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13954 {
13955 	vcpu->arch.sev_pio_count -= count;
13956 	vcpu->arch.sev_pio_data += count * size;
13957 }
13958 
13959 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13960 			   unsigned int port);
13961 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)13962 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13963 {
13964 	int size = vcpu->arch.pio.size;
13965 	int port = vcpu->arch.pio.port;
13966 
13967 	vcpu->arch.pio.count = 0;
13968 	if (vcpu->arch.sev_pio_count)
13969 		return kvm_sev_es_outs(vcpu, size, port);
13970 	return 1;
13971 }
13972 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)13973 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13974 			   unsigned int port)
13975 {
13976 	for (;;) {
13977 		unsigned int count =
13978 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13979 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13980 
13981 		/* memcpy done already by emulator_pio_out.  */
13982 		advance_sev_es_emulated_pio(vcpu, count, size);
13983 		if (!ret)
13984 			break;
13985 
13986 		/* Emulation done by the kernel.  */
13987 		if (!vcpu->arch.sev_pio_count)
13988 			return 1;
13989 	}
13990 
13991 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
13992 	return 0;
13993 }
13994 
13995 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13996 			  unsigned int port);
13997 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)13998 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13999 {
14000 	unsigned count = vcpu->arch.pio.count;
14001 	int size = vcpu->arch.pio.size;
14002 	int port = vcpu->arch.pio.port;
14003 
14004 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14005 	advance_sev_es_emulated_pio(vcpu, count, size);
14006 	if (vcpu->arch.sev_pio_count)
14007 		return kvm_sev_es_ins(vcpu, size, port);
14008 	return 1;
14009 }
14010 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14011 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14012 			  unsigned int port)
14013 {
14014 	for (;;) {
14015 		unsigned int count =
14016 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14017 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14018 			break;
14019 
14020 		/* Emulation done by the kernel.  */
14021 		advance_sev_es_emulated_pio(vcpu, count, size);
14022 		if (!vcpu->arch.sev_pio_count)
14023 			return 1;
14024 	}
14025 
14026 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14027 	return 0;
14028 }
14029 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14030 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14031 			 unsigned int port, void *data,  unsigned int count,
14032 			 int in)
14033 {
14034 	vcpu->arch.sev_pio_data = data;
14035 	vcpu->arch.sev_pio_count = count;
14036 	return in ? kvm_sev_es_ins(vcpu, size, port)
14037 		  : kvm_sev_es_outs(vcpu, size, port);
14038 }
14039 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
14040 
14041 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14042 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14043 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14044 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14045 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14046 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14047 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14048 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14049 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14050 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14051 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14052 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14053 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14054 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14055 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14056 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14057 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14058 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14059 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
14060 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14061 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14062 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14063 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14064 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14065 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14066 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14067 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14068 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14069 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14070 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14071 
kvm_x86_init(void)14072 static int __init kvm_x86_init(void)
14073 {
14074 	kvm_init_xstate_sizes();
14075 
14076 	kvm_mmu_x86_module_init();
14077 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14078 	return 0;
14079 }
14080 module_init(kvm_x86_init);
14081 
kvm_x86_exit(void)14082 static void __exit kvm_x86_exit(void)
14083 {
14084 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14085 }
14086 module_exit(kvm_x86_exit);
14087