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