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