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