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