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