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