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