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