Merge tag 'io_uring-6.16-20250630' of git://git.kernel.dk/linux
[linux-2.6-block.git] / arch / x86 / kvm / x86.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
043405e1
CO
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.
4d5c5d0f
BAY
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
9611c187 10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
043405e1
CO
11 *
12 * Authors:
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
4d5c5d0f
BAY
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
043405e1 17 */
8d20bd63 18#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
043405e1 19
edf88417 20#include <linux/kvm_host.h>
313a3dc7 21#include "irq.h"
88197e6a 22#include "ioapic.h"
1d737c8a 23#include "mmu.h"
7837699f 24#include "i8254.h"
37817f29 25#include "tss.h"
5fdbf976 26#include "kvm_cache_regs.h"
2f728d66 27#include "kvm_emulate.h"
58ea7cf7 28#include "mmu/page_track.h"
26eef70c 29#include "x86.h"
00b27a3e 30#include "cpuid.h"
474a5bb9 31#include "pmu.h"
e83d5887 32#include "hyperv.h"
8df14af4 33#include "lapic.h"
23200b7a 34#include "xen.h"
b0b42197 35#include "smm.h"
313a3dc7 36
18068523 37#include <linux/clocksource.h>
4d5c5d0f 38#include <linux/interrupt.h>
313a3dc7
CO
39#include <linux/kvm.h>
40#include <linux/fs.h>
41#include <linux/vmalloc.h>
1767e931
PG
42#include <linux/export.h>
43#include <linux/moduleparam.h>
0de10343 44#include <linux/mman.h>
2bacc55c 45#include <linux/highmem.h>
19de40a8 46#include <linux/iommu.h>
c8076604 47#include <linux/cpufreq.h>
18863bdd 48#include <linux/user-return-notifier.h>
a983fb23 49#include <linux/srcu.h>
5a0e3ad6 50#include <linux/slab.h>
ff9d07a0 51#include <linux/perf_event.h>
7bee342a 52#include <linux/uaccess.h>
af585b92 53#include <linux/hash.h>
a1b60c1c 54#include <linux/pci.h>
16e8d74d
MT
55#include <linux/timekeeper_internal.h>
56#include <linux/pvclock_gtod.h>
87276880
FW
57#include <linux/kvm_irqfd.h>
58#include <linux/irqbypass.h>
3905f9ad 59#include <linux/sched/stat.h>
0c5f81da 60#include <linux/sched/isolation.h>
d0ec49d4 61#include <linux/mem_encrypt.h>
72c3c0fe 62#include <linux/entry-kvm.h>
7d62874f 63#include <linux/suspend.h>
4c8c3c7f 64#include <linux/smp.h>
3905f9ad 65
4c8c3c7f 66#include <trace/events/ipi.h>
aec51dc4 67#include <trace/events/kvm.h>
2ed152af 68
24f1e32c 69#include <asm/debugreg.h>
d825ed0a 70#include <asm/msr.h>
a5f61300 71#include <asm/desc.h>
890ca9ae 72#include <asm/mce.h>
784a4661 73#include <asm/pkru.h>
f89e32e0 74#include <linux/kernel_stat.h>
a0ff0611
TG
75#include <asm/fpu/api.h>
76#include <asm/fpu/xcr.h>
77#include <asm/fpu/xstate.h>
1d5f066e 78#include <asm/pvclock.h>
217fc9cf 79#include <asm/div64.h>
efc64404 80#include <asm/irq_remapping.h>
b0c39dc6 81#include <asm/mshyperv.h>
0092e434 82#include <asm/hypervisor.h>
9715092f 83#include <asm/tlbflush.h>
bf8c55d8 84#include <asm/intel_pt.h>
b3dc0695 85#include <asm/emulate_prefix.h>
fe7e9488 86#include <asm/sgx.h>
dd2cb348 87#include <clocksource/hyperv_timer.h>
043405e1 88
d1898b73
DH
89#define CREATE_TRACE_POINTS
90#include "trace.h"
91
313a3dc7 92#define MAX_IO_MSRS 256
938c8745 93
40269c03
SC
94/*
95 * Note, kvm_caps fields should *never* have default values, all fields must be
96 * recomputed from scratch during vendor module load, e.g. to account for a
97 * vendor module being reloaded with different module parameters.
98 */
555485bd 99struct kvm_caps kvm_caps __read_mostly;
938c8745 100EXPORT_SYMBOL_GPL(kvm_caps);
890ca9ae 101
7974c064
SC
102struct kvm_host_values kvm_host __read_mostly;
103EXPORT_SYMBOL_GPL(kvm_host);
104
6e37ec88
SC
105#define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
106
0f65dd70 107#define emul_to_vcpu(ctxt) \
c9b8b07c 108 ((struct kvm_vcpu *)(ctxt)->vcpu)
0f65dd70 109
50a37eb4
JR
110/* EFER defaults:
111 * - enable syscall per default because its emulated by KVM
112 * - enable LME and LMA per default on 64 bit KVM
113 */
114#ifdef CONFIG_X86_64
1260edbe
LJ
115static
116u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
50a37eb4 117#else
1260edbe 118static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
50a37eb4 119#endif
313a3dc7 120
0dbb1123
AK
121#define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
122
ba7bb663
DD
123#define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
124
c519265f
RK
125#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
126 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
37131313 127
cb142eb7 128static void update_cr8_intercept(struct kvm_vcpu *vcpu);
7460fb4a 129static void process_nmi(struct kvm_vcpu *vcpu);
6addfc42 130static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
01643c51
KH
131static void store_regs(struct kvm_vcpu *vcpu);
132static int sync_regs(struct kvm_vcpu *vcpu);
d2f7d498 133static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
674eea0f 134
6dba9403
ML
135static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
137
3af4a9e6 138static DEFINE_MUTEX(vendor_module_lock);
afaf0b2f 139struct kvm_x86_ops kvm_x86_ops __read_mostly;
97896d04 140
9af5471b
JB
141#define KVM_X86_OP(func) \
142 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
143 *(((struct kvm_x86_ops *)0)->func));
e4fc23ba 144#define KVM_X86_OP_OPTIONAL KVM_X86_OP
5be2226f 145#define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
9af5471b
JB
146#include <asm/kvm-x86-ops.h>
147EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
148EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
9af5471b 149
893590c7 150static bool __read_mostly ignore_msrs = 0;
26951ec8 151module_param(ignore_msrs, bool, 0644);
ed85c068 152
d855066f 153bool __read_mostly report_ignored_msrs = true;
26951ec8 154module_param(report_ignored_msrs, bool, 0644);
d855066f 155EXPORT_SYMBOL_GPL(report_ignored_msrs);
fab0aa3b 156
4c27625b 157unsigned int min_timer_period_us = 200;
26951ec8 158module_param(min_timer_period_us, uint, 0644);
9ed96e87 159
630994b3 160static bool __read_mostly kvmclock_periodic_sync = true;
26951ec8 161module_param(kvmclock_periodic_sync, bool, 0444);
630994b3 162
cc578287 163/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
893590c7 164static u32 __read_mostly tsc_tolerance_ppm = 250;
26951ec8 165module_param(tsc_tolerance_ppm, uint, 0644);
cc578287 166
52004014 167static bool __read_mostly vector_hashing = true;
26951ec8 168module_param(vector_hashing, bool, 0444);
52004014 169
c4ae60e4 170bool __read_mostly enable_vmware_backdoor = false;
26951ec8 171module_param(enable_vmware_backdoor, bool, 0444);
c4ae60e4
LA
172EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
173
d500e1ed
SC
174/*
175 * Flags to manipulate forced emulation behavior (any non-zero value will
176 * enable forced emulation).
177 */
178#define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
179static int __read_mostly force_emulation_prefix;
40aaa5b6 180module_param(force_emulation_prefix, int, 0644);
6c86eedc 181
0c5f81da 182int __read_mostly pi_inject_timer = -1;
26951ec8 183module_param(pi_inject_timer, bint, 0644);
0c5f81da 184
4732f244
LX
185/* Enable/disable PMU virtualization */
186bool __read_mostly enable_pmu = true;
187EXPORT_SYMBOL_GPL(enable_pmu);
188module_param(enable_pmu, bool, 0444);
189
cb00a70b 190bool __read_mostly eager_page_split = true;
a3fe5dbd
DM
191module_param(eager_page_split, bool, 0644);
192
6f0f2d5e 193/* Enable/disable SMT_RSB bug mitigation */
944a8dad 194static bool __read_mostly mitigate_smt_rsb;
6f0f2d5e
TL
195module_param(mitigate_smt_rsb, bool, 0444);
196
7e34fbd0
SC
197/*
198 * Restoring the host value for MSRs that are only consumed when running in
199 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
200 * returns to userspace, i.e. the kernel can run with the guest's value.
201 */
202#define KVM_MAX_NR_USER_RETURN_MSRS 16
18863bdd 203
7e34fbd0 204struct kvm_user_return_msrs {
18863bdd
AK
205 struct user_return_notifier urn;
206 bool registered;
7e34fbd0 207 struct kvm_user_return_msr_values {
2bf78fa7
SY
208 u64 host;
209 u64 curr;
7e34fbd0 210 } values[KVM_MAX_NR_USER_RETURN_MSRS];
18863bdd
AK
211};
212
9cc39a5a
SC
213u32 __read_mostly kvm_nr_uret_msrs;
214EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
215static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
7e34fbd0 216static struct kvm_user_return_msrs __percpu *user_return_msrs;
18863bdd 217
cfc48181
SC
218#define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
219 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
220 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
86aff7a4 221 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
cfc48181 222
b96e6506 223bool __read_mostly allow_smaller_maxphyaddr = 0;
3edd6839
MG
224EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
225
fdf513e3
VK
226bool __read_mostly enable_apicv = true;
227EXPORT_SYMBOL_GPL(enable_apicv);
228
459074cf
SC
229bool __read_mostly enable_device_posted_irqs = true;
230EXPORT_SYMBOL_GPL(enable_device_posted_irqs);
231
fcfe1bae
JZ
232const 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),
71f51d2c
MZ
241 STATS_DESC_ICOUNTER(VM, pages_4k),
242 STATS_DESC_ICOUNTER(VM, pages_2m),
243 STATS_DESC_ICOUNTER(VM, pages_1g),
fcfe1bae 244 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
ec1cf69c 245 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
bc9e9e67 246 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
fcfe1bae 247};
fcfe1bae
JZ
248
249const 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
ce55c049
JZ
258const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
259 KVM_GENERIC_VCPU_STATS(),
1075d41e 260 STATS_DESC_COUNTER(VCPU, pf_taken),
ce55c049 261 STATS_DESC_COUNTER(VCPU, pf_fixed),
1075d41e
SC
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),
ce55c049
JZ
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),
6cd88243
PB
290 STATS_DESC_COUNTER(VCPU, preemption_reported),
291 STATS_DESC_COUNTER(VCPU, preemption_other),
63f4b210 292 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
2f4073e0 293 STATS_DESC_COUNTER(VCPU, notify_window_exits),
ce55c049 294};
ce55c049
JZ
295
296const 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
c9b8b07c
SC
305static struct kmem_cache *x86_emulator_cache;
306
6abe9c13 307/*
3adef903
SC
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.
6abe9c13 316 */
3adef903
SC
317
318static 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
338static 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
369static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
370 ARRAY_SIZE(msrs_to_save_pmu)];
371static unsigned num_msrs_to_save;
372
373static 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
441static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
442static 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 */
449static 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,
bc2ca368 454 MSR_PLATFORM_INFO,
3adef903
SC
455};
456
457static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
458 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
459static 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 */
465static bool kvm_is_immutable_feature_msr(u32 msr)
6abe9c13 466{
3adef903 467 int i;
6abe9c13 468
3adef903 469 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
cc4cb017 470 return true;
3adef903
SC
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
44dd0f57 480static bool kvm_is_advertised_msr(u32 msr_index)
3adef903
SC
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
44dd0f57
SC
489 for (i = 0; i < num_emulated_msrs; i++) {
490 if (emulated_msrs[i] == msr_index)
491 return true;
492 }
493
3adef903
SC
494 return false;
495}
496
1cec2034
SC
497typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
498 bool host_initiated);
499
500static __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)
6abe9c13 504{
1cec2034
SC
505 const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
506 int ret;
6abe9c13 507
1cec2034
SC
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
64a5d7a1
SC
521 /*
522 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
44dd0f57 523 * advertises to userspace, even if an MSR isn't fully supported.
64a5d7a1
SC
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 */
44dd0f57 527 if (host_initiated && !*data && kvm_is_advertised_msr(msr))
64a5d7a1
SC
528 return 0;
529
1cec2034 530 if (!ignore_msrs) {
d383b314 531 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
1cec2034
SC
532 op, msr, *data);
533 return ret;
6abe9c13 534 }
1cec2034
SC
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;
6abe9c13
PX
540}
541
c9b8b07c
SC
542static struct kmem_cache *kvm_alloc_emulator_cache(void)
543{
06add254
SC
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,
c9b8b07c 548 __alignof__(struct x86_emulate_ctxt),
06add254
SC
549 SLAB_ACCOUNT, useroffset,
550 size - useroffset, NULL);
c9b8b07c
SC
551}
552
b6785def 553static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
d6aa1000 554
af585b92
GN
555static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
556{
557 int i;
dd03bcaa 558 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
af585b92
GN
559 vcpu->arch.apf.gfns[i] = ~0;
560}
561
18863bdd
AK
562static void kvm_on_user_return(struct user_return_notifier *urn)
563{
564 unsigned slot;
7e34fbd0
SC
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;
1650b4eb
IA
568 unsigned long flags;
569
570 /*
571 * Disabling irqs at this point since the following code could be
071f24ad 572 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
1650b4eb
IA
573 */
574 local_irq_save(flags);
7e34fbd0
SC
575 if (msrs->registered) {
576 msrs->registered = false;
1650b4eb
IA
577 user_return_notifier_unregister(urn);
578 }
579 local_irq_restore(flags);
9cc39a5a 580 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
7e34fbd0 581 values = &msrs->values[slot];
2bf78fa7 582 if (values->host != values->curr) {
78255eb2 583 wrmsrq(kvm_uret_msrs_list[slot], values->host);
2bf78fa7 584 values->curr = values->host;
18863bdd
AK
585 }
586 }
18863bdd
AK
587}
588
e5fda4bb 589static int kvm_probe_user_return_msr(u32 msr)
5104d7ff
SC
590{
591 u64 val;
592 int ret;
593
594 preempt_disable();
6fe22aba 595 ret = rdmsrq_safe(msr, &val);
5104d7ff
SC
596 if (ret)
597 goto out;
6fa17efe 598 ret = wrmsrq_safe(msr, val);
5104d7ff
SC
599out:
600 preempt_enable();
601 return ret;
602}
5104d7ff 603
e5fda4bb 604int kvm_add_user_return_msr(u32 msr)
2bf78fa7 605{
e5fda4bb
SC
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++;
18863bdd 613}
e5fda4bb 614EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
18863bdd 615
8ea8b8d6
SC
616int kvm_find_user_return_msr(u32 msr)
617{
618 int i;
619
9cc39a5a
SC
620 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
621 if (kvm_uret_msrs_list[i] == msr)
8ea8b8d6
SC
622 return i;
623 }
624 return -1;
625}
626EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
627
7e34fbd0 628static void kvm_user_return_msr_cpu_online(void)
18863bdd 629{
e0183a42 630 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
05c19c2f
SC
631 u64 value;
632 int i;
18863bdd 633
9cc39a5a 634 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
6fe22aba 635 rdmsrq_safe(kvm_uret_msrs_list[i], &value);
7e34fbd0
SC
636 msrs->values[i].host = value;
637 msrs->values[i].curr = value;
05c19c2f 638 }
18863bdd
AK
639}
640
d3a6b6cf
CG
641static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
642{
643 if (!msrs->registered) {
644 msrs->urn.on_user_return = kvm_on_user_return;
645 user_return_notifier_register(&msrs->urn);
646 msrs->registered = true;
647 }
648}
649
7e34fbd0 650int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
18863bdd 651{
15e1c3d6 652 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
8b3c3104 653 int err;
18863bdd 654
7e34fbd0
SC
655 value = (value & mask) | (msrs->values[slot].host & ~mask);
656 if (value == msrs->values[slot].curr)
8b3c3104 657 return 0;
6fa17efe 658 err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
8b3c3104
AH
659 if (err)
660 return 1;
661
7e34fbd0 662 msrs->values[slot].curr = value;
d3a6b6cf 663 kvm_user_return_register_notifier(msrs);
8b3c3104 664 return 0;
18863bdd 665}
7e34fbd0 666EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
18863bdd 667
d3a6b6cf
CG
668void kvm_user_return_msr_update_cache(unsigned int slot, u64 value)
669{
670 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
671
672 msrs->values[slot].curr = value;
673 kvm_user_return_register_notifier(msrs);
674}
675EXPORT_SYMBOL_GPL(kvm_user_return_msr_update_cache);
676
13a34e06 677static void drop_user_return_notifiers(void)
3548bab5 678{
15e1c3d6 679 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
3548bab5 680
7e34fbd0
SC
681 if (msrs->registered)
682 kvm_on_user_return(&msrs->urn);
3548bab5
AK
683}
684
ad0577c3
SC
685/*
686 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
687 *
688 * Hardware virtualization extension instructions may fault if a reboot turns
689 * off virtualization while processes are running. Usually after catching the
690 * fault we just panic; during reboot instead the instruction is ignored.
691 */
692noinstr void kvm_spurious_fault(void)
e3ba45b8
GL
693{
694 /* Fault while not rebooting. We want the trace. */
b4fdcf60 695 BUG_ON(!kvm_rebooting);
e3ba45b8
GL
696}
697EXPORT_SYMBOL_GPL(kvm_spurious_fault);
698
3fd28fce
ED
699#define EXCPT_BENIGN 0
700#define EXCPT_CONTRIBUTORY 1
701#define EXCPT_PF 2
702
703static int exception_class(int vector)
704{
705 switch (vector) {
706 case PF_VECTOR:
707 return EXCPT_PF;
708 case DE_VECTOR:
709 case TS_VECTOR:
710 case NP_VECTOR:
711 case SS_VECTOR:
712 case GP_VECTOR:
713 return EXCPT_CONTRIBUTORY;
714 default:
715 break;
716 }
717 return EXCPT_BENIGN;
718}
719
d6e8c854
NA
720#define EXCPT_FAULT 0
721#define EXCPT_TRAP 1
722#define EXCPT_ABORT 2
723#define EXCPT_INTERRUPT 3
5623f751 724#define EXCPT_DB 4
d6e8c854
NA
725
726static int exception_type(int vector)
727{
728 unsigned int mask;
729
730 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
731 return EXCPT_INTERRUPT;
732
733 mask = 1 << vector;
734
5623f751
SC
735 /*
736 * #DBs can be trap-like or fault-like, the caller must check other CPU
737 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
738 */
739 if (mask & (1 << DB_VECTOR))
740 return EXCPT_DB;
741
742 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
d6e8c854
NA
743 return EXCPT_TRAP;
744
745 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
746 return EXCPT_ABORT;
747
748 /* Reserved exceptions will result in fault */
749 return EXCPT_FAULT;
750}
751
d4963e31
SC
752void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
753 struct kvm_queued_exception *ex)
da998b46 754{
d4963e31 755 if (!ex->has_payload)
da998b46
JM
756 return;
757
d4963e31 758 switch (ex->vector) {
f10c729f
JM
759 case DB_VECTOR:
760 /*
761 * "Certain debug exceptions may clear bit 0-3. The
762 * remaining contents of the DR6 register are never
763 * cleared by the processor".
764 */
765 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
766 /*
9a3ecd5e
CQ
767 * In order to reflect the #DB exception payload in guest
768 * dr6, three components need to be considered: active low
769 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
770 * DR6_BS and DR6_BT)
771 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
772 * In the target guest dr6:
773 * FIXED_1 bits should always be set.
774 * Active low bits should be cleared if 1-setting in payload.
775 * Active high bits should be set if 1-setting in payload.
776 *
777 * Note, the payload is compatible with the pending debug
778 * exceptions/exit qualification under VMX, that active_low bits
779 * are active high in payload.
780 * So they need to be flipped for DR6.
f10c729f 781 */
9a3ecd5e 782 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
d4963e31
SC
783 vcpu->arch.dr6 |= ex->payload;
784 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
307f1cfa
OU
785
786 /*
787 * The #DB payload is defined as compatible with the 'pending
788 * debug exceptions' field under VMX, not DR6. While bit 12 is
789 * defined in the 'pending debug exceptions' field (enabled
790 * breakpoint), it is reserved and must be zero in DR6.
791 */
792 vcpu->arch.dr6 &= ~BIT(12);
f10c729f 793 break;
da998b46 794 case PF_VECTOR:
d4963e31 795 vcpu->arch.cr2 = ex->payload;
da998b46
JM
796 break;
797 }
798
d4963e31
SC
799 ex->has_payload = false;
800 ex->payload = 0;
da998b46
JM
801}
802EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
803
7709aba8
SC
804static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
805 bool has_error_code, u32 error_code,
806 bool has_payload, unsigned long payload)
807{
808 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
809
810 ex->vector = vector;
811 ex->injected = false;
812 ex->pending = true;
813 ex->has_error_code = has_error_code;
814 ex->error_code = error_code;
815 ex->has_payload = has_payload;
816 ex->payload = payload;
817}
818
b50cb2b1
SC
819static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
820 bool has_error, u32 error_code,
821 bool has_payload, unsigned long payload)
3fd28fce
ED
822{
823 u32 prev_nr;
824 int class1, class2;
825
3842d135
AK
826 kvm_make_request(KVM_REQ_EVENT, vcpu);
827
7709aba8 828 /*
b50cb2b1
SC
829 * If the exception is destined for L2, morph it to a VM-Exit if L1
830 * wants to intercept the exception.
7709aba8 831 */
b50cb2b1 832 if (is_guest_mode(vcpu) &&
7709aba8
SC
833 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
834 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
835 has_payload, payload);
836 return;
837 }
838
664f8e26 839 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
3fd28fce 840 queue:
b50cb2b1
SC
841 vcpu->arch.exception.pending = true;
842 vcpu->arch.exception.injected = false;
843
3fd28fce 844 vcpu->arch.exception.has_error_code = has_error;
d4963e31 845 vcpu->arch.exception.vector = nr;
3fd28fce 846 vcpu->arch.exception.error_code = error_code;
91e86d22
JM
847 vcpu->arch.exception.has_payload = has_payload;
848 vcpu->arch.exception.payload = payload;
a06230b6 849 if (!is_guest_mode(vcpu))
d4963e31
SC
850 kvm_deliver_exception_payload(vcpu,
851 &vcpu->arch.exception);
3fd28fce
ED
852 return;
853 }
854
855 /* to check exception */
d4963e31 856 prev_nr = vcpu->arch.exception.vector;
3fd28fce
ED
857 if (prev_nr == DF_VECTOR) {
858 /* triple fault -> shutdown */
a8eeb04a 859 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3fd28fce
ED
860 return;
861 }
862 class1 = exception_class(prev_nr);
863 class2 = exception_class(nr);
81601495
SC
864 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
865 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
664f8e26 866 /*
81601495
SC
867 * Synthesize #DF. Clear the previously injected or pending
868 * exception so as not to incorrectly trigger shutdown.
664f8e26 869 */
664f8e26 870 vcpu->arch.exception.injected = false;
81601495
SC
871 vcpu->arch.exception.pending = false;
872
873 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
874 } else {
3fd28fce
ED
875 /* replace previous exception with a new one in a hope
876 that instruction re-execution will regenerate lost
877 exception */
878 goto queue;
81601495 879 }
3fd28fce
ED
880}
881
298101da
AK
882void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
883{
b50cb2b1 884 kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
298101da
AK
885}
886EXPORT_SYMBOL_GPL(kvm_queue_exception);
887
ce7ddec4 888
4d5523cf
PB
889void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
890 unsigned long payload)
f10c729f 891{
b50cb2b1 892 kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
f10c729f 893}
4d5523cf 894EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
f10c729f 895
da998b46
JM
896static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
897 u32 error_code, unsigned long payload)
898{
b50cb2b1 899 kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
da998b46
JM
900}
901
b50cb2b1
SC
902void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
903 bool has_error_code, u32 error_code)
904{
905
906 /*
907 * On VM-Entry, an exception can be pending if and only if event
908 * injection was blocked by nested_run_pending. In that case, however,
909 * vcpu_enter_guest() requests an immediate exit, and the guest
910 * shouldn't proceed far enough to need reinjection.
911 */
912 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
913
914 /*
915 * Do not check for interception when injecting an event for L2, as the
916 * exception was checked for intercept when it was original queued, and
917 * re-checking is incorrect if _L1_ injected the exception, in which
918 * case it's exempt from interception.
919 */
920 kvm_make_request(KVM_REQ_EVENT, vcpu);
921
922 vcpu->arch.exception.injected = true;
923 vcpu->arch.exception.has_error_code = has_error_code;
924 vcpu->arch.exception.vector = nr;
925 vcpu->arch.exception.error_code = error_code;
926 vcpu->arch.exception.has_payload = false;
927 vcpu->arch.exception.payload = 0;
928}
929EXPORT_SYMBOL_GPL(kvm_requeue_exception);
930
6affcbed 931int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
c3c91fee 932{
db8fcefa
AP
933 if (err)
934 kvm_inject_gp(vcpu, 0);
935 else
6affcbed
KH
936 return kvm_skip_emulated_instruction(vcpu);
937
938 return 1;
db8fcefa
AP
939}
940EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
8df25a32 941
d2f7d498
HW
942static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
943{
944 if (err) {
945 kvm_inject_gp(vcpu, 0);
946 return 1;
947 }
948
949 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
950 EMULTYPE_COMPLETE_USER_EXIT);
951}
952
6389ee94 953void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
c3c91fee
AK
954{
955 ++vcpu->stat.pf_guest;
7709aba8
SC
956
957 /*
958 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
959 * whether or not L1 wants to intercept "regular" #PF.
960 */
961 if (is_guest_mode(vcpu) && fault->async_page_fault)
962 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
963 true, fault->error_code,
964 true, fault->address);
965 else
da998b46
JM
966 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
967 fault->address);
c3c91fee
AK
968}
969
7709aba8 970void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
53b3d8e9 971 struct x86_exception *fault)
d4f8cf66 972{
0cd665bd 973 struct kvm_mmu *fault_mmu;
53b3d8e9
SC
974 WARN_ON_ONCE(fault->vector != PF_VECTOR);
975
0cd665bd
PB
976 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
977 vcpu->arch.walk_mmu;
ef54bcfe 978
ee1fa209
JS
979 /*
980 * Invalidate the TLB entry for the faulting address, if it exists,
981 * else the access will fault indefinitely (and to emulate hardware).
982 */
983 if ((fault->error_code & PFERR_PRESENT_MASK) &&
984 !(fault->error_code & PFERR_RSVD_MASK))
753b43c9 985 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
cd42853e 986 KVM_MMU_ROOT_CURRENT);
ee1fa209
JS
987
988 fault_mmu->inject_page_fault(vcpu, fault);
d4f8cf66 989}
53b3d8e9 990EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
d4f8cf66 991
3419ffc8
SY
992void kvm_inject_nmi(struct kvm_vcpu *vcpu)
993{
7460fb4a
AK
994 atomic_inc(&vcpu->arch.nmi_queued);
995 kvm_make_request(KVM_REQ_NMI, vcpu);
3419ffc8 996}
3419ffc8 997
298101da
AK
998void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
999{
b50cb2b1 1000 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
298101da
AK
1001}
1002EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
1003
0a79b009
AK
1004/*
1005 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
1006 * a #GP and return false.
1007 */
1008bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
298101da 1009{
89604647 1010 if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
0a79b009
AK
1011 return true;
1012 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1013 return false;
298101da
AK
1014}
1015
16f8a6f9
NA
1016bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1017{
607475cf 1018 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
16f8a6f9
NA
1019 return true;
1020
1021 kvm_queue_exception(vcpu, UD_VECTOR);
1022 return false;
1023}
1024EXPORT_SYMBOL_GPL(kvm_require_dr);
1025
16cfacc8
SC
1026static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1027{
5b7f575c 1028 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
16cfacc8
SC
1029}
1030
a03490ed 1031/*
16cfacc8 1032 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
a03490ed 1033 */
2df4a5eb 1034int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 1035{
2df4a5eb 1036 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
a03490ed 1037 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
15cabbc2 1038 gpa_t real_gpa;
a03490ed
CO
1039 int i;
1040 int ret;
ff03a073 1041 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
a03490ed 1042
15cabbc2
SC
1043 /*
1044 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1045 * to an L1 GPA.
1046 */
c59a0f57
LJ
1047 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1048 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
6e1d2a3f 1049 if (real_gpa == INVALID_GPA)
15cabbc2
SC
1050 return 0;
1051
94c641ba 1052 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
15cabbc2 1053 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
94c641ba 1054 cr3 & GENMASK(11, 5), sizeof(pdpte));
15cabbc2
SC
1055 if (ret < 0)
1056 return 0;
1057
a03490ed 1058 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
812f30b2 1059 if ((pdpte[i] & PT_PRESENT_MASK) &&
16cfacc8 1060 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
15cabbc2 1061 return 0;
a03490ed
CO
1062 }
1063 }
a03490ed 1064
6b123c3a
LJ
1065 /*
1066 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1067 * Shadow page roots need to be reconstructed instead.
1068 */
1069 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
0c1c92f1 1070 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
6b123c3a 1071
46cbc040
PB
1072 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1073 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1074 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
158a48ec
ML
1075 vcpu->arch.pdptrs_from_userspace = false;
1076
15cabbc2 1077 return 1;
a03490ed 1078}
cc4b6871 1079EXPORT_SYMBOL_GPL(load_pdptrs);
a03490ed 1080
26a0652c
SC
1081static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1082{
1083#ifdef CONFIG_X86_64
1084 if (cr0 & 0xffffffff00000000UL)
1085 return false;
1086#endif
1087
1088 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1089 return false;
1090
1091 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1092 return false;
1093
89604647 1094 return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
26a0652c
SC
1095}
1096
f27ad38a
TL
1097void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1098{
01b31714
MK
1099 /*
1100 * CR0.WP is incorporated into the MMU role, but only for non-nested,
e40bcf9f
MK
1101 * indirect shadow MMUs. If paging is disabled, no updates are needed
1102 * as there are no permission bits to emulate. If TDP is enabled, the
1103 * MMU's metadata needs to be updated, e.g. so that emulating guest
1104 * translations does the right thing, but there's no need to unload the
1105 * root as CR0.WP doesn't affect SPTEs.
01b31714 1106 */
e40bcf9f
MK
1107 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1108 if (!(cr0 & X86_CR0_PG))
1109 return;
1110
1111 if (tdp_enabled) {
1112 kvm_init_mmu(vcpu);
1113 return;
1114 }
01b31714
MK
1115 }
1116
f27ad38a
TL
1117 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1118 kvm_clear_async_pf_completion_queue(vcpu);
1119 kvm_async_pf_hash_reset(vcpu);
b5f61c03
PB
1120
1121 /*
1122 * Clearing CR0.PG is defined to flush the TLB from the guest's
1123 * perspective.
1124 */
1125 if (!(cr0 & X86_CR0_PG))
1126 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
f27ad38a
TL
1127 }
1128
20f632bd 1129 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
f27ad38a 1130 kvm_mmu_reset_context(vcpu);
f27ad38a
TL
1131}
1132EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
1133
49a9b07e 1134int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
a03490ed 1135{
aad82703 1136 unsigned long old_cr0 = kvm_read_cr0(vcpu);
aad82703 1137
26a0652c 1138 if (!kvm_is_valid_cr0(vcpu, cr0))
0f12244f 1139 return 1;
a03490ed 1140
26a0652c 1141 cr0 |= X86_CR0_ET;
a03490ed 1142
26a0652c
SC
1143 /* Write to CR0 reserved bits are ignored, even on Intel. */
1144 cr0 &= ~CR0_RESERVED_BITS;
a03490ed 1145
a03490ed 1146#ifdef CONFIG_X86_64
05487215
SC
1147 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1148 (cr0 & X86_CR0_PG)) {
1149 int cs_db, cs_l;
1150
1151 if (!is_pae(vcpu))
1152 return 1;
89604647 1153 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
05487215 1154 if (cs_l)
0f12244f 1155 return 1;
a03490ed 1156 }
05487215
SC
1157#endif
1158 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
e63f315d 1159 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
2df4a5eb 1160 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
05487215 1161 return 1;
a03490ed 1162
777ab82d 1163 if (!(cr0 & X86_CR0_PG) &&
607475cf 1164 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
ad756a16
MJ
1165 return 1;
1166
89604647 1167 kvm_x86_call(set_cr0)(vcpu, cr0);
a03490ed 1168
f27ad38a 1169 kvm_post_set_cr0(vcpu, old_cr0, cr0);
b18d5431 1170
0f12244f
GN
1171 return 0;
1172}
2d3ad1f4 1173EXPORT_SYMBOL_GPL(kvm_set_cr0);
a03490ed 1174
2d3ad1f4 1175void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
a03490ed 1176{
49a9b07e 1177 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
a03490ed 1178}
2d3ad1f4 1179EXPORT_SYMBOL_GPL(kvm_lmsw);
a03490ed 1180
139a12cf 1181void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 1182{
16809ecd
TL
1183 if (vcpu->arch.guest_state_protected)
1184 return;
1185
607475cf 1186 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
139a12cf 1187
7974c064 1188 if (vcpu->arch.xcr0 != kvm_host.xcr0)
139a12cf
AL
1189 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1190
2c5e168e 1191 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
7974c064 1192 vcpu->arch.ia32_xss != kvm_host.xss)
78255eb2 1193 wrmsrq(MSR_IA32_XSS, vcpu->arch.ia32_xss);
139a12cf 1194 }
37486135 1195
056b9919 1196 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
945024d7
JK
1197 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1198 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
607475cf 1199 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
4c20cd4c 1200 wrpkru(vcpu->arch.pkru);
42bdf991 1201}
139a12cf 1202EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
42bdf991 1203
139a12cf 1204void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 1205{
16809ecd
TL
1206 if (vcpu->arch.guest_state_protected)
1207 return;
1208
056b9919 1209 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
945024d7 1210 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
607475cf 1211 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
37486135
BM
1212 vcpu->arch.pkru = rdpkru();
1213 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
4c20cd4c 1214 wrpkru(vcpu->arch.host_pkru);
37486135
BM
1215 }
1216
607475cf 1217 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
139a12cf 1218
7974c064
SC
1219 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1220 xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
139a12cf 1221
2c5e168e 1222 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
7974c064 1223 vcpu->arch.ia32_xss != kvm_host.xss)
78255eb2 1224 wrmsrq(MSR_IA32_XSS, kvm_host.xss);
139a12cf
AL
1225 }
1226
42bdf991 1227}
139a12cf 1228EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
42bdf991 1229
ba1f77c5 1230#ifdef CONFIG_X86_64
988896bb
LB
1231static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1232{
ee519b3a 1233 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
988896bb 1234}
ba1f77c5 1235#endif
988896bb 1236
69b0049a 1237static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
2acf923e 1238{
56c103ec
LJ
1239 u64 xcr0 = xcr;
1240 u64 old_xcr0 = vcpu->arch.xcr0;
46c34cb0 1241 u64 valid_bits;
2acf923e
DC
1242
1243 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1244 if (index != XCR_XFEATURE_ENABLED_MASK)
1245 return 1;
d91cab78 1246 if (!(xcr0 & XFEATURE_MASK_FP))
2acf923e 1247 return 1;
d91cab78 1248 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
2acf923e 1249 return 1;
46c34cb0
PB
1250
1251 /*
1252 * Do not allow the guest to set bits that we do not support
1253 * saving. However, xcr0 bit 0 is always set, even if the
e8f65b9b 1254 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
46c34cb0 1255 */
ee519b3a 1256 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
46c34cb0 1257 if (xcr0 & ~valid_bits)
2acf923e 1258 return 1;
46c34cb0 1259
d91cab78
DH
1260 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1261 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
390bd528
LJ
1262 return 1;
1263
d91cab78
DH
1264 if (xcr0 & XFEATURE_MASK_AVX512) {
1265 if (!(xcr0 & XFEATURE_MASK_YMM))
612263b3 1266 return 1;
d91cab78 1267 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
612263b3
CP
1268 return 1;
1269 }
86aff7a4
JL
1270
1271 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1272 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1273 return 1;
1274
2acf923e 1275 vcpu->arch.xcr0 = xcr0;
56c103ec 1276
d91cab78 1277 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
93da6af3 1278 vcpu->arch.cpuid_dynamic_bits_dirty = true;
2acf923e
DC
1279 return 0;
1280}
1281
92f9895c 1282int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
2acf923e 1283{
50b2d49b 1284 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
89604647 1285 if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
92f9895c
SC
1286 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1287 kvm_inject_gp(vcpu, 0);
1288 return 1;
1289 }
bbefd4fc 1290
92f9895c 1291 return kvm_skip_emulated_instruction(vcpu);
2acf923e 1292}
92f9895c 1293EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
2acf923e 1294
c33f6f22
SC
1295static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1296{
1297 return __kvm_is_valid_cr4(vcpu, cr4) &&
89604647 1298 kvm_x86_call(is_valid_cr4)(vcpu, cr4);
3ca94192
WL
1299}
1300
5b51cb13
TL
1301void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1302{
b5f61c03
PB
1303 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1304 kvm_mmu_reset_context(vcpu);
1305
509bfe3d 1306 /*
509bfe3d
LJ
1307 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1308 * according to the SDM; however, stale prev_roots could be reused
1309 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
b5f61c03
PB
1310 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1311 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1312 * so fall through.
509bfe3d 1313 */
b5f61c03
PB
1314 if (!tdp_enabled &&
1315 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
f6d0a252 1316 kvm_mmu_unload(vcpu);
b5f61c03
PB
1317
1318 /*
1319 * The TLB has to be flushed for all PCIDs if any of the following
1320 * (architecturally required) changes happen:
1321 * - CR4.PCIDE is changed from 1 to 0
1322 * - CR4.PGE is toggled
509bfe3d 1323 *
b5f61c03 1324 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
509bfe3d 1325 */
b5f61c03
PB
1326 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1327 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
55261738 1328 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
b5f61c03
PB
1329
1330 /*
1331 * The TLB has to be flushed for the current PCID if any of the
1332 * following (architecturally required) changes happen:
1333 * - CR4.SMEP is changed from 0 to 1
1334 * - CR4.PAE is toggled
1335 */
1336 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1337 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1338 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1339
3ca94192 1340}
5b51cb13 1341EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
3ca94192
WL
1342
1343int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1344{
1345 unsigned long old_cr4 = kvm_read_cr4(vcpu);
3ca94192 1346
ee69c92b 1347 if (!kvm_is_valid_cr4(vcpu, cr4))
ae3e61e1
PB
1348 return 1;
1349
a03490ed 1350 if (is_long_mode(vcpu)) {
0f12244f
GN
1351 if (!(cr4 & X86_CR4_PAE))
1352 return 1;
d74fcfc1
SC
1353 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1354 return 1;
a2edf57f 1355 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
a37ebdce 1356 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
2df4a5eb 1357 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
0f12244f
GN
1358 return 1;
1359
ad756a16 1360 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
ad756a16
MJ
1361 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1362 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1363 return 1;
1364 }
1365
89604647 1366 kvm_x86_call(set_cr4)(vcpu, cr4);
a03490ed 1367
5b51cb13 1368 kvm_post_set_cr4(vcpu, old_cr4, cr4);
2acf923e 1369
0f12244f
GN
1370 return 0;
1371}
2d3ad1f4 1372EXPORT_SYMBOL_GPL(kvm_set_cr4);
a03490ed 1373
21823fbd
SC
1374static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1375{
1376 struct kvm_mmu *mmu = vcpu->arch.mmu;
1377 unsigned long roots_to_free = 0;
1378 int i;
1379
e45e9e39
LJ
1380 /*
1381 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1382 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1383 * also via the emulator. KVM's TDP page tables are not in the scope of
1384 * the invalidation, but the guest's TLB entries need to be flushed as
1385 * the CPU may have cached entries in its TLB for the target PCID.
1386 */
1387 if (unlikely(tdp_enabled)) {
1388 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1389 return;
1390 }
1391
21823fbd
SC
1392 /*
1393 * If neither the current CR3 nor any of the prev_roots use the given
1394 * PCID, then nothing needs to be done here because a resync will
1395 * happen anyway before switching to any other CR3.
1396 */
1397 if (kvm_get_active_pcid(vcpu) == pcid) {
e62f1aa8 1398 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
21823fbd
SC
1399 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1400 }
1401
509bfe3d
LJ
1402 /*
1403 * If PCID is disabled, there is no need to free prev_roots even if the
1404 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1405 * with PCIDE=0.
1406 */
607475cf 1407 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
509bfe3d
LJ
1408 return;
1409
21823fbd
SC
1410 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1411 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1412 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1413
0c1c92f1 1414 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
21823fbd
SC
1415}
1416
2390218b 1417int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 1418{
ade61e28 1419 bool skip_tlb_flush = false;
21823fbd 1420 unsigned long pcid = 0;
ac146235 1421#ifdef CONFIG_X86_64
607475cf 1422 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
208320ba
JS
1423 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1424 cr3 &= ~X86_CR3_PCID_NOFLUSH;
21823fbd 1425 pcid = cr3 & X86_CR3_PCID_MASK;
ade61e28 1426 }
ac146235 1427#endif
9d88fca7 1428
c7313155 1429 /* PDPTRs are always reloaded for PAE paging. */
21823fbd
SC
1430 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1431 goto handle_tlb_flush;
d835dfec 1432
886bbcc7
SC
1433 /*
1434 * Do not condition the GPA check on long mode, this helper is used to
1435 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1436 * the current vCPU mode is accurate.
1437 */
2c49db45 1438 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
d1cd3ce9 1439 return 1;
886bbcc7 1440
2df4a5eb 1441 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
346874c9 1442 return 1;
a03490ed 1443
21823fbd 1444 if (cr3 != kvm_read_cr3(vcpu))
b5129100 1445 kvm_mmu_new_pgd(vcpu, cr3);
21823fbd 1446
0f12244f 1447 vcpu->arch.cr3 = cr3;
3883bc9d 1448 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
405329fc 1449 /* Do not call post_set_cr3, we do not get here for confidential guests. */
7c390d35 1450
21823fbd
SC
1451handle_tlb_flush:
1452 /*
1453 * A load of CR3 that flushes the TLB flushes only the current PCID,
1454 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1455 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1456 * and it's impossible to use a non-zero PCID when PCID is disabled,
1457 * i.e. only PCID=0 can be relevant.
1458 */
1459 if (!skip_tlb_flush)
1460 kvm_invalidate_pcid(vcpu, pcid);
1461
0f12244f
GN
1462 return 0;
1463}
2d3ad1f4 1464EXPORT_SYMBOL_GPL(kvm_set_cr3);
a03490ed 1465
eea1cff9 1466int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
a03490ed 1467{
0f12244f
GN
1468 if (cr8 & CR8_RESERVED_BITS)
1469 return 1;
35754c98 1470 if (lapic_in_kernel(vcpu))
a03490ed
CO
1471 kvm_lapic_set_tpr(vcpu, cr8);
1472 else
ad312c7c 1473 vcpu->arch.cr8 = cr8;
0f12244f
GN
1474 return 0;
1475}
2d3ad1f4 1476EXPORT_SYMBOL_GPL(kvm_set_cr8);
a03490ed 1477
2d3ad1f4 1478unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
a03490ed 1479{
35754c98 1480 if (lapic_in_kernel(vcpu))
a03490ed
CO
1481 return kvm_lapic_get_cr8(vcpu);
1482 else
ad312c7c 1483 return vcpu->arch.cr8;
a03490ed 1484}
2d3ad1f4 1485EXPORT_SYMBOL_GPL(kvm_get_cr8);
a03490ed 1486
ae561ede
NA
1487static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1488{
1489 int i;
1490
1491 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1492 for (i = 0; i < KVM_NR_DB_REGS; i++)
1493 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
ae561ede
NA
1494 }
1495}
1496
7c86663b 1497void kvm_update_dr7(struct kvm_vcpu *vcpu)
c8639010
JK
1498{
1499 unsigned long dr7;
1500
1501 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1502 dr7 = vcpu->arch.guest_debug_dr7;
1503 else
1504 dr7 = vcpu->arch.dr7;
89604647 1505 kvm_x86_call(set_dr7)(vcpu, dr7);
360b948d
PB
1506 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1507 if (dr7 & DR7_BP_EN_MASK)
1508 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
c8639010 1509}
7c86663b 1510EXPORT_SYMBOL_GPL(kvm_update_dr7);
c8639010 1511
6f43ed01
NA
1512static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1513{
1514 u64 fixed = DR6_FIXED_1;
1515
8f2a2775 1516 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
6f43ed01 1517 fixed |= DR6_RTM;
e8ea85fb 1518
8f2a2775 1519 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
e8ea85fb 1520 fixed |= DR6_BUS_LOCK;
6f43ed01
NA
1521 return fixed;
1522}
1523
996ff542 1524int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
020df079 1525{
ea740059
MP
1526 size_t size = ARRAY_SIZE(vcpu->arch.db);
1527
020df079
GN
1528 switch (dr) {
1529 case 0 ... 3:
ea740059 1530 vcpu->arch.db[array_index_nospec(dr, size)] = val;
020df079
GN
1531 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1532 vcpu->arch.eff_db[dr] = val;
1533 break;
1534 case 4:
020df079 1535 case 6:
f5f6145e 1536 if (!kvm_dr6_valid(val))
996ff542 1537 return 1; /* #GP */
6f43ed01 1538 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
020df079
GN
1539 break;
1540 case 5:
020df079 1541 default: /* 7 */
b91991bf 1542 if (!kvm_dr7_valid(val))
996ff542 1543 return 1; /* #GP */
020df079 1544 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
c8639010 1545 kvm_update_dr7(vcpu);
020df079
GN
1546 break;
1547 }
1548
1549 return 0;
1550}
1551EXPORT_SYMBOL_GPL(kvm_set_dr);
1552
fc5375dd 1553unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
020df079 1554{
ea740059
MP
1555 size_t size = ARRAY_SIZE(vcpu->arch.db);
1556
020df079
GN
1557 switch (dr) {
1558 case 0 ... 3:
fc5375dd 1559 return vcpu->arch.db[array_index_nospec(dr, size)];
020df079 1560 case 4:
020df079 1561 case 6:
fc5375dd 1562 return vcpu->arch.dr6;
020df079 1563 case 5:
020df079 1564 default: /* 7 */
fc5375dd 1565 return vcpu->arch.dr7;
020df079 1566 }
338dbc97 1567}
020df079
GN
1568EXPORT_SYMBOL_GPL(kvm_get_dr);
1569
c483c454 1570int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
022cd0e8 1571{
de3cd117 1572 u32 ecx = kvm_rcx_read(vcpu);
022cd0e8 1573 u64 data;
022cd0e8 1574
c483c454
SC
1575 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1576 kvm_inject_gp(vcpu, 0);
1577 return 1;
1578 }
1579
de3cd117
SC
1580 kvm_rax_write(vcpu, (u32)data);
1581 kvm_rdx_write(vcpu, data >> 32);
c483c454 1582 return kvm_skip_emulated_instruction(vcpu);
022cd0e8 1583}
c483c454 1584EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
022cd0e8 1585
0204750b
JM
1586/*
1587 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1588 * does not yet virtualize. These include:
1589 * 10 - MISC_PACKAGE_CTRLS
1590 * 11 - ENERGY_FILTERING_CTL
1591 * 12 - DOITM
1592 * 18 - FB_CLEAR_CTRL
1593 * 21 - XAPIC_DISABLE_STATUS
1594 * 23 - OVERCLOCKING_STATUS
1595 */
1596
1597#define KVM_SUPPORTED_ARCH_CAP \
1598 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1599 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1600 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1601 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
2a018012 1602 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
159013a7 1603 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
0204750b 1604
4d22c17c 1605static u64 kvm_get_arch_capabilities(void)
5b76a3cf 1606{
7974c064 1607 u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
5b76a3cf 1608
b8e8c830
PB
1609 /*
1610 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1611 * the nested hypervisor runs with NX huge pages. If it is not,
d9f6e12f 1612 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
b8e8c830
PB
1613 * L1 guests, so it need not worry about its own (L2) guests.
1614 */
1615 data |= ARCH_CAP_PSCHANGE_MC_NO;
1616
5b76a3cf
PB
1617 /*
1618 * If we're doing cache flushes (either "always" or "cond")
1619 * we will do one whenever the guest does a vmlaunch/vmresume.
1620 * If an outer hypervisor is doing the cache flush for us
02f1b0b7 1621 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
5b76a3cf
PB
1622 * capability to the guest too, and if EPT is disabled we're not
1623 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1624 * require a nested hypervisor to do a flush of its own.
1625 */
1626 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1627 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1628
0c54914d
PB
1629 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1630 data |= ARCH_CAP_RDCL_NO;
1631 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1632 data |= ARCH_CAP_SSB_NO;
1633 if (!boot_cpu_has_bug(X86_BUG_MDS))
1634 data |= ARCH_CAP_MDS_NO;
2a018012
PG
1635 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1636 data |= ARCH_CAP_RFDS_NO;
159013a7
PG
1637 if (!boot_cpu_has_bug(X86_BUG_ITS))
1638 data |= ARCH_CAP_ITS_NO;
0c54914d 1639
7131636e
PB
1640 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1641 /*
1642 * If RTM=0 because the kernel has disabled TSX, the host might
1643 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1644 * and therefore knows that there cannot be TAA) but keep
1645 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1646 * and we want to allow migrating those guests to tsx=off hosts.
1647 */
1648 data &= ~ARCH_CAP_TAA_NO;
1649 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
cbbaa272 1650 data |= ARCH_CAP_TAA_NO;
7131636e
PB
1651 } else {
1652 /*
1653 * Nothing to do here; we emulate TSX_CTRL if present on the
1654 * host so the guest can choose between disabling TSX or
1655 * using VERW to clear CPU buffers.
1656 */
1657 }
e1d38b63 1658
81ac7e5d
DS
1659 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1660 data |= ARCH_CAP_GDS_NO;
1661
5b76a3cf
PB
1662 return data;
1663}
5b76a3cf 1664
7075f163
SC
1665static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1666 bool host_initiated)
66421c1e 1667{
7075f163
SC
1668 WARN_ON_ONCE(!host_initiated);
1669
1670 switch (index) {
cd283252 1671 case MSR_IA32_ARCH_CAPABILITIES:
7075f163 1672 *data = kvm_get_arch_capabilities();
5b76a3cf 1673 break;
5fe9805d 1674 case MSR_IA32_PERF_CAPABILITIES:
7075f163 1675 *data = kvm_caps.supported_perf_cap;
5fe9805d 1676 break;
b467ab82
PB
1677 case MSR_PLATFORM_INFO:
1678 *data = MSR_PLATFORM_INFO_CPUID_FAULT;
1679 break;
5b76a3cf 1680 case MSR_IA32_UCODE_REV:
6fe22aba 1681 rdmsrq_safe(index, data);
518e7b94 1682 break;
66421c1e 1683 default:
7075f163 1684 return kvm_x86_call(get_feature_msr)(index, data);
66421c1e
WL
1685 }
1686 return 0;
1687}
1688
b848f24b 1689static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
801e459a 1690{
1cec2034
SC
1691 return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1692 kvm_get_feature_msr);
801e459a
TL
1693}
1694
11988499 1695static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
15c4a640 1696{
8f2a2775 1697 if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
8c19b6f2
KP
1698 return false;
1699
8f2a2775 1700 if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
11988499 1701 return false;
1b2fd70c 1702
8f2a2775 1703 if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
11988499 1704 return false;
d8017474 1705
0a629563 1706 if (efer & (EFER_LME | EFER_LMA) &&
8f2a2775 1707 !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
0a629563
SC
1708 return false;
1709
8f2a2775 1710 if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
0a629563 1711 return false;
d8017474 1712
384bb783 1713 return true;
11988499
SC
1714
1715}
1716bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1717{
1718 if (efer & efer_reserved_bits)
1719 return false;
1720
1721 return __kvm_valid_efer(vcpu, efer);
384bb783
JK
1722}
1723EXPORT_SYMBOL_GPL(kvm_valid_efer);
1724
11988499 1725static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
384bb783
JK
1726{
1727 u64 old_efer = vcpu->arch.efer;
11988499 1728 u64 efer = msr_info->data;
72f211ec 1729 int r;
384bb783 1730
11988499 1731 if (efer & efer_reserved_bits)
66f61c92 1732 return 1;
384bb783 1733
11988499
SC
1734 if (!msr_info->host_initiated) {
1735 if (!__kvm_valid_efer(vcpu, efer))
1736 return 1;
1737
1738 if (is_paging(vcpu) &&
1739 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1740 return 1;
1741 }
384bb783 1742
15c4a640 1743 efer &= ~EFER_LMA;
f6801dff 1744 efer |= vcpu->arch.efer & EFER_LMA;
15c4a640 1745
89604647 1746 r = kvm_x86_call(set_efer)(vcpu, efer);
72f211ec
ML
1747 if (r) {
1748 WARN_ON(r > 0);
1749 return r;
1750 }
a3d204e2 1751
d6174299 1752 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
aad82703
SY
1753 kvm_mmu_reset_context(vcpu);
1754
d52734d0
MS
1755 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1756 (efer & EFER_SVME))
1757 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1758
b69e8cae 1759 return 0;
15c4a640
CO
1760}
1761
f2b4b7dd
JR
1762void kvm_enable_efer_bits(u64 mask)
1763{
1764 efer_reserved_bits &= ~mask;
1765}
1766EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1767
51de8151
AG
1768bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1769{
b318e8de
SC
1770 struct kvm_x86_msr_filter *msr_filter;
1771 struct msr_bitmap_range *ranges;
1a155254 1772 struct kvm *kvm = vcpu->kvm;
b318e8de 1773 bool allowed;
1a155254 1774 int idx;
b318e8de 1775 u32 i;
1a155254 1776
b318e8de
SC
1777 /* x2APIC MSRs do not support filtering. */
1778 if (index >= 0x800 && index <= 0x8ff)
1a155254
AG
1779 return true;
1780
1a155254
AG
1781 idx = srcu_read_lock(&kvm->srcu);
1782
b318e8de
SC
1783 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1784 if (!msr_filter) {
1785 allowed = true;
1786 goto out;
1787 }
1788
1789 allowed = msr_filter->default_allow;
1790 ranges = msr_filter->ranges;
1791
1792 for (i = 0; i < msr_filter->count; i++) {
1a155254
AG
1793 u32 start = ranges[i].base;
1794 u32 end = start + ranges[i].nmsrs;
1795 u32 flags = ranges[i].flags;
1796 unsigned long *bitmap = ranges[i].bitmap;
1797
1798 if ((index >= start) && (index < end) && (flags & type)) {
e12fa4b9 1799 allowed = test_bit(index - start, bitmap);
1a155254
AG
1800 break;
1801 }
1802 }
1803
b318e8de 1804out:
1a155254
AG
1805 srcu_read_unlock(&kvm->srcu, idx);
1806
b318e8de 1807 return allowed;
51de8151
AG
1808}
1809EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1810
15c4a640 1811/*
f20935d8
SC
1812 * Write @data into the MSR specified by @index. Select MSR specific fault
1813 * checks are bypassed if @host_initiated is %true.
15c4a640
CO
1814 * Returns 0 on success, non-0 otherwise.
1815 * Assumes vcpu_load() was already called.
1816 */
f20935d8
SC
1817static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1818 bool host_initiated)
15c4a640 1819{
f20935d8
SC
1820 struct msr_data msr;
1821
1822 switch (index) {
854e8bb1
NA
1823 case MSR_FS_BASE:
1824 case MSR_GS_BASE:
1825 case MSR_KERNEL_GS_BASE:
1826 case MSR_CSTAR:
1827 case MSR_LSTAR:
9245fd6b 1828 if (is_noncanonical_msr_address(data, vcpu))
854e8bb1
NA
1829 return 1;
1830 break;
1831 case MSR_IA32_SYSENTER_EIP:
1832 case MSR_IA32_SYSENTER_ESP:
1833 /*
1834 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1835 * non-canonical address is written on Intel but not on
1836 * AMD (which ignores the top 32-bits, because it does
1837 * not implement 64-bit SYSENTER).
1838 *
1839 * 64-bit code should hence be able to write a non-canonical
1840 * value on AMD. Making the address canonical ensures that
1841 * vmentry does not fail on Intel after writing a non-canonical
1842 * value, and that something deterministic happens if the guest
1843 * invokes 64-bit SYSENTER.
1844 */
9245fd6b 1845 data = __canonical_address(data, max_host_virt_addr_bits());
61a05d44
SC
1846 break;
1847 case MSR_TSC_AUX:
1848 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1849 return 1;
1850
1851 if (!host_initiated &&
8f2a2775
SC
1852 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1853 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
61a05d44
SC
1854 return 1;
1855
1856 /*
1857 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1858 * incomplete and conflicting architectural behavior. Current
1859 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1860 * reserved and always read as zeros. Enforce Intel's reserved
6463e5e4
SC
1861 * bits check if the guest CPU is Intel compatible, otherwise
1862 * clear the bits. This ensures cross-vendor migration will
1863 * provide consistent behavior for the guest.
61a05d44 1864 */
6463e5e4 1865 if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
61a05d44
SC
1866 return 1;
1867
1868 data = (u32)data;
1869 break;
854e8bb1 1870 }
f20935d8
SC
1871
1872 msr.data = data;
1873 msr.index = index;
1874 msr.host_initiated = host_initiated;
1875
89604647 1876 return kvm_x86_call(set_msr)(vcpu, &msr);
15c4a640
CO
1877}
1878
1cec2034
SC
1879static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1880 bool host_initiated)
1881{
1882 return __kvm_set_msr(vcpu, index, *data, host_initiated);
1883}
1884
6abe9c13
PX
1885static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1886 u32 index, u64 data, bool host_initiated)
1887{
1cec2034
SC
1888 return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1889 _kvm_set_msr);
6abe9c13
PX
1890}
1891
313a3dc7 1892/*
f20935d8
SC
1893 * Read the MSR specified by @index into @data. Select MSR specific fault
1894 * checks are bypassed if @host_initiated is %true.
1895 * Returns 0 on success, non-0 otherwise.
1896 * Assumes vcpu_load() was already called.
313a3dc7 1897 */
edef5c36
PB
1898int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1899 bool host_initiated)
609e36d3
PB
1900{
1901 struct msr_data msr;
f20935d8 1902 int ret;
609e36d3 1903
61a05d44
SC
1904 switch (index) {
1905 case MSR_TSC_AUX:
1906 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1907 return 1;
1908
1909 if (!host_initiated &&
8f2a2775
SC
1910 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1911 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
61a05d44
SC
1912 return 1;
1913 break;
1914 }
1915
609e36d3 1916 msr.index = index;
f20935d8 1917 msr.host_initiated = host_initiated;
609e36d3 1918
89604647 1919 ret = kvm_x86_call(get_msr)(vcpu, &msr);
f20935d8
SC
1920 if (!ret)
1921 *data = msr.data;
1922 return ret;
609e36d3
PB
1923}
1924
6abe9c13
PX
1925static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1926 u32 index, u64 *data, bool host_initiated)
1927{
1cec2034
SC
1928 return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
1929 __kvm_get_msr);
6abe9c13
PX
1930}
1931
653ea448 1932int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
ac8d6cad
HW
1933{
1934 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1935 return KVM_MSR_RET_FILTERED;
1936 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1937}
653ea448 1938EXPORT_SYMBOL_GPL(kvm_get_msr_with_filter);
ac8d6cad 1939
653ea448 1940int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
ac8d6cad
HW
1941{
1942 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1943 return KVM_MSR_RET_FILTERED;
1944 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1945}
653ea448 1946EXPORT_SYMBOL_GPL(kvm_set_msr_with_filter);
ac8d6cad 1947
f20935d8 1948int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
313a3dc7 1949{
6abe9c13 1950 return kvm_get_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1951}
1952EXPORT_SYMBOL_GPL(kvm_get_msr);
8fe8ab46 1953
f20935d8
SC
1954int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1955{
6abe9c13 1956 return kvm_set_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1957}
1958EXPORT_SYMBOL_GPL(kvm_set_msr);
1959
d2f7d498 1960static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1ae09954 1961{
d2f7d498 1962 if (!vcpu->run->msr.error) {
1ae09954
AG
1963 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1964 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1965 }
d2f7d498 1966}
1ae09954 1967
d2f7d498
HW
1968static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1969{
1970 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1ae09954
AG
1971}
1972
d2f7d498
HW
1973static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1974{
1975 complete_userspace_rdmsr(vcpu);
1976 return complete_emulated_msr_access(vcpu);
1977}
1978
1979static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1ae09954 1980{
89604647 1981 return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1ae09954
AG
1982}
1983
d2f7d498
HW
1984static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1985{
1986 complete_userspace_rdmsr(vcpu);
1987 return complete_fast_msr_access(vcpu);
1988}
1989
1ae09954
AG
1990static u64 kvm_msr_reason(int r)
1991{
1992 switch (r) {
aaecae7b 1993 case KVM_MSR_RET_UNSUPPORTED:
1ae09954 1994 return KVM_MSR_EXIT_REASON_UNKNOWN;
cc4cb017 1995 case KVM_MSR_RET_FILTERED:
1a155254 1996 return KVM_MSR_EXIT_REASON_FILTER;
1ae09954
AG
1997 default:
1998 return KVM_MSR_EXIT_REASON_INVAL;
1999 }
2000}
2001
2002static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2003 u32 exit_reason, u64 data,
2004 int (*completion)(struct kvm_vcpu *vcpu),
2005 int r)
2006{
2007 u64 msr_reason = kvm_msr_reason(r);
2008
2009 /* Check if the user wanted to know about this MSR fault */
2010 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2011 return 0;
2012
2013 vcpu->run->exit_reason = exit_reason;
2014 vcpu->run->msr.error = 0;
2015 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2016 vcpu->run->msr.reason = msr_reason;
2017 vcpu->run->msr.index = index;
2018 vcpu->run->msr.data = data;
2019 vcpu->arch.complete_userspace_io = completion;
2020
2021 return 1;
2022}
2023
1edce0a9
SC
2024int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2025{
2026 u32 ecx = kvm_rcx_read(vcpu);
2027 u64 data;
1ae09954
AG
2028 int r;
2029
ac8d6cad 2030 r = kvm_get_msr_with_filter(vcpu, ecx, &data);
1edce0a9 2031
8b474427
PB
2032 if (!r) {
2033 trace_kvm_msr_read(ecx, data);
2034
2035 kvm_rax_write(vcpu, data & -1u);
2036 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2037 } else {
d2f7d498
HW
2038 /* MSR read failed? See if we should ask user space */
2039 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2040 complete_fast_rdmsr, r))
2041 return 0;
1edce0a9 2042 trace_kvm_msr_read_ex(ecx);
1edce0a9
SC
2043 }
2044
89604647 2045 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
1edce0a9
SC
2046}
2047EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2048
2049int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2050{
2051 u32 ecx = kvm_rcx_read(vcpu);
2052 u64 data = kvm_read_edx_eax(vcpu);
1ae09954 2053 int r;
1edce0a9 2054
ac8d6cad 2055 r = kvm_set_msr_with_filter(vcpu, ecx, data);
1ae09954 2056
d2f7d498 2057 if (!r) {
8b474427 2058 trace_kvm_msr_write(ecx, data);
d2f7d498
HW
2059 } else {
2060 /* MSR write failed? See if we should ask user space */
2061 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2062 complete_fast_msr_access, r))
2063 return 0;
2064 /* Signal all other negative errors to userspace */
2065 if (r < 0)
2066 return r;
1edce0a9 2067 trace_kvm_msr_write_ex(ecx, data);
d2f7d498 2068 }
1edce0a9 2069
89604647 2070 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
1edce0a9
SC
2071}
2072EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2073
5ff3a351
SC
2074int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2075{
2076 return kvm_skip_emulated_instruction(vcpu);
2077}
5ff3a351
SC
2078
2079int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2080{
2081 /* Treat an INVD instruction as a NOP and just skip it. */
2082 return kvm_emulate_as_nop(vcpu);
2083}
2084EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2085
5ff3a351
SC
2086int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2087{
2088 kvm_queue_exception(vcpu, UD_VECTOR);
2089 return 1;
2090}
2091EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2092
bfbcc81b
SC
2093
2094static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
5ff3a351 2095{
a487f679
SC
2096 bool enabled;
2097
2098 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2099 goto emulate_as_nop;
2100
2101 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2102 enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2103 else
2104 enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2105
2106 if (!enabled)
bfbcc81b
SC
2107 return kvm_handle_invalid_op(vcpu);
2108
a487f679 2109emulate_as_nop:
8d20bd63 2110 pr_warn_once("%s instruction emulated as NOP!\n", insn);
5ff3a351
SC
2111 return kvm_emulate_as_nop(vcpu);
2112}
bfbcc81b
SC
2113int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2114{
2115 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2116}
2117EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2118
2119int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2120{
2121 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2122}
5ff3a351
SC
2123EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2124
d89d04ab 2125static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
5a9f5443 2126{
4ae7dc97 2127 xfer_to_guest_mode_prepare();
3ffe874e
SC
2128
2129 return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2130 kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
5a9f5443 2131}
5a9f5443 2132
1e9e2622
WL
2133/*
2134 * The fast path for frequent and performance sensitive wrmsr emulation,
2135 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2136 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2137 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2138 * other cases which must be called after interrupts are enabled on the host.
2139 */
2140static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2141{
e1be9ac8
WL
2142 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2143 return 1;
2144
2145 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
bd17f417
SC
2146 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2147 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
b9964ee3
SC
2148 ((u32)(data >> 32) != X2APIC_BROADCAST))
2149 return kvm_x2apic_icr_write(vcpu->arch.apic, data);
1e9e2622
WL
2150
2151 return 1;
2152}
2153
ae95f566
WL
2154static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2155{
2156 if (!kvm_can_use_hv_timer(vcpu))
2157 return 1;
2158
2159 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2160 return 0;
2161}
2162
404d5d7b 2163fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1e9e2622
WL
2164{
2165 u32 msr = kvm_rcx_read(vcpu);
8a1038de 2166 u64 data;
ea60229a
SC
2167 fastpath_t ret;
2168 bool handled;
1e9e2622 2169
3f2739bd
SC
2170 kvm_vcpu_srcu_read_lock(vcpu);
2171
1e9e2622
WL
2172 switch (msr) {
2173 case APIC_BASE_MSR + (APIC_ICR >> 4):
8a1038de 2174 data = kvm_read_edx_eax(vcpu);
ea60229a 2175 handled = !handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
1e9e2622 2176 break;
09141ec0 2177 case MSR_IA32_TSC_DEADLINE:
ae95f566 2178 data = kvm_read_edx_eax(vcpu);
ea60229a 2179 handled = !handle_fastpath_set_tscdeadline(vcpu, data);
ae95f566 2180 break;
1e9e2622 2181 default:
ea60229a 2182 handled = false;
404d5d7b 2183 break;
1e9e2622
WL
2184 }
2185
ea60229a 2186 if (handled) {
f7f39c50
SC
2187 if (!kvm_skip_emulated_instruction(vcpu))
2188 ret = EXIT_FASTPATH_EXIT_USERSPACE;
2189 else
2190 ret = EXIT_FASTPATH_REENTER_GUEST;
1e9e2622 2191 trace_kvm_msr_write(msr, data);
ea60229a
SC
2192 } else {
2193 ret = EXIT_FASTPATH_NONE;
2194 }
1e9e2622 2195
3f2739bd
SC
2196 kvm_vcpu_srcu_read_unlock(vcpu);
2197
404d5d7b 2198 return ret;
1e9e2622
WL
2199}
2200EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2201
f20935d8
SC
2202/*
2203 * Adapt set_msr() to msr_io()'s calling convention
2204 */
2205static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2206{
6abe9c13 2207 return kvm_get_msr_ignored_check(vcpu, index, data, true);
f20935d8
SC
2208}
2209
2210static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2211{
0094f62c
SC
2212 u64 val;
2213
2214 /*
2215 * Disallow writes to immutable feature MSRs after KVM_RUN. KVM does
2216 * not support modifying the guest vCPU model on the fly, e.g. changing
1d294dfa 2217 * the nVMX capabilities while L2 is running is nonsensical. Allow
0094f62c
SC
2218 * writes of the same value, e.g. to allow userspace to blindly stuff
2219 * all MSRs when emulating RESET.
2220 */
1d294dfa
SC
2221 if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2222 (do_get_msr(vcpu, index, &val) || *data != val))
2223 return -EINVAL;
0094f62c 2224
6abe9c13 2225 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
313a3dc7
CO
2226}
2227
16e8d74d 2228#ifdef CONFIG_X86_64
53fafdbb
MT
2229struct pvclock_clock {
2230 int vclock_mode;
2231 u64 cycle_last;
2232 u64 mask;
2233 u32 mult;
2234 u32 shift;
917f9475
PB
2235 u64 base_cycles;
2236 u64 offset;
53fafdbb
MT
2237};
2238
16e8d74d
MT
2239struct pvclock_gtod_data {
2240 seqcount_t seq;
2241
53fafdbb
MT
2242 struct pvclock_clock clock; /* extract of a clocksource struct */
2243 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
16e8d74d 2244
917f9475 2245 ktime_t offs_boot;
55dd00a7 2246 u64 wall_time_sec;
16e8d74d
MT
2247};
2248
2249static struct pvclock_gtod_data pvclock_gtod_data;
2250
2251static void update_pvclock_gtod(struct timekeeper *tk)
2252{
2253 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2254
2255 write_seqcount_begin(&vdata->seq);
2256
2257 /* copy pvclock gtod data */
b95a8a27 2258 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
876e7881
PZ
2259 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2260 vdata->clock.mask = tk->tkr_mono.mask;
2261 vdata->clock.mult = tk->tkr_mono.mult;
2262 vdata->clock.shift = tk->tkr_mono.shift;
917f9475
PB
2263 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2264 vdata->clock.offset = tk->tkr_mono.base;
16e8d74d 2265
b95a8a27 2266 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
53fafdbb
MT
2267 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2268 vdata->raw_clock.mask = tk->tkr_raw.mask;
2269 vdata->raw_clock.mult = tk->tkr_raw.mult;
2270 vdata->raw_clock.shift = tk->tkr_raw.shift;
917f9475
PB
2271 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2272 vdata->raw_clock.offset = tk->tkr_raw.base;
16e8d74d 2273
55dd00a7
MT
2274 vdata->wall_time_sec = tk->xtime_sec;
2275
917f9475 2276 vdata->offs_boot = tk->offs_boot;
53fafdbb 2277
16e8d74d
MT
2278 write_seqcount_end(&vdata->seq);
2279}
8171cd68
PB
2280
2281static s64 get_kvmclock_base_ns(void)
2282{
2283 /* Count up from boot time, but with the frequency of the raw clock. */
2284 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2285}
2286#else
2287static s64 get_kvmclock_base_ns(void)
2288{
2289 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2290 return ktime_get_boottime_ns();
2291}
16e8d74d
MT
2292#endif
2293
55749769 2294static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
18068523 2295{
9ed3c444
AK
2296 int version;
2297 int r;
50d0a0f9 2298 struct pvclock_wall_clock wc;
629b5348 2299 u32 wc_sec_hi;
8171cd68 2300 u64 wall_nsec;
18068523
GOC
2301
2302 if (!wall_clock)
2303 return;
2304
9ed3c444
AK
2305 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2306 if (r)
2307 return;
2308
2309 if (version & 1)
2310 ++version; /* first time write, random junk */
2311
2312 ++version;
18068523 2313
1dab1345
NK
2314 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2315 return;
18068523 2316
5d6d6a7d 2317 wall_nsec = kvm_get_wall_clock_epoch(kvm);
50d0a0f9 2318
5d6d6a7d 2319 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
8171cd68 2320 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
50d0a0f9 2321 wc.version = version;
18068523
GOC
2322
2323 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2324
629b5348
JM
2325 if (sec_hi_ofs) {
2326 wc_sec_hi = wall_nsec >> 32;
2327 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2328 &wc_sec_hi, sizeof(wc_sec_hi));
2329 }
2330
18068523
GOC
2331 version++;
2332 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
18068523
GOC
2333}
2334
5b9bb0eb
OU
2335static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2336 bool old_msr, bool host_initiated)
2337{
2338 struct kvm_arch *ka = &vcpu->kvm->arch;
2339
2340 if (vcpu->vcpu_id == 0 && !host_initiated) {
1e293d1a 2341 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
5b9bb0eb
OU
2342 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2343
2344 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2345 }
2346
2347 vcpu->arch.time = system_time;
2348 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2349
2350 /* we verify if the enable bit is set... */
8c82a0b3
ML
2351 if (system_time & 1)
2352 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
52491a38 2353 sizeof(struct pvclock_vcpu_time_info));
8c82a0b3
ML
2354 else
2355 kvm_gpc_deactivate(&vcpu->arch.pv_time);
5b9bb0eb
OU
2356
2357 return;
2358}
2359
50d0a0f9
GH
2360static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2361{
b51012de
PB
2362 do_shl32_div32(dividend, divisor);
2363 return dividend;
50d0a0f9
GH
2364}
2365
3ae13faa 2366static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
5f4e3f88 2367 s8 *pshift, u32 *pmultiplier)
50d0a0f9 2368{
5f4e3f88 2369 uint64_t scaled64;
50d0a0f9
GH
2370 int32_t shift = 0;
2371 uint64_t tps64;
2372 uint32_t tps32;
2373
3ae13faa
PB
2374 tps64 = base_hz;
2375 scaled64 = scaled_hz;
50933623 2376 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
50d0a0f9
GH
2377 tps64 >>= 1;
2378 shift--;
2379 }
2380
2381 tps32 = (uint32_t)tps64;
50933623
JK
2382 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2383 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
5f4e3f88
ZA
2384 scaled64 >>= 1;
2385 else
2386 tps32 <<= 1;
50d0a0f9
GH
2387 shift++;
2388 }
2389
5f4e3f88
ZA
2390 *pshift = shift;
2391 *pmultiplier = div_frac(scaled64, tps32);
50d0a0f9
GH
2392}
2393
d828199e 2394#ifdef CONFIG_X86_64
16e8d74d 2395static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
d828199e 2396#endif
16e8d74d 2397
c8076604 2398static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
69b0049a 2399static unsigned long max_tsc_khz;
c8076604 2400
cc578287 2401static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1e993611 2402{
cc578287
ZA
2403 u64 v = (u64)khz * (1000000 + ppm);
2404 do_div(v, 1000000);
2405 return v;
1e993611
JR
2406}
2407
1ab9287a
IS
2408static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2409
381d585c
HZ
2410static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2411{
2412 u64 ratio;
2413
2414 /* Guest TSC same frequency as host TSC? */
2415 if (!scale) {
938c8745 2416 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
381d585c
HZ
2417 return 0;
2418 }
2419
2420 /* TSC scaling supported? */
938c8745 2421 if (!kvm_caps.has_tsc_control) {
381d585c
HZ
2422 if (user_tsc_khz > tsc_khz) {
2423 vcpu->arch.tsc_catchup = 1;
2424 vcpu->arch.tsc_always_catchup = 1;
2425 return 0;
2426 } else {
3f16a5c3 2427 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
381d585c
HZ
2428 return -1;
2429 }
2430 }
2431
2432 /* TSC scaling required - calculate ratio */
938c8745 2433 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
381d585c
HZ
2434 user_tsc_khz, tsc_khz);
2435
938c8745 2436 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
3f16a5c3
PB
2437 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2438 user_tsc_khz);
381d585c
HZ
2439 return -1;
2440 }
2441
1ab9287a 2442 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
381d585c
HZ
2443 return 0;
2444}
2445
4941b8cb 2446static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
759379dd 2447{
cc578287
ZA
2448 u32 thresh_lo, thresh_hi;
2449 int use_scaling = 0;
217fc9cf 2450
03ba32ca 2451 /* tsc_khz can be zero if TSC calibration fails */
4941b8cb 2452 if (user_tsc_khz == 0) {
ad721883 2453 /* set tsc_scaling_ratio to a safe value */
938c8745 2454 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
381d585c 2455 return -1;
ad721883 2456 }
03ba32ca 2457
c285545f 2458 /* Compute a scale to convert nanoseconds in TSC cycles */
3ae13faa 2459 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
cc578287
ZA
2460 &vcpu->arch.virtual_tsc_shift,
2461 &vcpu->arch.virtual_tsc_mult);
4941b8cb 2462 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
cc578287
ZA
2463
2464 /*
2465 * Compute the variation in TSC rate which is acceptable
2466 * within the range of tolerance and decide if the
2467 * rate being applied is within that bounds of the hardware
2468 * rate. If so, no scaling or compensation need be done.
2469 */
2470 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2471 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
4941b8cb 2472 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
8d20bd63
SC
2473 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2474 user_tsc_khz, thresh_lo, thresh_hi);
cc578287
ZA
2475 use_scaling = 1;
2476 }
4941b8cb 2477 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
c285545f
ZA
2478}
2479
2480static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2481{
e26101b1 2482 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
cc578287
ZA
2483 vcpu->arch.virtual_tsc_mult,
2484 vcpu->arch.virtual_tsc_shift);
e26101b1 2485 tsc += vcpu->arch.this_tsc_write;
c285545f
ZA
2486 return tsc;
2487}
2488
ba1f77c5 2489#ifdef CONFIG_X86_64
9e62797f 2490static inline bool gtod_is_based_on_tsc(int mode)
b0c39dc6 2491{
b95a8a27 2492 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
b0c39dc6 2493}
ba1f77c5 2494#endif
b0c39dc6 2495
c52ffadc 2496static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
b48aa97e
MT
2497{
2498#ifdef CONFIG_X86_64
b48aa97e
MT
2499 struct kvm_arch *ka = &vcpu->kvm->arch;
2500 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2501
c52ffadc
SC
2502 /*
2503 * To use the masterclock, the host clocksource must be based on TSC
2504 * and all vCPUs must have matching TSCs. Note, the count for matching
2505 * vCPUs doesn't include the reference vCPU, hence "+1".
2506 */
2507 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2508 atomic_read(&vcpu->kvm->online_vcpus)) &&
2509 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
b48aa97e 2510
7f187922 2511 /*
c52ffadc
SC
2512 * Request a masterclock update if the masterclock needs to be toggled
2513 * on/off, or when starting a new generation and the masterclock is
2514 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2515 * taken _after_ the new generation is created).
7f187922 2516 */
c52ffadc
SC
2517 if ((ka->use_master_clock && new_generation) ||
2518 (ka->use_master_clock != use_master_clock))
b48aa97e
MT
2519 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2520
2521 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2522 atomic_read(&vcpu->kvm->online_vcpus),
2523 ka->use_master_clock, gtod->clock.vclock_mode);
2524#endif
2525}
2526
35181e86
HZ
2527/*
2528 * Multiply tsc by a fixed point number represented by ratio.
2529 *
2530 * The most significant 64-N bits (mult) of ratio represent the
2531 * integral part of the fixed point number; the remaining N bits
2532 * (frac) represent the fractional part, ie. ratio represents a fixed
2533 * point number (mult + frac * 2^(-N)).
2534 *
938c8745 2535 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
35181e86
HZ
2536 */
2537static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2538{
938c8745 2539 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
35181e86
HZ
2540}
2541
62711e5a 2542u64 kvm_scale_tsc(u64 tsc, u64 ratio)
35181e86
HZ
2543{
2544 u64 _tsc = tsc;
35181e86 2545
938c8745 2546 if (ratio != kvm_caps.default_tsc_scaling_ratio)
35181e86
HZ
2547 _tsc = __scale_tsc(ratio, tsc);
2548
2549 return _tsc;
2550}
35181e86 2551
9b399dfd 2552static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
07c1419a
HZ
2553{
2554 u64 tsc;
2555
62711e5a 2556 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
07c1419a
HZ
2557
2558 return target_tsc - tsc;
2559}
2560
4ba76538
HZ
2561u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2562{
fe3eb504 2563 return vcpu->arch.l1_tsc_offset +
62711e5a 2564 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
4ba76538
HZ
2565}
2566EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2567
83150f29
IS
2568u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2569{
2570 u64 nested_offset;
2571
938c8745 2572 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
83150f29
IS
2573 nested_offset = l1_offset;
2574 else
2575 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
938c8745 2576 kvm_caps.tsc_scaling_ratio_frac_bits);
83150f29
IS
2577
2578 nested_offset += l2_offset;
2579 return nested_offset;
2580}
2581EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2582
2583u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2584{
938c8745 2585 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
83150f29 2586 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
938c8745 2587 kvm_caps.tsc_scaling_ratio_frac_bits);
83150f29
IS
2588
2589 return l1_multiplier;
2590}
2591EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2592
edcfe540 2593static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
a545ab6a 2594{
adafea11
IY
2595 if (vcpu->arch.guest_tsc_protected)
2596 return;
2597
edcfe540
IS
2598 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2599 vcpu->arch.l1_tsc_offset,
2600 l1_offset);
2601
2602 vcpu->arch.l1_tsc_offset = l1_offset;
2603
2604 /*
2605 * If we are here because L1 chose not to trap WRMSR to TSC then
2606 * according to the spec this should set L1's TSC (as opposed to
2607 * setting L1's offset for L2).
2608 */
2609 if (is_guest_mode(vcpu))
2610 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2611 l1_offset,
89604647
WW
2612 kvm_x86_call(get_l2_tsc_offset)(vcpu),
2613 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
edcfe540
IS
2614 else
2615 vcpu->arch.tsc_offset = l1_offset;
2616
89604647 2617 kvm_x86_call(write_tsc_offset)(vcpu);
a545ab6a
LC
2618}
2619
1ab9287a
IS
2620static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2621{
2622 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2623
2624 /* Userspace is changing the multiplier while L2 is active */
2625 if (is_guest_mode(vcpu))
2626 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2627 l1_multiplier,
89604647 2628 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
1ab9287a
IS
2629 else
2630 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2631
938c8745 2632 if (kvm_caps.has_tsc_control)
89604647 2633 kvm_x86_call(write_tsc_multiplier)(vcpu);
1ab9287a
IS
2634}
2635
b0c39dc6
VK
2636static inline bool kvm_check_tsc_unstable(void)
2637{
2638#ifdef CONFIG_X86_64
2639 /*
2640 * TSC is marked unstable when we're running on Hyper-V,
2641 * 'TSC page' clocksource is good.
2642 */
b95a8a27 2643 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
b0c39dc6
VK
2644 return false;
2645#endif
2646 return check_tsc_unstable();
2647}
2648
58d4277b
OU
2649/*
2650 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2651 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2652 * participates in.
2653 */
2654static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
5f3b30b2 2655 u64 ns, bool matched, bool user_set_tsc)
58d4277b
OU
2656{
2657 struct kvm *kvm = vcpu->kvm;
2658
2659 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2660
adafea11
IY
2661 if (vcpu->arch.guest_tsc_protected)
2662 return;
2663
5f3b30b2
IY
2664 if (user_set_tsc)
2665 vcpu->kvm->arch.user_set_tsc = true;
2666
58d4277b
OU
2667 /*
2668 * We also track th most recent recorded KHZ, write and time to
2669 * allow the matching interval to be extended at each write.
2670 */
2671 kvm->arch.last_tsc_nsec = ns;
2672 kvm->arch.last_tsc_write = tsc;
2673 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
828ca896 2674 kvm->arch.last_tsc_offset = offset;
58d4277b
OU
2675
2676 vcpu->arch.last_guest_tsc = tsc;
2677
2678 kvm_vcpu_write_tsc_offset(vcpu, offset);
2679
2680 if (!matched) {
2681 /*
2682 * We split periods of matched TSC writes into generations.
2683 * For each generation, we track the original measured
2684 * nanosecond time, offset, and write, so if TSCs are in
2685 * sync, we can match exact offset, and if not, we can match
2686 * exact software computation in compute_guest_tsc()
2687 *
2688 * These values are tracked in kvm->arch.cur_xxx variables.
2689 */
2690 kvm->arch.cur_tsc_generation++;
2691 kvm->arch.cur_tsc_nsec = ns;
2692 kvm->arch.cur_tsc_write = tsc;
2693 kvm->arch.cur_tsc_offset = offset;
2694 kvm->arch.nr_vcpus_matched_tsc = 0;
2695 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2696 kvm->arch.nr_vcpus_matched_tsc++;
2697 }
2698
2699 /* Keep track of which generation this VCPU has synchronized to */
2700 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2701 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2702 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2703
c52ffadc 2704 kvm_track_tsc_matching(vcpu, !matched);
58d4277b
OU
2705}
2706
bf328e22 2707static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
99e3e30a 2708{
bf328e22 2709 u64 data = user_value ? *user_value : 0;
99e3e30a 2710 struct kvm *kvm = vcpu->kvm;
f38e098f 2711 u64 offset, ns, elapsed;
99e3e30a 2712 unsigned long flags;
58d4277b 2713 bool matched = false;
c5e8ec8e 2714 bool synchronizing = false;
99e3e30a 2715
038f8c11 2716 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
9b399dfd 2717 offset = kvm_compute_l1_tsc_offset(vcpu, data);
8171cd68 2718 ns = get_kvmclock_base_ns();
f38e098f 2719 elapsed = ns - kvm->arch.last_tsc_nsec;
5d3cb0f6 2720
03ba32ca 2721 if (vcpu->arch.virtual_tsc_khz) {
0c899c25 2722 if (data == 0) {
bd8fab39 2723 /*
bf328e22
LX
2724 * Force synchronization when creating a vCPU, or when
2725 * userspace explicitly writes a zero value.
bd8fab39
DP
2726 */
2727 synchronizing = true;
bf328e22 2728 } else if (kvm->arch.user_set_tsc) {
bd8fab39
DP
2729 u64 tsc_exp = kvm->arch.last_tsc_write +
2730 nsec_to_cycles(vcpu, elapsed);
2731 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2732 /*
bf328e22
LX
2733 * Here lies UAPI baggage: when a user-initiated TSC write has
2734 * a small delta (1 second) of virtual cycle time against the
2735 * previously set vCPU, we assume that they were intended to be
2736 * in sync and the delta was only due to the racy nature of the
2737 * legacy API.
2738 *
2739 * This trick falls down when restoring a guest which genuinely
2740 * has been running for less time than the 1 second of imprecision
2741 * which we allow for in the legacy API. In this case, the first
2742 * value written by userspace (on any vCPU) should not be subject
2743 * to this 'correction' to make it sync up with values that only
2744 * come from the kernel's default vCPU creation. Make the 1-second
2745 * slop hack only trigger if the user_set_tsc flag is already set.
bd8fab39
DP
2746 */
2747 synchronizing = data < tsc_exp + tsc_hz &&
2748 data + tsc_hz > tsc_exp;
2749 }
c5e8ec8e 2750 }
f38e098f 2751
bf328e22 2752
f38e098f 2753 /*
5d3cb0f6
ZA
2754 * For a reliable TSC, we can match TSC offsets, and for an unstable
2755 * TSC, we add elapsed time in this computation. We could let the
2756 * compensation code attempt to catch up if we fall behind, but
2757 * it's better to try to match offsets from the beginning.
2758 */
c5e8ec8e 2759 if (synchronizing &&
5d3cb0f6 2760 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
b0c39dc6 2761 if (!kvm_check_tsc_unstable()) {
e26101b1 2762 offset = kvm->arch.cur_tsc_offset;
f38e098f 2763 } else {
857e4099 2764 u64 delta = nsec_to_cycles(vcpu, elapsed);
5d3cb0f6 2765 data += delta;
9b399dfd 2766 offset = kvm_compute_l1_tsc_offset(vcpu, data);
f38e098f 2767 }
b48aa97e 2768 matched = true;
f38e098f 2769 }
e26101b1 2770
5f3b30b2 2771 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
e26101b1 2772 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
99e3e30a 2773}
e26101b1 2774
58ea6767
HZ
2775static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2776 s64 adjustment)
2777{
56ba77a4 2778 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
326e7425 2779 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
58ea6767
HZ
2780}
2781
2782static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2783{
938c8745 2784 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
58ea6767 2785 WARN_ON(adjustment < 0);
62711e5a 2786 adjustment = kvm_scale_tsc((u64) adjustment,
fe3eb504 2787 vcpu->arch.l1_tsc_scaling_ratio);
ea26e4ec 2788 adjust_tsc_offset_guest(vcpu, adjustment);
58ea6767
HZ
2789}
2790
d828199e
MT
2791#ifdef CONFIG_X86_64
2792
a5a1d1c2 2793static u64 read_tsc(void)
d828199e 2794{
a5a1d1c2 2795 u64 ret = (u64)rdtsc_ordered();
03b9730b 2796 u64 last = pvclock_gtod_data.clock.cycle_last;
d828199e
MT
2797
2798 if (likely(ret >= last))
2799 return ret;
2800
2801 /*
2802 * GCC likes to generate cmov here, but this branch is extremely
6a6256f9 2803 * predictable (it's just a function of time and the likely is
d828199e
MT
2804 * very likely) and there's a data dependence, so force GCC
2805 * to generate a branch instead. I don't barrier() because
2806 * we don't actually need a barrier, and if this function
2807 * ever gets inlined it will generate worse code.
2808 */
2809 asm volatile ("");
2810 return last;
2811}
2812
53fafdbb
MT
2813static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2814 int *mode)
d828199e 2815{
b0c39dc6 2816 u64 tsc_pg_val;
9397fa2e 2817 long v;
b0c39dc6 2818
53fafdbb 2819 switch (clock->vclock_mode) {
b95a8a27 2820 case VDSO_CLOCKMODE_HVCLOCK:
9397fa2e
PZ
2821 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2822 tsc_timestamp, &tsc_pg_val)) {
b0c39dc6 2823 /* TSC page valid */
b95a8a27 2824 *mode = VDSO_CLOCKMODE_HVCLOCK;
53fafdbb
MT
2825 v = (tsc_pg_val - clock->cycle_last) &
2826 clock->mask;
b0c39dc6
VK
2827 } else {
2828 /* TSC page invalid */
b95a8a27 2829 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6
VK
2830 }
2831 break;
b95a8a27
TG
2832 case VDSO_CLOCKMODE_TSC:
2833 *mode = VDSO_CLOCKMODE_TSC;
b0c39dc6 2834 *tsc_timestamp = read_tsc();
53fafdbb
MT
2835 v = (*tsc_timestamp - clock->cycle_last) &
2836 clock->mask;
b0c39dc6
VK
2837 break;
2838 default:
b95a8a27 2839 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6 2840 }
d828199e 2841
b95a8a27 2842 if (*mode == VDSO_CLOCKMODE_NONE)
b0c39dc6 2843 *tsc_timestamp = v = 0;
d828199e 2844
53fafdbb 2845 return v * clock->mult;
d828199e
MT
2846}
2847
451a7078
DW
2848/*
2849 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2850 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2851 */
2852static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
d828199e 2853{
cbcf2dd3 2854 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
d828199e 2855 unsigned long seq;
d828199e 2856 int mode;
cbcf2dd3 2857 u64 ns;
d828199e 2858
d828199e
MT
2859 do {
2860 seq = read_seqcount_begin(&gtod->seq);
917f9475 2861 ns = gtod->raw_clock.base_cycles;
53fafdbb 2862 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
917f9475
PB
2863 ns >>= gtod->raw_clock.shift;
2864 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
d828199e 2865 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
cbcf2dd3 2866 *t = ns;
d828199e
MT
2867
2868 return mode;
2869}
2870
451a7078
DW
2871/*
2872 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2873 * no boot time offset.
2874 */
2875static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2876{
2877 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2878 unsigned long seq;
2879 int mode;
2880 u64 ns;
2881
2882 do {
2883 seq = read_seqcount_begin(&gtod->seq);
2884 ns = gtod->clock.base_cycles;
2885 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2886 ns >>= gtod->clock.shift;
2887 ns += ktime_to_ns(gtod->clock.offset);
2888 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2889 *t = ns;
2890
2891 return mode;
2892}
2893
899a31f5 2894static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
55dd00a7
MT
2895{
2896 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2897 unsigned long seq;
2898 int mode;
2899 u64 ns;
2900
2901 do {
2902 seq = read_seqcount_begin(&gtod->seq);
55dd00a7 2903 ts->tv_sec = gtod->wall_time_sec;
917f9475 2904 ns = gtod->clock.base_cycles;
53fafdbb 2905 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
55dd00a7
MT
2906 ns >>= gtod->clock.shift;
2907 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2908
2909 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2910 ts->tv_nsec = ns;
2911
2912 return mode;
2913}
2914
451a7078
DW
2915/*
2916 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2917 * reports the TSC value from which it do so. Returns true if host is
2918 * using TSC based clocksource.
2919 */
b0c39dc6 2920static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
d828199e 2921{
d828199e 2922 /* checked again under seqlock below */
b0c39dc6 2923 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
d828199e
MT
2924 return false;
2925
451a7078
DW
2926 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2927 tsc_timestamp));
d828199e 2928}
55dd00a7 2929
451a7078
DW
2930/*
2931 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2932 * so. Returns true if host is using TSC based clocksource.
2933 */
2934bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2935{
2936 /* checked again under seqlock below */
2937 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2938 return false;
2939
2940 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
2941 tsc_timestamp));
2942}
2943
2944/*
2945 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2946 * so. Returns true if host is using TSC based clocksource.
2947 *
2948 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2949 * for that.
2950 */
899a31f5 2951static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
b0c39dc6 2952 u64 *tsc_timestamp)
55dd00a7
MT
2953{
2954 /* checked again under seqlock below */
b0c39dc6 2955 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
55dd00a7
MT
2956 return false;
2957
b0c39dc6 2958 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
55dd00a7 2959}
d828199e
MT
2960#endif
2961
2962/*
2963 *
b48aa97e
MT
2964 * Assuming a stable TSC across physical CPUS, and a stable TSC
2965 * across virtual CPUs, the following condition is possible.
2966 * Each numbered line represents an event visible to both
d828199e
MT
2967 * CPUs at the next numbered event.
2968 *
2969 * "timespecX" represents host monotonic time. "tscX" represents
2970 * RDTSC value.
2971 *
2972 * VCPU0 on CPU0 | VCPU1 on CPU1
2973 *
2974 * 1. read timespec0,tsc0
2975 * 2. | timespec1 = timespec0 + N
2976 * | tsc1 = tsc0 + M
2977 * 3. transition to guest | transition to guest
2978 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2979 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2980 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2981 *
2982 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2983 *
2984 * - ret0 < ret1
2985 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2986 * ...
2987 * - 0 < N - M => M < N
2988 *
2989 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2990 * always the case (the difference between two distinct xtime instances
2991 * might be smaller then the difference between corresponding TSC reads,
2992 * when updating guest vcpus pvclock areas).
2993 *
2994 * To avoid that problem, do not allow visibility of distinct
2995 * system_timestamp/tsc_timestamp values simultaneously: use a master
2996 * copy of host monotonic time values. Update that master copy
2997 * in lockstep.
2998 *
b48aa97e 2999 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
d828199e
MT
3000 *
3001 */
3002
3003static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3004{
3005#ifdef CONFIG_X86_64
3006 struct kvm_arch *ka = &kvm->arch;
3007 int vclock_mode;
b48aa97e
MT
3008 bool host_tsc_clocksource, vcpus_matched;
3009
869b4421 3010 lockdep_assert_held(&kvm->arch.tsc_write_lock);
b48aa97e
MT
3011 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3012 atomic_read(&kvm->online_vcpus));
d828199e
MT
3013
3014 /*
3015 * If the host uses TSC clock, then passthrough TSC as stable
3016 * to the guest.
3017 */
b48aa97e 3018 host_tsc_clocksource = kvm_get_time_and_clockread(
d828199e
MT
3019 &ka->master_kernel_ns,
3020 &ka->master_cycle_now);
3021
16a96021 3022 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
a826faf1 3023 && !ka->backwards_tsc_observed
54750f2c 3024 && !ka->boot_vcpu_runs_old_kvmclock;
b48aa97e 3025
d828199e
MT
3026 if (ka->use_master_clock)
3027 atomic_set(&kvm_guest_has_master_clock, 1);
3028
3029 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
b48aa97e
MT
3030 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3031 vcpus_matched);
d828199e
MT
3032#endif
3033}
3034
6b6fcd28 3035static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2860c4b1
PB
3036{
3037 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3038}
3039
869b4421 3040static void __kvm_start_pvclock_update(struct kvm *kvm)
2e762ff7 3041{
869b4421
PB
3042 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3043 write_seqcount_begin(&kvm->arch.pvclock_sc);
3044}
e880c6ea 3045
869b4421
PB
3046static void kvm_start_pvclock_update(struct kvm *kvm)
3047{
2e762ff7 3048 kvm_make_mclock_inprogress_request(kvm);
c2c647f9 3049
2e762ff7 3050 /* no guest entries from this point */
869b4421 3051 __kvm_start_pvclock_update(kvm);
6b6fcd28 3052}
2e762ff7 3053
6b6fcd28
PB
3054static void kvm_end_pvclock_update(struct kvm *kvm)
3055{
3056 struct kvm_arch *ka = &kvm->arch;
3057 struct kvm_vcpu *vcpu;
46808a4c 3058 unsigned long i;
2e762ff7 3059
869b4421
PB
3060 write_seqcount_end(&ka->pvclock_sc);
3061 raw_spin_unlock_irq(&ka->tsc_write_lock);
2e762ff7 3062 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 3063 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2e762ff7
MT
3064
3065 /* guest entries allowed */
3066 kvm_for_each_vcpu(i, vcpu, kvm)
72875d8a 3067 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2e762ff7
MT
3068}
3069
6b6fcd28
PB
3070static void kvm_update_masterclock(struct kvm *kvm)
3071{
42dcbe7d 3072 kvm_hv_request_tsc_page_update(kvm);
6b6fcd28
PB
3073 kvm_start_pvclock_update(kvm);
3074 pvclock_update_vm_gtod_copy(kvm);
3075 kvm_end_pvclock_update(kvm);
2e762ff7
MT
3076}
3077
3ebcbd22
AR
3078/*
3079 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3080 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3081 * can change during boot even if the TSC is constant, as it's possible for KVM
3082 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3083 * notification when calibration completes, but practically speaking calibration
3084 * will complete before userspace is alive enough to create VMs.
3085 */
3086static unsigned long get_cpu_tsc_khz(void)
3087{
3088 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3089 return tsc_khz;
3090 else
3091 return __this_cpu_read(cpu_tsc_khz);
3092}
3093
869b4421
PB
3094/* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
3095static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
108b249c 3096{
108b249c 3097 struct kvm_arch *ka = &kvm->arch;
8b953440 3098 struct pvclock_vcpu_time_info hv_clock;
8b953440 3099
e2c2206a
WL
3100 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3101 get_cpu();
3102
869b4421 3103 data->flags = 0;
3ebcbd22
AR
3104 if (ka->use_master_clock &&
3105 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
c68dc1b5
OU
3106#ifdef CONFIG_X86_64
3107 struct timespec64 ts;
3108
3109 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3110 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3111 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3112 } else
3113#endif
3114 data->host_tsc = rdtsc();
3115
869b4421
PB
3116 data->flags |= KVM_CLOCK_TSC_STABLE;
3117 hv_clock.tsc_timestamp = ka->master_cycle_now;
3118 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3ebcbd22 3119 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
e70b57a6
WL
3120 &hv_clock.tsc_shift,
3121 &hv_clock.tsc_to_system_mul);
c68dc1b5 3122 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
55c0cefb
OU
3123 } else {
3124 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3125 }
e2c2206a
WL
3126
3127 put_cpu();
55c0cefb 3128}
e2c2206a 3129
869b4421
PB
3130static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3131{
3132 struct kvm_arch *ka = &kvm->arch;
3133 unsigned seq;
3134
3135 do {
3136 seq = read_seqcount_begin(&ka->pvclock_sc);
3137 __get_kvmclock(kvm, data);
3138 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3139}
3140
55c0cefb
OU
3141u64 get_kvmclock_ns(struct kvm *kvm)
3142{
3143 struct kvm_clock_data data;
3144
55c0cefb
OU
3145 get_kvmclock(kvm, &data);
3146 return data.clock;
108b249c
PB
3147}
3148
46aed4d4
SC
3149static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3150 struct kvm_vcpu *vcpu,
916d3608 3151 struct gfn_to_pfn_cache *gpc,
1b3c3805 3152 unsigned int offset)
0d6dd2ff 3153{
916d3608 3154 struct pvclock_vcpu_time_info *guest_hv_clock;
24c16637 3155 struct pvclock_vcpu_time_info hv_clock;
916d3608 3156 unsigned long flags;
0d6dd2ff 3157
46aed4d4 3158 memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
24c16637 3159
916d3608 3160 read_lock_irqsave(&gpc->lock, flags);
58f5ee5f 3161 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
916d3608
DW
3162 read_unlock_irqrestore(&gpc->lock, flags);
3163
58f5ee5f 3164 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
916d3608 3165 return;
0d6dd2ff 3166
916d3608
DW
3167 read_lock_irqsave(&gpc->lock, flags);
3168 }
3169
3170 guest_hv_clock = (void *)(gpc->khva + offset);
3171
3172 /*
3173 * This VCPU is paused, but it's legal for a guest to read another
0d6dd2ff
PB
3174 * VCPU's kvmclock, so we really have to follow the specification where
3175 * it says that version is odd if data is being modified, and even after
3176 * it is consistent.
0d6dd2ff 3177 */
0d6dd2ff 3178
24c16637 3179 guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
0d6dd2ff
PB
3180 smp_wmb();
3181
3182 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
24c16637 3183 hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
0d6dd2ff 3184
24c16637 3185 memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
6d722835 3186
916d3608 3187 smp_wmb();
0d6dd2ff 3188
24c16637 3189 guest_hv_clock->version = ++hv_clock.version;
0d6dd2ff 3190
78b74638 3191 kvm_gpc_mark_dirty_in_slot(gpc);
916d3608 3192 read_unlock_irqrestore(&gpc->lock, flags);
0d6dd2ff 3193
46aed4d4 3194 trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
0d6dd2ff
PB
3195}
3196
a2b00f85 3197int kvm_guest_time_update(struct kvm_vcpu *v)
18068523 3198{
39d61b46 3199 struct pvclock_vcpu_time_info hv_clock = {};
78db6a50 3200 unsigned long flags, tgt_tsc_khz;
869b4421 3201 unsigned seq;
18068523 3202 struct kvm_vcpu_arch *vcpu = &v->arch;
d828199e 3203 struct kvm_arch *ka = &v->kvm->arch;
f25e656d 3204 s64 kernel_ns;
d828199e 3205 u64 tsc_timestamp, host_tsc;
d828199e
MT
3206 bool use_master_clock;
3207
3208 kernel_ns = 0;
3209 host_tsc = 0;
18068523 3210
d828199e
MT
3211 /*
3212 * If the host uses TSC clock, then passthrough TSC as stable
3213 * to the guest.
3214 */
869b4421
PB
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));
c09664bb
MT
3223
3224 /* Keep irq disabled to prevent changes to the clock */
3225 local_irq_save(flags);
3ebcbd22 3226 tgt_tsc_khz = get_cpu_tsc_khz();
78db6a50 3227 if (unlikely(tgt_tsc_khz == 0)) {
c09664bb
MT
3228 local_irq_restore(flags);
3229 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3230 return 1;
3231 }
d828199e 3232 if (!use_master_clock) {
4ea1636b 3233 host_tsc = rdtsc();
8171cd68 3234 kernel_ns = get_kvmclock_base_ns();
d828199e
MT
3235 }
3236
4ba76538 3237 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
d828199e 3238
c285545f
ZA
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) {
f1e2b260 3252 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
c285545f
ZA
3253 tsc_timestamp = tsc;
3254 }
50d0a0f9
GH
3255 }
3256
18068523
GOC
3257 local_irq_restore(flags);
3258
0d6dd2ff 3259 /* With all the info we got, fill in the values */
18068523 3260
938c8745 3261 if (kvm_caps.has_tsc_control)
62711e5a 3262 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
fe3eb504 3263 v->arch.l1_tsc_scaling_ratio);
78db6a50
PB
3264
3265 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3ae13faa 3266 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
39d61b46
SC
3267 &vcpu->pvclock_tsc_shift,
3268 &vcpu->pvclock_tsc_mul);
78db6a50 3269 vcpu->hw_tsc_khz = tgt_tsc_khz;
8cfdc000
ZA
3270 }
3271
39d61b46
SC
3272 hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3273 hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3274 hv_clock.tsc_timestamp = tsc_timestamp;
3275 hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
28e4639a 3276 vcpu->last_guest_tsc = tsc_timestamp;
51d59c6b 3277
d828199e 3278 /* If the host uses TSC clocksource, then it is stable */
39d61b46 3279 hv_clock.flags = 0;
d828199e 3280 if (use_master_clock)
39d61b46 3281 hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
78c0337a 3282
93fb0b10
SC
3283 if (vcpu->pv_time.active) {
3284 /*
3285 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3286 * historic behavior is to only process the request if kvmclock
3287 * is active/enabled.
3288 */
6c4927a4 3289 if (vcpu->pvclock_set_guest_stopped_request) {
39d61b46 3290 hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
6c4927a4
SC
3291 vcpu->pvclock_set_guest_stopped_request = false;
3292 }
1b3c3805 3293 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
93fb0b10 3294
39d61b46 3295 hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
6c4927a4 3296 }
d828199e 3297
847d68ab 3298 kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
78c0337a 3299
ee11ab6b 3300#ifdef CONFIG_KVM_XEN
1b3c3805
SC
3301 /*
3302 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3303 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3304 * This default behaviour led to bugs in some guest kernels which cause
3305 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3306 *
3307 * Note! Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3308 */
3ecf162a 3309 if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
1b3c3805
SC
3310 hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3311
7caf9571 3312 if (vcpu->xen.vcpu_info_cache.active)
39d61b46 3313 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
1b3c3805 3314 offsetof(struct compat_vcpu_info, time));
69d413cf 3315 if (vcpu->xen.vcpu_time_info_cache.active)
1b3c3805 3316 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
ee11ab6b 3317#endif
8cfdc000 3318 return 0;
c8076604
GH
3319}
3320
5d6d6a7d
DW
3321/*
3322 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3323 * which it started (i.e. its epoch, when its kvmclock was zero).
3324 *
3325 * In fact those clocks are subtly different; wall clock frequency is
3326 * adjusted by NTP and has leap seconds, while the kvmclock is a
3327 * simple function of the TSC without any such adjustment.
3328 *
3329 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3330 * that and kvmclock, but even that would be subject to change over
3331 * time.
3332 *
3333 * Attempt to calculate the epoch at a given moment using the *same*
3334 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3335 * wallclock and kvmclock times, and subtracting one from the other.
3336 *
3337 * Fall back to using their values at slightly different moments by
3338 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3339 */
3340uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3341{
3342#ifdef CONFIG_X86_64
3343 struct pvclock_vcpu_time_info hv_clock;
3344 struct kvm_arch *ka = &kvm->arch;
3345 unsigned long seq, local_tsc_khz;
3346 struct timespec64 ts;
3347 uint64_t host_tsc;
3348
3349 do {
3350 seq = read_seqcount_begin(&ka->pvclock_sc);
3351
3352 local_tsc_khz = 0;
3353 if (!ka->use_master_clock)
3354 break;
3355
3356 /*
3357 * The TSC read and the call to get_cpu_tsc_khz() must happen
3358 * on the same CPU.
3359 */
3360 get_cpu();
3361
3362 local_tsc_khz = get_cpu_tsc_khz();
3363
3364 if (local_tsc_khz &&
3365 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3366 local_tsc_khz = 0; /* Fall back to old method */
3367
3368 put_cpu();
3369
3370 /*
3371 * These values must be snapshotted within the seqcount loop.
3372 * After that, it's just mathematics which can happen on any
3373 * CPU at any time.
3374 */
3375 hv_clock.tsc_timestamp = ka->master_cycle_now;
3376 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3377
3378 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3379
3380 /*
3381 * If the conditions were right, and obtaining the wallclock+TSC was
3382 * successful, calculate the KVM clock at the corresponding time and
3383 * subtract one from the other to get the guest's epoch in nanoseconds
3384 * since 1970-01-01.
3385 */
3386 if (local_tsc_khz) {
3387 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3388 &hv_clock.tsc_shift,
3389 &hv_clock.tsc_to_system_mul);
3390 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3391 __pvclock_read_cycles(&hv_clock, host_tsc);
3392 }
3393#endif
3394 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3395}
3396
0061d53d
MT
3397/*
3398 * kvmclock updates which are isolated to a given vcpu, such as
3399 * vcpu->cpu migration, should not allow system_timestamp from
3400 * the rest of the vcpus to remain static. Otherwise ntp frequency
3401 * correction applies to one vcpu's system_timestamp but not
3402 * the others.
3403 *
3404 * So in those cases, request a kvmclock update for all vcpus.
7e44e449
AJ
3405 * We need to rate-limit these requests though, as they can
3406 * considerably slow guests that have a large number of vcpus.
3407 * The time for a remote vcpu to update its kvmclock is bound
3408 * by the delay we use to rate-limit the updates.
0061d53d
MT
3409 */
3410
7e44e449
AJ
3411#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3412
3413static void kvmclock_update_fn(struct work_struct *work)
0061d53d 3414{
46808a4c 3415 unsigned long i;
7e44e449
AJ
3416 struct delayed_work *dwork = to_delayed_work(work);
3417 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3418 kvmclock_update_work);
3419 struct kvm *kvm = container_of(ka, struct kvm, arch);
0061d53d
MT
3420 struct kvm_vcpu *vcpu;
3421
3422 kvm_for_each_vcpu(i, vcpu, kvm) {
105b21bb 3423 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0061d53d
MT
3424 kvm_vcpu_kick(vcpu);
3425 }
3426}
3427
7e44e449
AJ
3428static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3429{
3430 struct kvm *kvm = v->kvm;
3431
105b21bb 3432 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
7e44e449
AJ
3433 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3434 KVMCLOCK_UPDATE_DELAY);
3435}
3436
332967a3
AJ
3437#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3438
3439static void kvmclock_sync_fn(struct work_struct *work)
3440{
3441 struct delayed_work *dwork = to_delayed_work(work);
3442 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3443 kvmclock_sync_work);
3444 struct kvm *kvm = container_of(ka, struct kvm, arch);
3445
3446 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3447 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3448 KVMCLOCK_SYNC_PERIOD);
3449}
3450
281b5278
JW
3451/* These helpers are safe iff @msr is known to be an MCx bank MSR. */
3452static bool is_mci_control_msr(u32 msr)
3453{
3454 return (msr & 3) == 0;
3455}
3456static bool is_mci_status_msr(u32 msr)
3457{
3458 return (msr & 3) == 1;
3459}
3460
191c8137
BP
3461/*
3462 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3463 */
3464static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3465{
3466 /* McStatusWrEn enabled? */
fd706c9b 3467 if (guest_cpuid_is_amd_compatible(vcpu))
191c8137
BP
3468 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3469
3470 return false;
3471}
3472
9ffd986c 3473static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 3474{
890ca9ae
HY
3475 u64 mcg_cap = vcpu->arch.mcg_cap;
3476 unsigned bank_num = mcg_cap & 0xff;
9ffd986c
WL
3477 u32 msr = msr_info->index;
3478 u64 data = msr_info->data;
281b5278 3479 u32 offset, last_msr;
890ca9ae 3480
15c4a640 3481 switch (msr) {
15c4a640 3482 case MSR_IA32_MCG_STATUS:
890ca9ae 3483 vcpu->arch.mcg_status = data;
15c4a640 3484 break;
c7ac679c 3485 case MSR_IA32_MCG_CTL:
44883f01
PB
3486 if (!(mcg_cap & MCG_CTL_P) &&
3487 (data || !msr_info->host_initiated))
890ca9ae
HY
3488 return 1;
3489 if (data != 0 && data != ~(u64)0)
44883f01 3490 return 1;
890ca9ae
HY
3491 vcpu->arch.mcg_ctl = data;
3492 break;
281b5278
JW
3493 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3494 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3495 if (msr > last_msr)
3496 return 1;
191c8137 3497
281b5278
JW
3498 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3499 return 1;
3500 /* An attempt to write a 1 to a reserved bit raises #GP */
3501 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3502 return 1;
3503 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3504 last_msr + 1 - MSR_IA32_MC0_CTL2);
3505 vcpu->arch.mci_ctl2_banks[offset] = data;
3506 break;
3507 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3508 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3509 if (msr > last_msr)
3510 return 1;
3511
3512 /*
3513 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3514 * values are architecturally undefined. But, some Linux
3515 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3516 * issue on AMD K8s, allow bit 10 to be clear when setting all
3517 * other bits in order to avoid an uncaught #GP in the guest.
f5223a33
SC
3518 *
3519 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3520 * single-bit ECC data errors.
281b5278
JW
3521 */
3522 if (is_mci_control_msr(msr) &&
3523 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3524 return 1;
191c8137 3525
281b5278
JW
3526 /*
3527 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3528 * AMD-based CPUs allow non-zero values, but if and only if
3529 * HWCR[McStatusWrEn] is set.
3530 */
3531 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3532 data != 0 && !can_set_mci_status(vcpu))
3533 return 1;
3534
3535 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3536 last_msr + 1 - MSR_IA32_MC0_CTL);
3537 vcpu->arch.mce_banks[offset] = data;
3538 break;
3539 default:
890ca9ae
HY
3540 return 1;
3541 }
3542 return 0;
3543}
3544
2635b5c4
VK
3545static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3546{
3547 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3548
3549 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3550}
3551
344d9588
GN
3552static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3553{
3554 gpa_t gpa = data & ~0x3f;
3555
2635b5c4
VK
3556 /* Bits 4:5 are reserved, Should be zero */
3557 if (data & 0x30)
344d9588
GN
3558 return 1;
3559
66570e96
OU
3560 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3561 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3562 return 1;
3563
3564 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3565 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3566 return 1;
3567
9d3c447c 3568 if (!lapic_in_kernel(vcpu))
d831de17 3569 return data ? 1 : 0;
9d3c447c 3570
2635b5c4 3571 vcpu->arch.apf.msr_en_val = data;
344d9588 3572
2635b5c4 3573 if (!kvm_pv_async_pf_enabled(vcpu)) {
344d9588
GN
3574 kvm_clear_async_pf_completion_queue(vcpu);
3575 kvm_async_pf_hash_reset(vcpu);
3576 return 0;
3577 }
3578
4e335d9e 3579 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
68fd66f1 3580 sizeof(u64)))
344d9588
GN
3581 return 1;
3582
4fa0efb4 3583 vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
52a5c155 3584 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2635b5c4 3585
344d9588 3586 kvm_async_pf_wakeup_all(vcpu);
2635b5c4
VK
3587
3588 return 0;
3589}
3590
3591static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3592{
3593 /* Bits 8-63 are reserved */
3594 if (data >> 8)
3595 return 1;
3596
3597 if (!lapic_in_kernel(vcpu))
3598 return 1;
3599
3600 vcpu->arch.apf.msr_int_val = data;
3601
3602 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3603
344d9588
GN
3604 return 0;
3605}
3606
12f9a48f
GC
3607static void kvmclock_reset(struct kvm_vcpu *vcpu)
3608{
8c82a0b3 3609 kvm_gpc_deactivate(&vcpu->arch.pv_time);
49dedf0d 3610 vcpu->arch.time = 0;
12f9a48f
GC
3611}
3612
7780938c 3613static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
f38a7b75
WL
3614{
3615 ++vcpu->stat.tlb_flush;
89604647 3616 kvm_x86_call(flush_tlb_all)(vcpu);
e94cea09
SC
3617
3618 /* Flushing all ASIDs flushes the current ASID... */
3619 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
f38a7b75
WL
3620}
3621
0baedd79
VK
3622static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3623{
3624 ++vcpu->stat.tlb_flush;
b53e84ee
LJ
3625
3626 if (!tdp_enabled) {
61b05a9f 3627 /*
b53e84ee
LJ
3628 * A TLB flush on behalf of the guest is equivalent to
3629 * INVPCID(all), toggling CR4.PGE, etc., which requires
61b05a9f
LJ
3630 * a forced sync of the shadow page tables. Ensure all the
3631 * roots are synced and the guest TLB in hardware is clean.
b53e84ee 3632 */
61b05a9f
LJ
3633 kvm_mmu_sync_roots(vcpu);
3634 kvm_mmu_sync_prev_roots(vcpu);
b53e84ee
LJ
3635 }
3636
89604647 3637 kvm_x86_call(flush_tlb_guest)(vcpu);
adc43caa
VK
3638
3639 /*
3640 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3641 * grained flushing.
3642 */
0823570f 3643 kvm_hv_vcpu_purge_flush_tlb(vcpu);
0baedd79
VK
3644}
3645
40e5f908
SC
3646
3647static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3648{
3649 ++vcpu->stat.tlb_flush;
89604647 3650 kvm_x86_call(flush_tlb_current)(vcpu);
40e5f908
SC
3651}
3652
3653/*
3654 * Service "local" TLB flush requests, which are specific to the current MMU
3655 * context. In addition to the generic event handling in vcpu_enter_guest(),
3656 * TLB flushes that are targeted at an MMU context also need to be serviced
3657 * prior before nested VM-Enter/VM-Exit.
3658 */
3659void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3660{
3661 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3662 kvm_vcpu_flush_tlb_current(vcpu);
3663
3664 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3665 kvm_vcpu_flush_tlb_guest(vcpu);
3666}
3667EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3668
c9aaa895
GC
3669static void record_steal_time(struct kvm_vcpu *vcpu)
3670{
7e2175eb
DW
3671 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3672 struct kvm_steal_time __user *st;
3673 struct kvm_memslots *slots;
901d3765 3674 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
7e2175eb
DW
3675 u64 steal;
3676 u32 version;
b0431382 3677
30b5c851
DW
3678 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3679 kvm_xen_runstate_set_running(vcpu);
3680 return;
3681 }
3682
c9aaa895
GC
3683 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3684 return;
3685
7e2175eb 3686 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
c9aaa895
GC
3687 return;
3688
7e2175eb
DW
3689 slots = kvm_memslots(vcpu->kvm);
3690
3691 if (unlikely(slots->generation != ghc->generation ||
901d3765 3692 gpa != ghc->gpa ||
7e2175eb 3693 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
7e2175eb
DW
3694 /* We rely on the fact that it fits in a single page. */
3695 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3696
901d3765 3697 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
7e2175eb
DW
3698 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3699 return;
3700 }
3701
3702 st = (struct kvm_steal_time __user *)ghc->hva;
f38a7b75
WL
3703 /*
3704 * Doing a TLB flush here, on the guest's behalf, can avoid
3705 * expensive IPIs.
3706 */
66570e96 3707 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
7e2175eb
DW
3708 u8 st_preempted = 0;
3709 int err = -EFAULT;
3710
3e067fd8
PB
3711 if (!user_access_begin(st, sizeof(*st)))
3712 return;
3713
7e2175eb
DW
3714 asm volatile("1: xchgb %0, %2\n"
3715 "xor %1, %1\n"
3716 "2:\n"
3717 _ASM_EXTABLE_UA(1b, 2b)
964b7aa0
DW
3718 : "+q" (st_preempted),
3719 "+&r" (err),
3720 "+m" (st->preempted));
7e2175eb
DW
3721 if (err)
3722 goto out;
3723
3724 user_access_end();
3725
3726 vcpu->arch.st.preempted = 0;
af3511ff 3727
66570e96 3728 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
af3511ff
LJ
3729 st_preempted & KVM_VCPU_FLUSH_TLB);
3730 if (st_preempted & KVM_VCPU_FLUSH_TLB)
66570e96 3731 kvm_vcpu_flush_tlb_guest(vcpu);
7e2175eb
DW
3732
3733 if (!user_access_begin(st, sizeof(*st)))
3734 goto dirty;
1eff0ada 3735 } else {
3e067fd8
PB
3736 if (!user_access_begin(st, sizeof(*st)))
3737 return;
3738
7e2175eb
DW
3739 unsafe_put_user(0, &st->preempted, out);
3740 vcpu->arch.st.preempted = 0;
66570e96 3741 }
0b9f6c46 3742
7e2175eb
DW
3743 unsafe_get_user(version, &st->version, out);
3744 if (version & 1)
3745 version += 1; /* first time write, random junk */
35f3fae1 3746
7e2175eb
DW
3747 version += 1;
3748 unsafe_put_user(version, &st->version, out);
35f3fae1
WL
3749
3750 smp_wmb();
3751
7e2175eb
DW
3752 unsafe_get_user(steal, &st->steal, out);
3753 steal += current->sched_info.run_delay -
c54cdf14
LC
3754 vcpu->arch.st.last_steal;
3755 vcpu->arch.st.last_steal = current->sched_info.run_delay;
7e2175eb 3756 unsafe_put_user(steal, &st->steal, out);
35f3fae1 3757
7e2175eb
DW
3758 version += 1;
3759 unsafe_put_user(version, &st->version, out);
35f3fae1 3760
7e2175eb
DW
3761 out:
3762 user_access_end();
3763 dirty:
3764 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
c9aaa895
GC
3765}
3766
8fe8ab46 3767int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 3768{
8fe8ab46
WA
3769 u32 msr = msr_info->index;
3770 u64 data = msr_info->data;
5753785f 3771
3617c0ee
DW
3772 /*
3773 * Do not allow host-initiated writes to trigger the Xen hypercall
3774 * page setup; it could incur locking paths which are not expected
3775 * if userspace sets the MSR in an unusual location.
3776 */
bb0978d9 3777 if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3617c0ee 3778 !msr_info->host_initiated)
23200b7a 3779 return kvm_xen_write_hypercall_page(vcpu, data);
1232f8e6 3780
15c4a640 3781 switch (msr) {
2e32b719 3782 case MSR_AMD64_NB_CFG:
2e32b719
BP
3783 case MSR_IA32_UCODE_WRITE:
3784 case MSR_VM_HSAVE_PA:
3785 case MSR_AMD64_PATCH_LOADER:
3786 case MSR_AMD64_BU_CFG2:
405a353a 3787 case MSR_AMD64_DC_CFG:
2770d472 3788 case MSR_AMD64_TW_CFG:
0e1b869f 3789 case MSR_F15H_EX_CFG:
2e32b719
BP
3790 break;
3791
518e7b94
WL
3792 case MSR_IA32_UCODE_REV:
3793 if (msr_info->host_initiated)
3794 vcpu->arch.microcode_version = data;
3795 break;
0cf9135b 3796 case MSR_IA32_ARCH_CAPABILITIES:
a5d56389 3797 if (!msr_info->host_initiated ||
8f2a2775 3798 !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
a5d56389 3799 return KVM_MSR_RET_UNSUPPORTED;
0cf9135b
SC
3800 vcpu->arch.arch_capabilities = data;
3801 break;
686e0f03 3802 case MSR_IA32_PERF_CAPABILITIES:
d75cac36 3803 if (!msr_info->host_initiated ||
8f2a2775 3804 !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
d75cac36
SC
3805 return KVM_MSR_RET_UNSUPPORTED;
3806
686e0f03 3807 if (data & ~kvm_caps.supported_perf_cap)
d574c539
VK
3808 return 1;
3809
3a6de51a
SC
3810 /*
3811 * Note, this is not just a performance optimization! KVM
3812 * disallows changing feature MSRs after the vCPU has run; PMU
3813 * refresh will bug the VM if called after the vCPU has run.
3814 */
3815 if (vcpu->arch.perf_capabilities == data)
3816 break;
3817
d574c539 3818 vcpu->arch.perf_capabilities = data;
17a024a8 3819 kvm_pmu_refresh(vcpu);
3a6de51a 3820 break;
e47d8608
JP
3821 case MSR_IA32_PRED_CMD: {
3822 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3823
3824 if (!msr_info->host_initiated) {
3825 if ((!guest_has_pred_cmd_msr(vcpu)))
3826 return 1;
3827
8f2a2775
SC
3828 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3829 !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
e47d8608
JP
3830 reserved_bits |= PRED_CMD_IBPB;
3831
8f2a2775 3832 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
e47d8608
JP
3833 reserved_bits |= PRED_CMD_SBPB;
3834 }
903358c7 3835
e47d8608
JP
3836 if (!boot_cpu_has(X86_FEATURE_IBPB))
3837 reserved_bits |= PRED_CMD_IBPB;
3838
3839 if (!boot_cpu_has(X86_FEATURE_SBPB))
3840 reserved_bits |= PRED_CMD_SBPB;
3841
3842 if (data & reserved_bits)
903358c7 3843 return 1;
e47d8608 3844
903358c7
SC
3845 if (!data)
3846 break;
3847
78255eb2 3848 wrmsrq(MSR_IA32_PRED_CMD, data);
903358c7 3849 break;
e47d8608 3850 }
da3db168
SC
3851 case MSR_IA32_FLUSH_CMD:
3852 if (!msr_info->host_initiated &&
8f2a2775 3853 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
da3db168
SC
3854 return 1;
3855
3856 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3857 return 1;
3858 if (!data)
3859 break;
3860
78255eb2 3861 wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
da3db168 3862 break;
15c4a640 3863 case MSR_EFER:
11988499 3864 return set_efer(vcpu, msr_info);
8f1589d9
AP
3865 case MSR_K7_HWCR:
3866 data &= ~(u64)0x40; /* ignore flush filter disable */
82494028 3867 data &= ~(u64)0x100; /* ignore ignne emulation enable */
a223c313 3868 data &= ~(u64)0x8; /* ignore TLB cache disable */
191c8137 3869
8b0e00fb
JM
3870 /*
3871 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3872 * through at least v6.6 whine if TscFreqSel is clear,
3873 * depending on F/M/S.
3874 */
3875 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
e76ae527 3876 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
8f1589d9
AP
3877 return 1;
3878 }
598a790f 3879 vcpu->arch.msr_hwcr = data;
15c4a640 3880 break;
f7c6d140
AP
3881 case MSR_FAM10H_MMIO_CONF_BASE:
3882 if (data != 0) {
e76ae527 3883 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
f7c6d140
AP
3884 return 1;
3885 }
15c4a640 3886 break;
34a83dea 3887 case MSR_IA32_CR_PAT:
bc7fe2f0
SC
3888 if (!kvm_pat_valid(data))
3889 return 1;
3890
3891 vcpu->arch.pat = data;
3892 break;
34a83dea
SC
3893 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3894 case MSR_MTRRdefType:
ff53604b 3895 return kvm_mtrr_set_msr(vcpu, msr, data);
15c4a640 3896 case MSR_IA32_APICBASE:
c9155eb0 3897 return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
bf10bd0b 3898 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
0105d1a5 3899 return kvm_x2apic_msr_write(vcpu, msr, data);
09141ec0 3900 case MSR_IA32_TSC_DEADLINE:
a3e06bbe
LJ
3901 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3902 break;
ba904635 3903 case MSR_IA32_TSC_ADJUST:
8f2a2775 3904 if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
ba904635 3905 if (!msr_info->host_initiated) {
d913b904 3906 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
d7add054 3907 adjust_tsc_offset_guest(vcpu, adj);
d9130a2d
ZD
3908 /* Before back to guest, tsc_timestamp must be adjusted
3909 * as well, otherwise guest's percpu pvclock time could jump.
3910 */
3911 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
ba904635
WA
3912 }
3913 vcpu->arch.ia32_tsc_adjust_msr = data;
3914 }
3915 break;
bef6ecca
LX
3916 case MSR_IA32_MISC_ENABLE: {
3917 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
d1055173 3918
9fc22296
SC
3919 if (!msr_info->host_initiated) {
3920 /* RO bits */
3921 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3922 return 1;
3923
3924 /* R bits, i.e. writes are ignored, but don't fault. */
3925 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3926 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3927 }
bef6ecca 3928
511a8556 3929 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
bef6ecca 3930 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
8f2a2775 3931 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
511a8556
WL
3932 return 1;
3933 vcpu->arch.ia32_misc_enable_msr = data;
93da6af3 3934 vcpu->arch.cpuid_dynamic_bits_dirty = true;
511a8556
WL
3935 } else {
3936 vcpu->arch.ia32_misc_enable_msr = data;
3937 }
15c4a640 3938 break;
bef6ecca 3939 }
64d60670 3940 case MSR_IA32_SMBASE:
4b8e1b32 3941 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
64d60670
PB
3942 return 1;
3943 vcpu->arch.smbase = data;
3944 break;
73f624f4
PB
3945 case MSR_IA32_POWER_CTL:
3946 vcpu->arch.msr_ia32_power_ctl = data;
3947 break;
dd259935 3948 case MSR_IA32_TSC:
0c899c25 3949 if (msr_info->host_initiated) {
bf328e22 3950 kvm_synchronize_tsc(vcpu, &data);
adafea11 3951 } else if (!vcpu->arch.guest_tsc_protected) {
9b399dfd 3952 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
0c899c25
PB
3953 adjust_tsc_offset_guest(vcpu, adj);
3954 vcpu->arch.ia32_tsc_adjust_msr += adj;
3955 }
dd259935 3956 break;
864e2ab2
AL
3957 case MSR_IA32_XSS:
3958 if (!msr_info->host_initiated &&
3959 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3960 return 1;
3961 /*
a1bead2a
SC
3962 * KVM supports exposing PT to the guest, but does not support
3963 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3964 * XSAVES/XRSTORS to save/restore PT MSRs.
864e2ab2 3965 */
938c8745 3966 if (data & ~kvm_caps.supported_xss)
864e2ab2
AL
3967 return 1;
3968 vcpu->arch.ia32_xss = data;
93da6af3 3969 vcpu->arch.cpuid_dynamic_bits_dirty = true;
864e2ab2 3970 break;
52797bf9
LA
3971 case MSR_SMI_COUNT:
3972 if (!msr_info->host_initiated)
3973 return 1;
3974 vcpu->arch.smi_count = data;
3975 break;
11c6bffa 3976 case MSR_KVM_WALL_CLOCK_NEW:
66570e96
OU
3977 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3978 return 1;
3979
629b5348
JM
3980 vcpu->kvm->arch.wall_clock = data;
3981 kvm_write_wall_clock(vcpu->kvm, data, 0);
66570e96 3982 break;
18068523 3983 case MSR_KVM_WALL_CLOCK:
66570e96
OU
3984 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3985 return 1;
3986
629b5348
JM
3987 vcpu->kvm->arch.wall_clock = data;
3988 kvm_write_wall_clock(vcpu->kvm, data, 0);
18068523 3989 break;
11c6bffa 3990 case MSR_KVM_SYSTEM_TIME_NEW:
66570e96
OU
3991 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3992 return 1;
3993
5b9bb0eb
OU
3994 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3995 break;
3996 case MSR_KVM_SYSTEM_TIME:
66570e96
OU
3997 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3998 return 1;
3999
4000 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
18068523 4001 break;
344d9588 4002 case MSR_KVM_ASYNC_PF_EN:
66570e96
OU
4003 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4004 return 1;
4005
344d9588
GN
4006 if (kvm_pv_enable_async_pf(vcpu, data))
4007 return 1;
4008 break;
2635b5c4 4009 case MSR_KVM_ASYNC_PF_INT:
66570e96
OU
4010 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4011 return 1;
4012
2635b5c4
VK
4013 if (kvm_pv_enable_async_pf_int(vcpu, data))
4014 return 1;
4015 break;
557a961a 4016 case MSR_KVM_ASYNC_PF_ACK:
0a31df68 4017 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
66570e96 4018 return 1;
557a961a
VK
4019 if (data & 0x1) {
4020 vcpu->arch.apf.pageready_pending = false;
4021 kvm_check_async_pf_completion(vcpu);
4022 }
4023 break;
c9aaa895 4024 case MSR_KVM_STEAL_TIME:
66570e96
OU
4025 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4026 return 1;
c9aaa895
GC
4027
4028 if (unlikely(!sched_info_on()))
4029 return 1;
4030
4031 if (data & KVM_STEAL_RESERVED_MASK)
4032 return 1;
4033
c9aaa895
GC
4034 vcpu->arch.st.msr_val = data;
4035
4036 if (!(data & KVM_MSR_ENABLED))
4037 break;
4038
c9aaa895
GC
4039 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4040
4041 break;
ae7a2a3f 4042 case MSR_KVM_PV_EOI_EN:
66570e96
OU
4043 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4044 return 1;
4045
77c3323f 4046 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
ae7a2a3f
MT
4047 return 1;
4048 break;
c9aaa895 4049
2d5ba19b 4050 case MSR_KVM_POLL_CONTROL:
66570e96
OU
4051 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4052 return 1;
4053
2d5ba19b
MT
4054 /* only enable bit supported */
4055 if (data & (-1ULL << 1))
4056 return 1;
4057
4058 vcpu->arch.msr_kvm_poll_control = data;
4059 break;
4060
890ca9ae
HY
4061 case MSR_IA32_MCG_CTL:
4062 case MSR_IA32_MCG_STATUS:
81760dcc 4063 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
281b5278 4064 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
9ffd986c 4065 return set_msr_mce(vcpu, msr_info);
71db6023 4066
6912ac32
WH
4067 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4068 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
6912ac32
WH
4069 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4070 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 4071 if (kvm_pmu_is_valid_msr(vcpu, msr))
afd80d85 4072 return kvm_pmu_set_msr(vcpu, msr_info);
5753785f 4073
e76ae527
SC
4074 if (data)
4075 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
5753785f 4076 break;
84e0cefa
JS
4077 case MSR_K7_CLK_CTL:
4078 /*
4079 * Ignore all writes to this no longer documented MSR.
4080 * Writes are only relevant for old K7 processors,
4081 * all pre-dating SVM, but a recommended workaround from
4a969980 4082 * AMD for these chips. It is possible to specify the
84e0cefa
JS
4083 * affected processor models on the command line, hence
4084 * the need to ignore the workaround.
4085 */
4086 break;
b4f69df0 4087#ifdef CONFIG_KVM_HYPERV
55cd8e5a 4088 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
4089 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4090 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
4091 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4092 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 4093 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
4094 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4095 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4096 case HV_X64_MSR_TSC_EMULATION_STATUS:
2be1bd3a 4097 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
e7d9513b
AS
4098 return kvm_hv_set_msr_common(vcpu, msr, data,
4099 msr_info->host_initiated);
b4f69df0 4100#endif
91c9c3ed 4101 case MSR_IA32_BBL_CR_CTL3:
4102 /* Drop writes to this legacy MSR -- see rdmsr
4103 * counterpart for further detail.
4104 */
e76ae527 4105 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
91c9c3ed 4106 break;
2b036c6b 4107 case MSR_AMD64_OSVW_ID_LENGTH:
8f2a2775 4108 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
4109 return 1;
4110 vcpu->arch.osvw.length = data;
4111 break;
4112 case MSR_AMD64_OSVW_STATUS:
8f2a2775 4113 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
4114 return 1;
4115 vcpu->arch.osvw.status = data;
4116 break;
db2336a8 4117 case MSR_PLATFORM_INFO:
1ded7a57 4118 if (!msr_info->host_initiated)
db2336a8
KH
4119 return 1;
4120 vcpu->arch.msr_platform_info = data;
4121 break;
4122 case MSR_MISC_FEATURES_ENABLES:
4123 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4124 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4125 !supports_cpuid_fault(vcpu)))
4126 return 1;
4127 vcpu->arch.msr_misc_features_enables = data;
4128 break;
820a6ee9
JL
4129#ifdef CONFIG_X86_64
4130 case MSR_IA32_XFD:
4131 if (!msr_info->host_initiated &&
8f2a2775 4132 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
820a6ee9
JL
4133 return 1;
4134
988896bb 4135 if (data & ~kvm_guest_supported_xfd(vcpu))
820a6ee9
JL
4136 return 1;
4137
4138 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4139 break;
548e8365
JL
4140 case MSR_IA32_XFD_ERR:
4141 if (!msr_info->host_initiated &&
8f2a2775 4142 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
548e8365
JL
4143 return 1;
4144
988896bb 4145 if (data & ~kvm_guest_supported_xfd(vcpu))
548e8365
JL
4146 return 1;
4147
4148 vcpu->arch.guest_fpu.xfd_err = data;
4149 break;
820a6ee9 4150#endif
2de154f5 4151 default:
157fc497
SC
4152 if (kvm_pmu_is_valid_msr(vcpu, msr))
4153 return kvm_pmu_set_msr(vcpu, msr_info);
2de154f5 4154
aaecae7b 4155 return KVM_MSR_RET_UNSUPPORTED;
15c4a640
CO
4156 }
4157 return 0;
4158}
4159EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4160
44883f01 4161static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
15c4a640
CO
4162{
4163 u64 data;
890ca9ae
HY
4164 u64 mcg_cap = vcpu->arch.mcg_cap;
4165 unsigned bank_num = mcg_cap & 0xff;
281b5278 4166 u32 offset, last_msr;
15c4a640
CO
4167
4168 switch (msr) {
15c4a640
CO
4169 case MSR_IA32_P5_MC_ADDR:
4170 case MSR_IA32_P5_MC_TYPE:
890ca9ae
HY
4171 data = 0;
4172 break;
15c4a640 4173 case MSR_IA32_MCG_CAP:
890ca9ae
HY
4174 data = vcpu->arch.mcg_cap;
4175 break;
c7ac679c 4176 case MSR_IA32_MCG_CTL:
44883f01 4177 if (!(mcg_cap & MCG_CTL_P) && !host)
890ca9ae
HY
4178 return 1;
4179 data = vcpu->arch.mcg_ctl;
4180 break;
4181 case MSR_IA32_MCG_STATUS:
4182 data = vcpu->arch.mcg_status;
4183 break;
281b5278
JW
4184 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4185 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4186 if (msr > last_msr)
4187 return 1;
6ec4c5ee 4188
281b5278
JW
4189 if (!(mcg_cap & MCG_CMCI_P) && !host)
4190 return 1;
4191 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4192 last_msr + 1 - MSR_IA32_MC0_CTL2);
4193 data = vcpu->arch.mci_ctl2_banks[offset];
4194 break;
4195 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4196 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4197 if (msr > last_msr)
4198 return 1;
4199
4200 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4201 last_msr + 1 - MSR_IA32_MC0_CTL);
4202 data = vcpu->arch.mce_banks[offset];
4203 break;
4204 default:
890ca9ae
HY
4205 return 1;
4206 }
4207 *pdata = data;
4208 return 0;
4209}
4210
609e36d3 4211int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
890ca9ae 4212{
609e36d3 4213 switch (msr_info->index) {
890ca9ae 4214 case MSR_IA32_PLATFORM_ID:
15c4a640 4215 case MSR_IA32_EBL_CR_POWERON:
b5e2fec0
AG
4216 case MSR_IA32_LASTBRANCHFROMIP:
4217 case MSR_IA32_LASTBRANCHTOIP:
4218 case MSR_IA32_LASTINTFROMIP:
4219 case MSR_IA32_LASTINTTOIP:
059e5c32 4220 case MSR_AMD64_SYSCFG:
3afb1121
PB
4221 case MSR_K8_TSEG_ADDR:
4222 case MSR_K8_TSEG_MASK:
61a6bd67 4223 case MSR_VM_HSAVE_PA:
1fdbd48c 4224 case MSR_K8_INT_PENDING_MSG:
c323c0e5 4225 case MSR_AMD64_NB_CFG:
f7c6d140 4226 case MSR_FAM10H_MMIO_CONF_BASE:
2e32b719 4227 case MSR_AMD64_BU_CFG2:
0c2df2a1 4228 case MSR_IA32_PERF_CTL:
405a353a 4229 case MSR_AMD64_DC_CFG:
2770d472 4230 case MSR_AMD64_TW_CFG:
0e1b869f 4231 case MSR_F15H_EX_CFG:
2ca1a06a
VS
4232 /*
4233 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4234 * limit) MSRs. Just return 0, as we do not want to expose the host
4235 * data here. Do not conditionalize this on CPUID, as KVM does not do
4236 * so for existing CPU-specific MSRs.
4237 */
4238 case MSR_RAPL_POWER_UNIT:
4239 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4240 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4241 case MSR_PKG_ENERGY_STATUS: /* Total package */
4242 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
609e36d3 4243 msr_info->data = 0;
15c4a640 4244 break;
6912ac32
WH
4245 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4246 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4247 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4248 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 4249 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 4250 return kvm_pmu_get_msr(vcpu, msr_info);
609e36d3 4251 msr_info->data = 0;
5753785f 4252 break;
742bc670 4253 case MSR_IA32_UCODE_REV:
518e7b94 4254 msr_info->data = vcpu->arch.microcode_version;
742bc670 4255 break;
0cf9135b 4256 case MSR_IA32_ARCH_CAPABILITIES:
8f2a2775 4257 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
a5d56389 4258 return KVM_MSR_RET_UNSUPPORTED;
0cf9135b
SC
4259 msr_info->data = vcpu->arch.arch_capabilities;
4260 break;
d574c539 4261 case MSR_IA32_PERF_CAPABILITIES:
8f2a2775 4262 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
d75cac36 4263 return KVM_MSR_RET_UNSUPPORTED;
d574c539
VK
4264 msr_info->data = vcpu->arch.perf_capabilities;
4265 break;
73f624f4
PB
4266 case MSR_IA32_POWER_CTL:
4267 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4268 break;
cc5b54dd
ML
4269 case MSR_IA32_TSC: {
4270 /*
4271 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4272 * even when not intercepted. AMD manual doesn't explicitly
4273 * state this but appears to behave the same.
4274 *
ee6fa053 4275 * On userspace reads and writes, however, we unconditionally
c0623f5e 4276 * return L1's TSC value to ensure backwards-compatible
ee6fa053 4277 * behavior for migration.
cc5b54dd 4278 */
fe3eb504 4279 u64 offset, ratio;
cc5b54dd 4280
fe3eb504
IS
4281 if (msr_info->host_initiated) {
4282 offset = vcpu->arch.l1_tsc_offset;
4283 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4284 } else {
4285 offset = vcpu->arch.tsc_offset;
4286 ratio = vcpu->arch.tsc_scaling_ratio;
4287 }
4288
62711e5a 4289 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
dd259935 4290 break;
cc5b54dd 4291 }
34a83dea 4292 case MSR_IA32_CR_PAT:
bc7fe2f0
SC
4293 msr_info->data = vcpu->arch.pat;
4294 break;
9ba075a6 4295 case MSR_MTRRcap:
34a83dea
SC
4296 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4297 case MSR_MTRRdefType:
ff53604b 4298 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
15c4a640 4299 case 0xcd: /* fsb frequency */
609e36d3 4300 msr_info->data = 3;
15c4a640 4301 break;
7b914098
JS
4302 /*
4303 * MSR_EBC_FREQUENCY_ID
4304 * Conservative value valid for even the basic CPU models.
4305 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4306 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4307 * and 266MHz for model 3, or 4. Set Core Clock
4308 * Frequency to System Bus Frequency Ratio to 1 (bits
4309 * 31:24) even though these are only valid for CPU
4310 * models > 2, however guests may end up dividing or
4311 * multiplying by zero otherwise.
4312 */
4313 case MSR_EBC_FREQUENCY_ID:
609e36d3 4314 msr_info->data = 1 << 24;
7b914098 4315 break;
15c4a640 4316 case MSR_IA32_APICBASE:
d91060e3 4317 msr_info->data = vcpu->arch.apic_base;
15c4a640 4318 break;
bf10bd0b 4319 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
609e36d3 4320 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
09141ec0 4321 case MSR_IA32_TSC_DEADLINE:
609e36d3 4322 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
a3e06bbe 4323 break;
ba904635 4324 case MSR_IA32_TSC_ADJUST:
609e36d3 4325 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
ba904635 4326 break;
15c4a640 4327 case MSR_IA32_MISC_ENABLE:
609e36d3 4328 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
15c4a640 4329 break;
64d60670 4330 case MSR_IA32_SMBASE:
4b8e1b32 4331 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
64d60670
PB
4332 return 1;
4333 msr_info->data = vcpu->arch.smbase;
15c4a640 4334 break;
52797bf9
LA
4335 case MSR_SMI_COUNT:
4336 msr_info->data = vcpu->arch.smi_count;
4337 break;
847f0ad8
AG
4338 case MSR_IA32_PERF_STATUS:
4339 /* TSC increment by tick */
609e36d3 4340 msr_info->data = 1000ULL;
847f0ad8 4341 /* CPU multiplier */
b0996ae4 4342 msr_info->data |= (((uint64_t)4ULL) << 40);
847f0ad8 4343 break;
15c4a640 4344 case MSR_EFER:
609e36d3 4345 msr_info->data = vcpu->arch.efer;
15c4a640 4346 break;
18068523 4347 case MSR_KVM_WALL_CLOCK:
1930e5dd
OU
4348 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4349 return 1;
4350
4351 msr_info->data = vcpu->kvm->arch.wall_clock;
4352 break;
11c6bffa 4353 case MSR_KVM_WALL_CLOCK_NEW:
1930e5dd
OU
4354 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4355 return 1;
4356
609e36d3 4357 msr_info->data = vcpu->kvm->arch.wall_clock;
18068523
GOC
4358 break;
4359 case MSR_KVM_SYSTEM_TIME:
1930e5dd
OU
4360 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4361 return 1;
4362
4363 msr_info->data = vcpu->arch.time;
4364 break;
11c6bffa 4365 case MSR_KVM_SYSTEM_TIME_NEW:
1930e5dd
OU
4366 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4367 return 1;
4368
609e36d3 4369 msr_info->data = vcpu->arch.time;
18068523 4370 break;
344d9588 4371 case MSR_KVM_ASYNC_PF_EN:
1930e5dd
OU
4372 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4373 return 1;
4374
2635b5c4
VK
4375 msr_info->data = vcpu->arch.apf.msr_en_val;
4376 break;
4377 case MSR_KVM_ASYNC_PF_INT:
1930e5dd
OU
4378 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4379 return 1;
4380
2635b5c4 4381 msr_info->data = vcpu->arch.apf.msr_int_val;
344d9588 4382 break;
557a961a 4383 case MSR_KVM_ASYNC_PF_ACK:
0a31df68 4384 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
1930e5dd
OU
4385 return 1;
4386
557a961a
VK
4387 msr_info->data = 0;
4388 break;
c9aaa895 4389 case MSR_KVM_STEAL_TIME:
1930e5dd
OU
4390 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4391 return 1;
4392
609e36d3 4393 msr_info->data = vcpu->arch.st.msr_val;
c9aaa895 4394 break;
1d92128f 4395 case MSR_KVM_PV_EOI_EN:
1930e5dd
OU
4396 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4397 return 1;
4398
609e36d3 4399 msr_info->data = vcpu->arch.pv_eoi.msr_val;
1d92128f 4400 break;
2d5ba19b 4401 case MSR_KVM_POLL_CONTROL:
1930e5dd
OU
4402 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4403 return 1;
4404
2d5ba19b
MT
4405 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4406 break;
890ca9ae
HY
4407 case MSR_IA32_P5_MC_ADDR:
4408 case MSR_IA32_P5_MC_TYPE:
4409 case MSR_IA32_MCG_CAP:
4410 case MSR_IA32_MCG_CTL:
4411 case MSR_IA32_MCG_STATUS:
81760dcc 4412 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
281b5278 4413 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
44883f01
PB
4414 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4415 msr_info->host_initiated);
864e2ab2
AL
4416 case MSR_IA32_XSS:
4417 if (!msr_info->host_initiated &&
4418 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4419 return 1;
4420 msr_info->data = vcpu->arch.ia32_xss;
4421 break;
84e0cefa
JS
4422 case MSR_K7_CLK_CTL:
4423 /*
4424 * Provide expected ramp-up count for K7. All other
4425 * are set to zero, indicating minimum divisors for
4426 * every field.
4427 *
4428 * This prevents guest kernels on AMD host with CPU
4429 * type 6, model 8 and higher from exploding due to
4430 * the rdmsr failing.
4431 */
609e36d3 4432 msr_info->data = 0x20000000;
84e0cefa 4433 break;
b4f69df0 4434#ifdef CONFIG_KVM_HYPERV
55cd8e5a 4435 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
4436 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4437 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
4438 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4439 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 4440 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
4441 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4442 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4443 case HV_X64_MSR_TSC_EMULATION_STATUS:
2be1bd3a 4444 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
e83d5887 4445 return kvm_hv_get_msr_common(vcpu,
44883f01
PB
4446 msr_info->index, &msr_info->data,
4447 msr_info->host_initiated);
b4f69df0 4448#endif
91c9c3ed 4449 case MSR_IA32_BBL_CR_CTL3:
4450 /* This legacy MSR exists but isn't fully documented in current
4451 * silicon. It is however accessed by winxp in very narrow
4452 * scenarios where it sets bit #19, itself documented as
4453 * a "reserved" bit. Best effort attempt to source coherent
4454 * read data here should the balance of the register be
4455 * interpreted by the guest:
4456 *
4457 * L2 cache control register 3: 64GB range, 256KB size,
4458 * enabled, latency 0x1, configured
4459 */
609e36d3 4460 msr_info->data = 0xbe702111;
91c9c3ed 4461 break;
2b036c6b 4462 case MSR_AMD64_OSVW_ID_LENGTH:
8f2a2775 4463 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 4464 return 1;
609e36d3 4465 msr_info->data = vcpu->arch.osvw.length;
2b036c6b
BO
4466 break;
4467 case MSR_AMD64_OSVW_STATUS:
8f2a2775 4468 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 4469 return 1;
609e36d3 4470 msr_info->data = vcpu->arch.osvw.status;
2b036c6b 4471 break;
db2336a8 4472 case MSR_PLATFORM_INFO:
6fbbde9a
DS
4473 if (!msr_info->host_initiated &&
4474 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4475 return 1;
db2336a8
KH
4476 msr_info->data = vcpu->arch.msr_platform_info;
4477 break;
4478 case MSR_MISC_FEATURES_ENABLES:
4479 msr_info->data = vcpu->arch.msr_misc_features_enables;
4480 break;
191c8137
BP
4481 case MSR_K7_HWCR:
4482 msr_info->data = vcpu->arch.msr_hwcr;
4483 break;
820a6ee9
JL
4484#ifdef CONFIG_X86_64
4485 case MSR_IA32_XFD:
4486 if (!msr_info->host_initiated &&
8f2a2775 4487 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
820a6ee9
JL
4488 return 1;
4489
4490 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4491 break;
548e8365
JL
4492 case MSR_IA32_XFD_ERR:
4493 if (!msr_info->host_initiated &&
8f2a2775 4494 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
548e8365
JL
4495 return 1;
4496
4497 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4498 break;
820a6ee9 4499#endif
15c4a640 4500 default:
c6702c9d 4501 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 4502 return kvm_pmu_get_msr(vcpu, msr_info);
2de154f5 4503
aaecae7b 4504 return KVM_MSR_RET_UNSUPPORTED;
15c4a640 4505 }
15c4a640
CO
4506 return 0;
4507}
4508EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4509
313a3dc7
CO
4510/*
4511 * Read or write a bunch of msrs. All parameters are kernel addresses.
4512 *
4513 * @return number of msrs set successfully.
4514 */
4515static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4516 struct kvm_msr_entry *entries,
4517 int (*do_msr)(struct kvm_vcpu *vcpu,
4518 unsigned index, u64 *data))
4519{
801e459a 4520 int i;
313a3dc7 4521
313a3dc7
CO
4522 for (i = 0; i < msrs->nmsrs; ++i)
4523 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4524 break;
4525
313a3dc7
CO
4526 return i;
4527}
4528
4529/*
4530 * Read or write a bunch of msrs. Parameters are user addresses.
4531 *
4532 * @return number of msrs set successfully.
4533 */
4534static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4535 int (*do_msr)(struct kvm_vcpu *vcpu,
4536 unsigned index, u64 *data),
4537 int writeback)
4538{
4539 struct kvm_msrs msrs;
4540 struct kvm_msr_entry *entries;
313a3dc7 4541 unsigned size;
e73ba25f 4542 int r;
313a3dc7
CO
4543
4544 r = -EFAULT;
0e96f31e 4545 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
313a3dc7
CO
4546 goto out;
4547
4548 r = -E2BIG;
4549 if (msrs.nmsrs >= MAX_IO_MSRS)
4550 goto out;
4551
313a3dc7 4552 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
ff5c2c03
SL
4553 entries = memdup_user(user_msrs->entries, size);
4554 if (IS_ERR(entries)) {
4555 r = PTR_ERR(entries);
313a3dc7 4556 goto out;
ff5c2c03 4557 }
313a3dc7 4558
e73ba25f 4559 r = __msr_io(vcpu, &msrs, entries, do_msr);
313a3dc7 4560
313a3dc7 4561 if (writeback && copy_to_user(user_msrs->entries, entries, size))
e73ba25f 4562 r = -EFAULT;
313a3dc7 4563
7a73c028 4564 kfree(entries);
313a3dc7
CO
4565out:
4566 return r;
4567}
4568
4d5422ce
WL
4569static inline bool kvm_can_mwait_in_guest(void)
4570{
4571 return boot_cpu_has(X86_FEATURE_MWAIT) &&
8e9b29b6
KA
4572 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4573 boot_cpu_has(X86_FEATURE_ARAT);
4d5422ce
WL
4574}
4575
c829ccd4
SC
4576static u64 kvm_get_allowed_disable_exits(void)
4577{
4578 u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4579
4580 if (!mitigate_smt_rsb) {
4581 r |= KVM_X86_DISABLE_EXITS_HLT |
4582 KVM_X86_DISABLE_EXITS_CSTATE;
4583
4584 if (kvm_can_mwait_in_guest())
4585 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4586 }
4587 return r;
4588}
4589
b4f69df0 4590#ifdef CONFIG_KVM_HYPERV
c21d54f0
VK
4591static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4592 struct kvm_cpuid2 __user *cpuid_arg)
4593{
4594 struct kvm_cpuid2 cpuid;
4595 int r;
4596
4597 r = -EFAULT;
4598 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4599 return r;
4600
4601 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4602 if (r)
4603 return r;
4604
4605 r = -EFAULT;
4606 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4607 return r;
4608
4609 return 0;
4610}
b4f69df0 4611#endif
c21d54f0 4612
89ea60c2
SC
4613static bool kvm_is_vm_type_supported(unsigned long type)
4614{
2a955c4d 4615 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
89ea60c2 4616}
c21d54f0 4617
a476cadf 4618static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
74c1807f
PB
4619{
4620 return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4621}
4622
784aa3d7 4623int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
018d00d2 4624{
4d5422ce 4625 int r = 0;
018d00d2
ZX
4626
4627 switch (ext) {
4628 case KVM_CAP_IRQCHIP:
4629 case KVM_CAP_HLT:
4630 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
018d00d2 4631 case KVM_CAP_SET_TSS_ADDR:
07716717 4632 case KVM_CAP_EXT_CPUID:
9c15bb1d 4633 case KVM_CAP_EXT_EMUL_CPUID:
c8076604 4634 case KVM_CAP_CLOCKSOURCE:
7837699f 4635 case KVM_CAP_PIT:
a28e4f5a 4636 case KVM_CAP_NOP_IO_DELAY:
62d9f0db 4637 case KVM_CAP_MP_STATE:
ed848624 4638 case KVM_CAP_SYNC_MMU:
a355c85c 4639 case KVM_CAP_USER_NMI:
52d939a0 4640 case KVM_CAP_REINJECT_CONTROL:
4925663a 4641 case KVM_CAP_IRQ_INJECT_STATUS:
d34e6b17 4642 case KVM_CAP_IOEVENTFD:
f848a5a8 4643 case KVM_CAP_IOEVENTFD_NO_LENGTH:
c5ff41ce 4644 case KVM_CAP_PIT2:
e9f42757 4645 case KVM_CAP_PIT_STATE2:
b927a3ce 4646 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3cfc3092 4647 case KVM_CAP_VCPU_EVENTS:
b4f69df0 4648#ifdef CONFIG_KVM_HYPERV
55cd8e5a 4649 case KVM_CAP_HYPERV:
10388a07 4650 case KVM_CAP_HYPERV_VAPIC:
c25bc163 4651 case KVM_CAP_HYPERV_SPIN:
b4f69df0 4652 case KVM_CAP_HYPERV_TIME:
5c919412 4653 case KVM_CAP_HYPERV_SYNIC:
efc479e6 4654 case KVM_CAP_HYPERV_SYNIC2:
d3457c87 4655 case KVM_CAP_HYPERV_VP_INDEX:
faeb7833 4656 case KVM_CAP_HYPERV_EVENTFD:
c1aea919 4657 case KVM_CAP_HYPERV_TLBFLUSH:
214ff83d 4658 case KVM_CAP_HYPERV_SEND_IPI:
2bc39970 4659 case KVM_CAP_HYPERV_CPUID:
644f7067 4660 case KVM_CAP_HYPERV_ENFORCE_CPUID:
c21d54f0 4661 case KVM_CAP_SYS_HYPERV_CPUID:
b4f69df0 4662#endif
ab9f4ecb 4663 case KVM_CAP_PCI_SEGMENT:
a1efbe77 4664 case KVM_CAP_DEBUGREGS:
d2be1651 4665 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2d5b5a66 4666 case KVM_CAP_XSAVE:
344d9588 4667 case KVM_CAP_ASYNC_PF:
72de5fa4 4668 case KVM_CAP_ASYNC_PF_INT:
92a1f12d 4669 case KVM_CAP_GET_TSC_KHZ:
1c0b28c2 4670 case KVM_CAP_KVMCLOCK_CTRL:
100943c5 4671 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
defcf51f 4672 case KVM_CAP_TSC_DEADLINE_TIMER:
90de4a18 4673 case KVM_CAP_DISABLE_QUIRKS:
d71ba788 4674 case KVM_CAP_SET_BOOT_CPU_ID:
49df6397 4675 case KVM_CAP_SPLIT_IRQCHIP:
460df4c1 4676 case KVM_CAP_IMMEDIATE_EXIT:
66bb8a06 4677 case KVM_CAP_PMU_EVENT_FILTER:
14329b82 4678 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
801e459a 4679 case KVM_CAP_GET_MSR_FEATURES:
6fbbde9a 4680 case KVM_CAP_MSR_PLATFORM_INFO:
c4f55198 4681 case KVM_CAP_EXCEPTION_PAYLOAD:
ed235117 4682 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
b9b2782c 4683 case KVM_CAP_SET_GUEST_DEBUG:
1aa561b1 4684 case KVM_CAP_LAST_CPU:
1ae09954 4685 case KVM_CAP_X86_USER_SPACE_MSR:
1a155254 4686 case KVM_CAP_X86_MSR_FILTER:
66570e96 4687 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
fe7e9488
SC
4688#ifdef CONFIG_X86_SGX_KVM
4689 case KVM_CAP_SGX_ATTRIBUTE:
4690#endif
54526d1f 4691 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
30d7c5d6 4692 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6dba9403 4693 case KVM_CAP_SREGS2:
19238e75 4694 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
828ca896 4695 case KVM_CAP_VCPU_ATTRIBUTES:
dd6e6312 4696 case KVM_CAP_SYS_ATTRIBUTES:
8a289785 4697 case KVM_CAP_VAPIC:
127770ac 4698 case KVM_CAP_ENABLE_CAP:
084cc29f 4699 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
52882b9c 4700 case KVM_CAP_IRQFD_RESAMPLE:
16f95f3b 4701 case KVM_CAP_MEMORY_FAULT_INFO:
85542adb 4702 case KVM_CAP_X86_GUEST_MODE:
018d00d2
ZX
4703 r = 1;
4704 break;
6e01b760
PB
4705 case KVM_CAP_PRE_FAULT_MEMORY:
4706 r = tdp_enabled;
4707 break;
6fef5185
IY
4708 case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4709 r = APIC_BUS_CYCLE_NS_DEFAULT;
4710 break;
0dbb1123
AK
4711 case KVM_CAP_EXIT_HYPERCALL:
4712 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4713 break;
7e582ccb
ML
4714 case KVM_CAP_SET_GUEST_DEBUG2:
4715 return KVM_GUESTDBG_VALID_MASK;
b59b153d 4716#ifdef CONFIG_KVM_XEN
23200b7a
JM
4717 case KVM_CAP_XEN_HVM:
4718 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
8d4e7e80 4719 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
14243b38 4720 KVM_XEN_HVM_CONFIG_SHARED_INFO |
661a20fa 4721 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
6d722835 4722 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
615451d8
PD
4723 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4724 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
30b5c851 4725 if (sched_info_on())
d8ba8ba4
DW
4726 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4727 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
23200b7a 4728 break;
b59b153d 4729#endif
01643c51 4730 case KVM_CAP_SYNC_REGS:
74c1807f 4731 r = kvm_sync_valid_fields(kvm);
01643c51 4732 break;
e3fd9a93 4733 case KVM_CAP_ADJUST_CLOCK:
c68dc1b5 4734 r = KVM_CLOCK_VALID_FLAGS;
e3fd9a93 4735 break;
4d5422ce 4736 case KVM_CAP_X86_DISABLE_EXITS:
c829ccd4 4737 r = kvm_get_allowed_disable_exits();
668fffa3 4738 break;
6d396b55 4739 case KVM_CAP_X86_SMM:
4b8e1b32
PB
4740 if (!IS_ENABLED(CONFIG_KVM_SMM))
4741 break;
4742
6d396b55
PB
4743 /* SMBASE is usually relocated above 1M on modern chipsets,
4744 * and SMM handlers might indeed rely on 4G segment limits,
4745 * so do not report SMM to be available if real mode is
4746 * emulated via vm86 mode. Still, do not go to great lengths
4747 * to avoid userspace's usage of the feature, because it is a
4748 * fringe case that is not enabled except via specific settings
4749 * of the module parameters.
4750 */
89604647 4751 r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
6d396b55 4752 break;
f725230a 4753 case KVM_CAP_NR_VCPUS:
2845e735 4754 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
8c3ba334
SL
4755 break;
4756 case KVM_CAP_MAX_VCPUS:
f725230a 4757 r = KVM_MAX_VCPUS;
f94f4a97
IY
4758 if (kvm)
4759 r = kvm->max_vcpus;
f725230a 4760 break;
a86cb413 4761 case KVM_CAP_MAX_VCPU_ID:
a1c42dde 4762 r = KVM_MAX_VCPU_IDS;
a86cb413 4763 break;
a68a6a72
MT
4764 case KVM_CAP_PV_MMU: /* obsolete */
4765 r = 0;
2f333bcb 4766 break;
890ca9ae
HY
4767 case KVM_CAP_MCE:
4768 r = KVM_MAX_MCE_BANKS;
4769 break;
2d5b5a66 4770 case KVM_CAP_XCRS:
d366bf7e 4771 r = boot_cpu_has(X86_FEATURE_XSAVE);
2d5b5a66 4772 break;
92a1f12d 4773 case KVM_CAP_TSC_CONTROL:
ffbb61d0 4774 case KVM_CAP_VM_TSC_CONTROL:
938c8745 4775 r = kvm_caps.has_tsc_control;
92a1f12d 4776 break;
37131313
RK
4777 case KVM_CAP_X2APIC_API:
4778 r = KVM_X2APIC_API_VALID_FLAGS;
4779 break;
8fcc4b59 4780 case KVM_CAP_NESTED_STATE:
33b22172
PB
4781 r = kvm_x86_ops.nested_ops->get_state ?
4782 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
8fcc4b59 4783 break;
b4f69df0 4784#ifdef CONFIG_KVM_HYPERV
344c6c80 4785 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
b83237ad 4786 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
5a0165f6
VK
4787 break;
4788 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
33b22172 4789 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
344c6c80 4790 break;
b4f69df0 4791#endif
3edd6839
MG
4792 case KVM_CAP_SMALLER_MAXPHYADDR:
4793 r = (int) allow_smaller_maxphyaddr;
4794 break;
004a0124
AJ
4795 case KVM_CAP_STEAL_TIME:
4796 r = sched_info_on();
4797 break;
fe6b6bc8 4798 case KVM_CAP_X86_BUS_LOCK_EXIT:
938c8745 4799 if (kvm_caps.has_bus_lock_exit)
fe6b6bc8
CQ
4800 r = KVM_BUS_LOCK_DETECTION_OFF |
4801 KVM_BUS_LOCK_DETECTION_EXIT;
4802 else
4803 r = 0;
4804 break;
be50b206 4805 case KVM_CAP_XSAVE2: {
6be3ae45 4806 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
be50b206
GZ
4807 if (r < sizeof(struct kvm_xsave))
4808 r = sizeof(struct kvm_xsave);
4809 break;
1c4dc573 4810 }
ba7bb663
DD
4811 case KVM_CAP_PMU_CAPABILITY:
4812 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4813 break;
6d849191 4814 case KVM_CAP_DISABLE_QUIRKS2:
bd7d5362 4815 r = kvm_caps.supported_quirks;
6d849191 4816 break;
2f4073e0
TX
4817 case KVM_CAP_X86_NOTIFY_VMEXIT:
4818 r = kvm_caps.has_notify_vmexit;
4819 break;
89ea60c2 4820 case KVM_CAP_VM_TYPES:
2a955c4d 4821 r = kvm_caps.supported_vm_types;
89ea60c2 4822 break;
d30d9ee9
TD
4823 case KVM_CAP_READONLY_MEM:
4824 r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
9d4c3040 4825 break;
018d00d2 4826 default:
018d00d2
ZX
4827 break;
4828 }
4829 return r;
56f289a8
SC
4830}
4831
546d714b 4832static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
dd6e6312 4833{
546d714b
PB
4834 if (attr->group) {
4835 if (kvm_x86_ops.dev_get_attr)
89604647 4836 return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
dd6e6312 4837 return -ENXIO;
546d714b 4838 }
dd6e6312 4839
dd6e6312
PB
4840 switch (attr->attr) {
4841 case KVM_X86_XCOMP_GUEST_SUPP:
546d714b 4842 *val = kvm_caps.supported_xcr0;
dd6e6312
PB
4843 return 0;
4844 default:
4845 return -ENXIO;
dd6e6312
PB
4846 }
4847}
4848
546d714b
PB
4849static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4850{
4851 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4852 int r;
4853 u64 val;
4854
4855 r = __kvm_x86_dev_get_attr(attr, &val);
4856 if (r < 0)
4857 return r;
4858
4859 if (put_user(val, uaddr))
4860 return -EFAULT;
4861
4862 return 0;
4863}
4864
dd6e6312
PB
4865static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4866{
546d714b 4867 u64 val;
dd6e6312 4868
546d714b 4869 return __kvm_x86_dev_get_attr(attr, &val);
dd6e6312
PB
4870}
4871
043405e1
CO
4872long kvm_arch_dev_ioctl(struct file *filp,
4873 unsigned int ioctl, unsigned long arg)
4874{
4875 void __user *argp = (void __user *)arg;
4876 long r;
4877
4878 switch (ioctl) {
4879 case KVM_GET_MSR_INDEX_LIST: {
4880 struct kvm_msr_list __user *user_msr_list = argp;
4881 struct kvm_msr_list msr_list;
4882 unsigned n;
4883
4884 r = -EFAULT;
0e96f31e 4885 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
043405e1
CO
4886 goto out;
4887 n = msr_list.nmsrs;
62ef68bb 4888 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
0e96f31e 4889 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
043405e1
CO
4890 goto out;
4891 r = -E2BIG;
e125e7b6 4892 if (n < msr_list.nmsrs)
043405e1
CO
4893 goto out;
4894 r = -EFAULT;
4895 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4896 num_msrs_to_save * sizeof(u32)))
4897 goto out;
e125e7b6 4898 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
043405e1 4899 &emulated_msrs,
62ef68bb 4900 num_emulated_msrs * sizeof(u32)))
043405e1
CO
4901 goto out;
4902 r = 0;
4903 break;
4904 }
9c15bb1d
BP
4905 case KVM_GET_SUPPORTED_CPUID:
4906 case KVM_GET_EMULATED_CPUID: {
674eea0f
AK
4907 struct kvm_cpuid2 __user *cpuid_arg = argp;
4908 struct kvm_cpuid2 cpuid;
4909
4910 r = -EFAULT;
0e96f31e 4911 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
674eea0f 4912 goto out;
9c15bb1d
BP
4913
4914 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4915 ioctl);
674eea0f
AK
4916 if (r)
4917 goto out;
4918
4919 r = -EFAULT;
0e96f31e 4920 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
674eea0f
AK
4921 goto out;
4922 r = 0;
4923 break;
4924 }
cf6c26ec 4925 case KVM_X86_GET_MCE_CAP_SUPPORTED:
890ca9ae 4926 r = -EFAULT;
938c8745
SC
4927 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4928 sizeof(kvm_caps.supported_mce_cap)))
890ca9ae
HY
4929 goto out;
4930 r = 0;
4931 break;
801e459a
TL
4932 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4933 struct kvm_msr_list __user *user_msr_list = argp;
4934 struct kvm_msr_list msr_list;
4935 unsigned int n;
4936
4937 r = -EFAULT;
4938 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4939 goto out;
4940 n = msr_list.nmsrs;
4941 msr_list.nmsrs = num_msr_based_features;
4942 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4943 goto out;
4944 r = -E2BIG;
4945 if (n < msr_list.nmsrs)
4946 goto out;
4947 r = -EFAULT;
4948 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4949 num_msr_based_features * sizeof(u32)))
4950 goto out;
4951 r = 0;
4952 break;
4953 }
4954 case KVM_GET_MSRS:
b848f24b 4955 r = msr_io(NULL, argp, do_get_feature_msr, 1);
801e459a 4956 break;
b4f69df0 4957#ifdef CONFIG_KVM_HYPERV
c21d54f0
VK
4958 case KVM_GET_SUPPORTED_HV_CPUID:
4959 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4960 break;
b4f69df0 4961#endif
dd6e6312
PB
4962 case KVM_GET_DEVICE_ATTR: {
4963 struct kvm_device_attr attr;
4964 r = -EFAULT;
4965 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4966 break;
4967 r = kvm_x86_dev_get_attr(&attr);
4968 break;
4969 }
4970 case KVM_HAS_DEVICE_ATTR: {
4971 struct kvm_device_attr attr;
4972 r = -EFAULT;
4973 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4974 break;
4975 r = kvm_x86_dev_has_attr(&attr);
4976 break;
4977 }
043405e1
CO
4978 default:
4979 r = -EINVAL;
cf6c26ec 4980 break;
043405e1
CO
4981 }
4982out:
4983 return r;
4984}
4985
f5f48ee1
SY
4986static void wbinvd_ipi(void *garbage)
4987{
4988 wbinvd();
4989}
4990
4991static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4992{
e0f0bbc5 4993 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
f5f48ee1
SY
4994}
4995
54a1a24f
SC
4996static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
4997
313a3dc7
CO
4998void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4999{
8fbb696a
SC
5000 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5001
ef2e18ef
SC
5002 vcpu->arch.l1tf_flush_l1d = true;
5003
5004 if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5005 pmu->need_cleanup = true;
5006 kvm_make_request(KVM_REQ_PMU, vcpu);
8fbb696a
SC
5007 }
5008
f5f48ee1
SY
5009 /* Address WBINVD may be executed by guest */
5010 if (need_emulate_wbinvd(vcpu)) {
89604647 5011 if (kvm_x86_call(has_wbinvd_exit)())
f5f48ee1
SY
5012 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5013 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5014 smp_call_function_single(vcpu->cpu,
5015 wbinvd_ipi, NULL, 1);
5016 }
5017
89604647 5018 kvm_x86_call(vcpu_load)(vcpu, cpu);
8f6055cb 5019
54a1a24f
SC
5020 if (vcpu != per_cpu(last_vcpu, cpu)) {
5021 /*
5022 * Flush the branch predictor when switching vCPUs on the same
5023 * physical CPU, as each vCPU needs its own branch prediction
5024 * domain. No IBPB is needed when switching between L1 and L2
5025 * on the same vCPU unless IBRS is advertised to the vCPU; that
5026 * is handled on the nested VM-Exit path.
5027 */
5028 if (static_branch_likely(&switch_vcpu_ibpb))
5029 indirect_branch_prediction_barrier();
5030 per_cpu(last_vcpu, cpu) = vcpu;
5031 }
5032
37486135
BM
5033 /* Save host pkru register if supported */
5034 vcpu->arch.host_pkru = read_pkru();
5035
0dd6a6ed
ZA
5036 /* Apply any externally detected TSC adjustments (due to suspend) */
5037 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5038 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5039 vcpu->arch.tsc_offset_adjustment = 0;
105b21bb 5040 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed 5041 }
8f6055cb 5042
b0c39dc6 5043 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
6f526ec5 5044 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4ea1636b 5045 rdtsc() - vcpu->arch.last_host_tsc;
e48672fa
ZA
5046 if (tsc_delta < 0)
5047 mark_tsc_unstable("KVM discovered backwards TSC");
ce7a058a 5048
b0c39dc6 5049 if (kvm_check_tsc_unstable()) {
9b399dfd 5050 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
b183aa58 5051 vcpu->arch.last_guest_tsc);
a545ab6a 5052 kvm_vcpu_write_tsc_offset(vcpu, offset);
adafea11
IY
5053 if (!vcpu->arch.guest_tsc_protected)
5054 vcpu->arch.tsc_catchup = 1;
c285545f 5055 }
a749e247
PB
5056
5057 if (kvm_lapic_hv_timer_in_use(vcpu))
5058 kvm_lapic_restart_hv_timer(vcpu);
5059
d98d07ca
MT
5060 /*
5061 * On a host with synchronized TSC, there is no need to update
5062 * kvmclock on vcpu->cpu migration
5063 */
5064 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
0061d53d 5065 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
c285545f 5066 if (vcpu->cpu != cpu)
1bd2009e 5067 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
e48672fa 5068 vcpu->cpu = cpu;
6b7d7e76 5069 }
c9aaa895 5070
c9aaa895 5071 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
313a3dc7
CO
5072}
5073
0b9f6c46
PX
5074static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5075{
7e2175eb
DW
5076 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5077 struct kvm_steal_time __user *st;
5078 struct kvm_memslots *slots;
5079 static const u8 preempted = KVM_VCPU_PREEMPTED;
c3c28d24 5080 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
b0431382 5081
6cd88243
PB
5082 /*
5083 * The vCPU can be marked preempted if and only if the VM-Exit was on
5084 * an instruction boundary and will not trigger guest emulation of any
5085 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5086 * when this is true, for example allowing the vCPU to be marked
5087 * preempted if and only if the VM-Exit was due to a host interrupt.
5088 */
5089 if (!vcpu->arch.at_instruction_boundary) {
5090 vcpu->stat.preemption_other++;
5091 return;
5092 }
5093
5094 vcpu->stat.preemption_reported++;
0b9f6c46
PX
5095 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5096 return;
5097
a6bd811f 5098 if (vcpu->arch.st.preempted)
8c6de56a
BO
5099 return;
5100
7e2175eb
DW
5101 /* This happens on process exit */
5102 if (unlikely(current->mm != vcpu->kvm->mm))
9c1a0744 5103 return;
b0431382 5104
7e2175eb
DW
5105 slots = kvm_memslots(vcpu->kvm);
5106
5107 if (unlikely(slots->generation != ghc->generation ||
c3c28d24 5108 gpa != ghc->gpa ||
7e2175eb 5109 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
9c1a0744 5110 return;
b0431382 5111
7e2175eb
DW
5112 st = (struct kvm_steal_time __user *)ghc->hva;
5113 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
0b9f6c46 5114
7e2175eb
DW
5115 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5116 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
0b9f6c46 5117
7e2175eb 5118 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
0b9f6c46
PX
5119}
5120
313a3dc7
CO
5121void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5122{
9c1a0744
WL
5123 int idx;
5124
54aa83c9 5125 if (vcpu->preempted) {
f0e7012c
SC
5126 /*
5127 * Assume protected guests are in-kernel. Inefficient yielding
5128 * due to false positives is preferable to never yielding due
5129 * to false negatives.
5130 */
5131 vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5132 !kvm_x86_call(get_cpl_no_cache)(vcpu);
de63ad4c 5133
54aa83c9
PB
5134 /*
5135 * Take the srcu lock as memslots will be accessed to check the gfn
5136 * cache generation against the memslots generation.
5137 */
5138 idx = srcu_read_lock(&vcpu->kvm->srcu);
5139 if (kvm_xen_msr_enabled(vcpu->kvm))
5140 kvm_xen_runstate_set_preempted(vcpu);
5141 else
5142 kvm_steal_time_set_preempted(vcpu);
5143 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5144 }
30b5c851 5145
89604647 5146 kvm_x86_call(vcpu_put)(vcpu);
4ea1636b 5147 vcpu->arch.last_host_tsc = rdtsc();
313a3dc7
CO
5148}
5149
313a3dc7
CO
5150static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5151 struct kvm_lapic_state *s)
5152{
f65916ae
IY
5153 if (vcpu->arch.apic->guest_apic_protected)
5154 return -EINVAL;
5155
89604647 5156 kvm_x86_call(sync_pir_to_irr)(vcpu);
d62caabb 5157
a92e2543 5158 return kvm_apic_get_state(vcpu, s);
313a3dc7
CO
5159}
5160
5161static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5162 struct kvm_lapic_state *s)
5163{
a92e2543
RK
5164 int r;
5165
f65916ae
IY
5166 if (vcpu->arch.apic->guest_apic_protected)
5167 return -EINVAL;
5168
a92e2543
RK
5169 r = kvm_apic_set_state(vcpu, s);
5170 if (r)
5171 return r;
cb142eb7 5172 update_cr8_intercept(vcpu);
313a3dc7
CO
5173
5174 return 0;
5175}
5176
127a457a
MG
5177static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5178{
71cc849b
PB
5179 /*
5180 * We can accept userspace's request for interrupt injection
5181 * as long as we have a place to store the interrupt number.
5182 * The actual injection will happen when the CPU is able to
5183 * deliver the interrupt.
5184 */
5185 if (kvm_cpu_has_extint(vcpu))
5186 return false;
5187
5188 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
127a457a
MG
5189 return (!lapic_in_kernel(vcpu) ||
5190 kvm_apic_accept_pic_intr(vcpu));
5191}
5192
782d422b
MG
5193static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5194{
fa7a549d
PB
5195 /*
5196 * Do not cause an interrupt window exit if an exception
5197 * is pending or an event needs reinjection; userspace
5198 * might want to inject the interrupt manually using KVM_SET_REGS
5199 * or KVM_SET_SREGS. For that to work, we must be at an
5200 * instruction boundary and with no events half-injected.
5201 */
5202 return (kvm_arch_interrupt_allowed(vcpu) &&
5203 kvm_cpu_accept_dm_intr(vcpu) &&
5204 !kvm_event_needs_reinjection(vcpu) &&
7709aba8 5205 !kvm_is_exception_pending(vcpu));
782d422b
MG
5206}
5207
f77bc6a4
ZX
5208static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5209 struct kvm_interrupt *irq)
5210{
02cdb50f 5211 if (irq->irq >= KVM_NR_INTERRUPTS)
f77bc6a4 5212 return -EINVAL;
1c1a9ce9
SR
5213
5214 if (!irqchip_in_kernel(vcpu->kvm)) {
5215 kvm_queue_interrupt(vcpu, irq->irq, false);
5216 kvm_make_request(KVM_REQ_EVENT, vcpu);
5217 return 0;
5218 }
5219
5220 /*
5221 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5222 * fail for in-kernel 8259.
5223 */
5224 if (pic_in_kernel(vcpu->kvm))
f77bc6a4 5225 return -ENXIO;
f77bc6a4 5226
1c1a9ce9
SR
5227 if (vcpu->arch.pending_external_vector != -1)
5228 return -EEXIST;
f77bc6a4 5229
1c1a9ce9 5230 vcpu->arch.pending_external_vector = irq->irq;
934bf653 5231 kvm_make_request(KVM_REQ_EVENT, vcpu);
f77bc6a4
ZX
5232 return 0;
5233}
5234
c4abb7c9
JK
5235static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5236{
c4abb7c9 5237 kvm_inject_nmi(vcpu);
c4abb7c9
JK
5238
5239 return 0;
5240}
5241
b209749f
AK
5242static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5243 struct kvm_tpr_access_ctl *tac)
5244{
5245 if (tac->flags)
5246 return -EINVAL;
5247 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5248 return 0;
5249}
5250
890ca9ae
HY
5251static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5252 u64 mcg_cap)
5253{
5254 int r;
5255 unsigned bank_num = mcg_cap & 0xff, bank;
5256
5257 r = -EINVAL;
c4e0e4ab 5258 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
890ca9ae 5259 goto out;
938c8745 5260 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
890ca9ae
HY
5261 goto out;
5262 r = 0;
5263 vcpu->arch.mcg_cap = mcg_cap;
5264 /* Init IA32_MCG_CTL to all 1s */
5265 if (mcg_cap & MCG_CTL_P)
5266 vcpu->arch.mcg_ctl = ~(u64)0;
281b5278
JW
5267 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5268 for (bank = 0; bank < bank_num; bank++) {
890ca9ae 5269 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
281b5278
JW
5270 if (mcg_cap & MCG_CMCI_P)
5271 vcpu->arch.mci_ctl2_banks[bank] = 0;
5272 }
f83894b2
SC
5273
5274 kvm_apic_after_set_mcg_cap(vcpu);
c45dcc71 5275
89604647 5276 kvm_x86_call(setup_mce)(vcpu);
890ca9ae
HY
5277out:
5278 return r;
5279}
5280
aebc3ca1
JW
5281/*
5282 * Validate this is an UCNA (uncorrectable no action) error by checking the
5283 * MCG_STATUS and MCi_STATUS registers:
5284 * - none of the bits for Machine Check Exceptions are set
5285 * - both the VAL (valid) and UC (uncorrectable) bits are set
5286 * MCI_STATUS_PCC - Processor Context Corrupted
5287 * MCI_STATUS_S - Signaled as a Machine Check Exception
5288 * MCI_STATUS_AR - Software recoverable Action Required
5289 */
5290static bool is_ucna(struct kvm_x86_mce *mce)
5291{
5292 return !mce->mcg_status &&
5293 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5294 (mce->status & MCI_STATUS_VAL) &&
5295 (mce->status & MCI_STATUS_UC);
5296}
5297
5298static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5299{
5300 u64 mcg_cap = vcpu->arch.mcg_cap;
5301
5302 banks[1] = mce->status;
5303 banks[2] = mce->addr;
5304 banks[3] = mce->misc;
5305 vcpu->arch.mcg_status = mce->mcg_status;
5306
5307 if (!(mcg_cap & MCG_CMCI_P) ||
5308 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5309 return 0;
5310
5311 if (lapic_in_kernel(vcpu))
5312 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5313
5314 return 0;
5315}
5316
890ca9ae
HY
5317static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5318 struct kvm_x86_mce *mce)
5319{
5320 u64 mcg_cap = vcpu->arch.mcg_cap;
5321 unsigned bank_num = mcg_cap & 0xff;
5322 u64 *banks = vcpu->arch.mce_banks;
5323
5324 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5325 return -EINVAL;
aebc3ca1
JW
5326
5327 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5328
5329 if (is_ucna(mce))
5330 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5331
890ca9ae
HY
5332 /*
5333 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5334 * reporting is disabled
5335 */
5336 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5337 vcpu->arch.mcg_ctl != ~(u64)0)
5338 return 0;
890ca9ae
HY
5339 /*
5340 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5341 * reporting is disabled for the bank
5342 */
5343 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5344 return 0;
5345 if (mce->status & MCI_STATUS_UC) {
5346 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
607475cf 5347 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
a8eeb04a 5348 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
890ca9ae
HY
5349 return 0;
5350 }
5351 if (banks[1] & MCI_STATUS_VAL)
5352 mce->status |= MCI_STATUS_OVER;
5353 banks[2] = mce->addr;
5354 banks[3] = mce->misc;
5355 vcpu->arch.mcg_status = mce->mcg_status;
5356 banks[1] = mce->status;
5357 kvm_queue_exception(vcpu, MC_VECTOR);
5358 } else if (!(banks[1] & MCI_STATUS_VAL)
5359 || !(banks[1] & MCI_STATUS_UC)) {
5360 if (banks[1] & MCI_STATUS_VAL)
5361 mce->status |= MCI_STATUS_OVER;
5362 banks[2] = mce->addr;
5363 banks[3] = mce->misc;
5364 banks[1] = mce->status;
5365 } else
5366 banks[1] |= MCI_STATUS_OVER;
5367 return 0;
5368}
5369
3cfc3092
JK
5370static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5371 struct kvm_vcpu_events *events)
5372{
7709aba8 5373 struct kvm_queued_exception *ex;
d4963e31 5374
7460fb4a 5375 process_nmi(vcpu);
59073aaf 5376
cf7316d0 5377#ifdef CONFIG_KVM_SMM
1f7becf1
JZ
5378 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5379 process_smi(vcpu);
cf7316d0 5380#endif
1f7becf1 5381
a06230b6 5382 /*
7709aba8
SC
5383 * KVM's ABI only allows for one exception to be migrated. Luckily,
5384 * the only time there can be two queued exceptions is if there's a
5385 * non-exiting _injected_ exception, and a pending exiting exception.
5386 * In that case, ignore the VM-Exiting exception as it's an extension
5387 * of the injected exception.
5388 */
5389 if (vcpu->arch.exception_vmexit.pending &&
5390 !vcpu->arch.exception.pending &&
5391 !vcpu->arch.exception.injected)
5392 ex = &vcpu->arch.exception_vmexit;
5393 else
5394 ex = &vcpu->arch.exception;
5395
a06230b6 5396 /*
d4963e31
SC
5397 * In guest mode, payload delivery should be deferred if the exception
5398 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5399 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5400 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5401 * propagate the payload and so it cannot be safely deferred. Deliver
5402 * the payload if the capability hasn't been requested.
a06230b6
OU
5403 */
5404 if (!vcpu->kvm->arch.exception_payload_enabled &&
d4963e31
SC
5405 ex->pending && ex->has_payload)
5406 kvm_deliver_exception_payload(vcpu, ex);
a06230b6 5407
85672346
PB
5408 memset(events, 0, sizeof(*events));
5409
664f8e26 5410 /*
59073aaf
JM
5411 * The API doesn't provide the instruction length for software
5412 * exceptions, so don't report them. As long as the guest RIP
5413 * isn't advanced, we should expect to encounter the exception
5414 * again.
664f8e26 5415 */
85672346 5416 if (!kvm_exception_is_soft(ex->vector)) {
d4963e31
SC
5417 events->exception.injected = ex->injected;
5418 events->exception.pending = ex->pending;
59073aaf
JM
5419 /*
5420 * For ABI compatibility, deliberately conflate
5421 * pending and injected exceptions when
5422 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5423 */
5424 if (!vcpu->kvm->arch.exception_payload_enabled)
d4963e31 5425 events->exception.injected |= ex->pending;
59073aaf 5426 }
d4963e31
SC
5427 events->exception.nr = ex->vector;
5428 events->exception.has_error_code = ex->has_error_code;
5429 events->exception.error_code = ex->error_code;
5430 events->exception_has_payload = ex->has_payload;
5431 events->exception_payload = ex->payload;
3cfc3092 5432
03b82a30 5433 events->interrupt.injected =
04140b41 5434 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3cfc3092 5435 events->interrupt.nr = vcpu->arch.interrupt.nr;
89604647 5436 events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
3cfc3092
JK
5437
5438 events->nmi.injected = vcpu->arch.nmi_injected;
fa4c027a 5439 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
89604647 5440 events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
3cfc3092 5441
85672346 5442 /* events->sipi_vector is never valid when reporting to user space */
3cfc3092 5443
a7662aa5 5444#ifdef CONFIG_KVM_SMM
f077825a
PB
5445 events->smi.smm = is_smm(vcpu);
5446 events->smi.pending = vcpu->arch.smi_pending;
5447 events->smi.smm_inside_nmi =
5448 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
a7662aa5 5449#endif
f077825a
PB
5450 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5451
dab4b911 5452 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
f077825a
PB
5453 | KVM_VCPUEVENT_VALID_SHADOW
5454 | KVM_VCPUEVENT_VALID_SMM);
59073aaf
JM
5455 if (vcpu->kvm->arch.exception_payload_enabled)
5456 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
ed235117
CQ
5457 if (vcpu->kvm->arch.triple_fault_event) {
5458 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5459 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5460 }
3cfc3092
JK
5461}
5462
5463static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5464 struct kvm_vcpu_events *events)
5465{
dab4b911 5466 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64 5467 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
f077825a 5468 | KVM_VCPUEVENT_VALID_SHADOW
59073aaf 5469 | KVM_VCPUEVENT_VALID_SMM
ed235117
CQ
5470 | KVM_VCPUEVENT_VALID_PAYLOAD
5471 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
3cfc3092
JK
5472 return -EINVAL;
5473
59073aaf
JM
5474 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5475 if (!vcpu->kvm->arch.exception_payload_enabled)
5476 return -EINVAL;
5477 if (events->exception.pending)
5478 events->exception.injected = 0;
5479 else
5480 events->exception_has_payload = 0;
5481 } else {
5482 events->exception.pending = 0;
5483 events->exception_has_payload = 0;
5484 }
5485
5486 if ((events->exception.injected || events->exception.pending) &&
5487 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
78e546c8
PB
5488 return -EINVAL;
5489
28bf2888
DH
5490 /* INITs are latched while in SMM */
5491 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5492 (events->smi.smm || events->smi.pending) &&
5493 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5494 return -EINVAL;
5495
7460fb4a 5496 process_nmi(vcpu);
7709aba8
SC
5497
5498 /*
5499 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5500 * morph the exception to a VM-Exit if appropriate. Do this only for
5501 * pending exceptions, already-injected exceptions are not subject to
5502 * intercpetion. Note, userspace that conflates pending and injected
5503 * is hosed, and will incorrectly convert an injected exception into a
5504 * pending exception, which in turn may cause a spurious VM-Exit.
5505 */
5506 vcpu->arch.exception_from_userspace = events->exception.pending;
5507
5508 vcpu->arch.exception_vmexit.pending = false;
5509
59073aaf
JM
5510 vcpu->arch.exception.injected = events->exception.injected;
5511 vcpu->arch.exception.pending = events->exception.pending;
d4963e31 5512 vcpu->arch.exception.vector = events->exception.nr;
3cfc3092
JK
5513 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5514 vcpu->arch.exception.error_code = events->exception.error_code;
59073aaf
JM
5515 vcpu->arch.exception.has_payload = events->exception_has_payload;
5516 vcpu->arch.exception.payload = events->exception_payload;
3cfc3092 5517
04140b41 5518 vcpu->arch.interrupt.injected = events->interrupt.injected;
3cfc3092
JK
5519 vcpu->arch.interrupt.nr = events->interrupt.nr;
5520 vcpu->arch.interrupt.soft = events->interrupt.soft;
48005f64 5521 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
89604647
WW
5522 kvm_x86_call(set_interrupt_shadow)(vcpu,
5523 events->interrupt.shadow);
3cfc3092
JK
5524
5525 vcpu->arch.nmi_injected = events->nmi.injected;
ab2ee212 5526 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
bdedff26
SC
5527 vcpu->arch.nmi_pending = 0;
5528 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
6231c9e1
PP
5529 if (events->nmi.pending)
5530 kvm_make_request(KVM_REQ_NMI, vcpu);
ab2ee212 5531 }
89604647 5532 kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
3cfc3092 5533
66450a21 5534 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
bce87cce 5535 lapic_in_kernel(vcpu))
66450a21 5536 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3cfc3092 5537
f077825a 5538 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4b8e1b32 5539#ifdef CONFIG_KVM_SMM
f7e57078 5540 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
f9697df2 5541 kvm_leave_nested(vcpu);
dc87275f 5542 kvm_smm_changed(vcpu, events->smi.smm);
f7e57078 5543 }
6ef4e07e 5544
f077825a 5545 vcpu->arch.smi_pending = events->smi.pending;
f4ef1910
WL
5546
5547 if (events->smi.smm) {
5548 if (events->smi.smm_inside_nmi)
5549 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
f077825a 5550 else
f4ef1910 5551 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
ff90afa7
LA
5552 }
5553
4b8e1b32
PB
5554#else
5555 if (events->smi.smm || events->smi.pending ||
5556 events->smi.smm_inside_nmi)
5557 return -EINVAL;
5558#endif
5559
ff90afa7
LA
5560 if (lapic_in_kernel(vcpu)) {
5561 if (events->smi.latched_init)
5562 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5563 else
5564 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
f077825a
PB
5565 }
5566 }
5567
ed235117
CQ
5568 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5569 if (!vcpu->kvm->arch.triple_fault_event)
5570 return -EINVAL;
5571 if (events->triple_fault.pending)
5572 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5573 else
5574 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5575 }
5576
3842d135
AK
5577 kvm_make_request(KVM_REQ_EVENT, vcpu);
5578
3cfc3092
JK
5579 return 0;
5580}
5581
517987e3
PB
5582static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5583 struct kvm_debugregs *dbgregs)
a1efbe77 5584{
e1dda3af 5585 unsigned int i;
73aaf249 5586
517987e3
PB
5587 if (vcpu->kvm->arch.has_protected_state &&
5588 vcpu->arch.guest_state_protected)
5589 return -EINVAL;
5590
2c10b614 5591 memset(dbgregs, 0, sizeof(*dbgregs));
e1dda3af
MK
5592
5593 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5594 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5595 dbgregs->db[i] = vcpu->arch.db[i];
5596
2a5f091c 5597 dbgregs->dr6 = vcpu->arch.dr6;
a1efbe77 5598 dbgregs->dr7 = vcpu->arch.dr7;
517987e3 5599 return 0;
a1efbe77
JK
5600}
5601
5602static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5603 struct kvm_debugregs *dbgregs)
5604{
e1dda3af
MK
5605 unsigned int i;
5606
517987e3
PB
5607 if (vcpu->kvm->arch.has_protected_state &&
5608 vcpu->arch.guest_state_protected)
5609 return -EINVAL;
5610
a1efbe77
JK
5611 if (dbgregs->flags)
5612 return -EINVAL;
5613
fd238002 5614 if (!kvm_dr6_valid(dbgregs->dr6))
d14bdb55 5615 return -EINVAL;
fd238002 5616 if (!kvm_dr7_valid(dbgregs->dr7))
d14bdb55
PB
5617 return -EINVAL;
5618
e1dda3af
MK
5619 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5620 vcpu->arch.db[i] = dbgregs->db[i];
5621
ae561ede 5622 kvm_update_dr0123(vcpu);
a1efbe77
JK
5623 vcpu->arch.dr6 = dbgregs->dr6;
5624 vcpu->arch.dr7 = dbgregs->dr7;
9926c9fd 5625 kvm_update_dr7(vcpu);
a1efbe77 5626
a1efbe77
JK
5627 return 0;
5628}
5629
18164f66 5630
517987e3
PB
5631static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5632 u8 *state, unsigned int size)
2d5b5a66 5633{
8647c52e
SC
5634 /*
5635 * Only copy state for features that are enabled for the guest. The
5636 * state itself isn't problematic, but setting bits in the header for
5637 * features that are supported in *this* host but not exposed to the
5638 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5639 * compatible host without the features that are NOT exposed to the
5640 * guest.
5641 *
5642 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5643 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5644 * supported by the host.
5645 */
5646 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5647 XFEATURE_MASK_FPSSE;
5648
d69c1382 5649 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
517987e3 5650 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
ed02b213 5651
18164f66 5652 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
8647c52e 5653 supported_xcr0, vcpu->arch.pkru);
517987e3 5654 return 0;
2d5b5a66
SY
5655}
5656
517987e3
PB
5657static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5658 struct kvm_xsave *guest_xsave)
be50b206 5659{
517987e3
PB
5660 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5661 sizeof(guest_xsave->region));
be50b206
GZ
5662}
5663
2d5b5a66
SY
5664static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5665 struct kvm_xsave *guest_xsave)
5666{
d69c1382 5667 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
517987e3 5668 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
ed02b213 5669
d69c1382
TG
5670 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5671 guest_xsave->region,
938c8745
SC
5672 kvm_caps.supported_xcr0,
5673 &vcpu->arch.pkru);
2d5b5a66
SY
5674}
5675
517987e3
PB
5676static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5677 struct kvm_xcrs *guest_xcrs)
2d5b5a66 5678{
517987e3
PB
5679 if (vcpu->kvm->arch.has_protected_state &&
5680 vcpu->arch.guest_state_protected)
5681 return -EINVAL;
5682
d366bf7e 5683 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
2d5b5a66 5684 guest_xcrs->nr_xcrs = 0;
517987e3 5685 return 0;
2d5b5a66
SY
5686 }
5687
5688 guest_xcrs->nr_xcrs = 1;
5689 guest_xcrs->flags = 0;
5690 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5691 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
517987e3 5692 return 0;
2d5b5a66
SY
5693}
5694
5695static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5696 struct kvm_xcrs *guest_xcrs)
5697{
5698 int i, r = 0;
5699
517987e3
PB
5700 if (vcpu->kvm->arch.has_protected_state &&
5701 vcpu->arch.guest_state_protected)
5702 return -EINVAL;
5703
d366bf7e 5704 if (!boot_cpu_has(X86_FEATURE_XSAVE))
2d5b5a66
SY
5705 return -EINVAL;
5706
5707 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5708 return -EINVAL;
5709
5710 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5711 /* Only support XCR0 currently */
c67a04cb 5712 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
2d5b5a66 5713 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
c67a04cb 5714 guest_xcrs->xcrs[i].value);
2d5b5a66
SY
5715 break;
5716 }
5717 if (r)
5718 r = -EINVAL;
5719 return r;
5720}
5721
1c0b28c2
EM
5722/*
5723 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5724 * stopped by the hypervisor. This function will be called from the host only.
5725 * EINVAL is returned when the host attempts to set the flag for a guest that
5726 * does not support pv clocks.
5727 */
5728static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5729{
916d3608 5730 if (!vcpu->arch.pv_time.active)
1c0b28c2 5731 return -EINVAL;
51d59c6b 5732 vcpu->arch.pvclock_set_guest_stopped_request = true;
1c0b28c2
EM
5733 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5734 return 0;
5735}
5736
828ca896
OU
5737static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5738 struct kvm_device_attr *attr)
5739{
5740 int r;
5741
5742 switch (attr->attr) {
5743 case KVM_VCPU_TSC_OFFSET:
5744 r = 0;
5745 break;
5746 default:
5747 r = -ENXIO;
5748 }
5749
5750 return r;
5751}
5752
5753static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5754 struct kvm_device_attr *attr)
5755{
8d2aec3b 5756 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
828ca896
OU
5757 int r;
5758
828ca896
OU
5759 switch (attr->attr) {
5760 case KVM_VCPU_TSC_OFFSET:
5761 r = -EFAULT;
5762 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5763 break;
5764 r = 0;
5765 break;
5766 default:
5767 r = -ENXIO;
5768 }
5769
5770 return r;
5771}
5772
5773static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5774 struct kvm_device_attr *attr)
5775{
8d2aec3b 5776 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
828ca896
OU
5777 struct kvm *kvm = vcpu->kvm;
5778 int r;
5779
828ca896
OU
5780 switch (attr->attr) {
5781 case KVM_VCPU_TSC_OFFSET: {
5782 u64 offset, tsc, ns;
5783 unsigned long flags;
5784 bool matched;
5785
5786 r = -EFAULT;
5787 if (get_user(offset, uaddr))
5788 break;
5789
5790 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5791
5792 matched = (vcpu->arch.virtual_tsc_khz &&
5793 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5794 kvm->arch.last_tsc_offset == offset);
5795
62711e5a 5796 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
828ca896
OU
5797 ns = get_kvmclock_base_ns();
5798
5f3b30b2 5799 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
828ca896
OU
5800 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5801
5802 r = 0;
5803 break;
5804 }
5805 default:
5806 r = -ENXIO;
5807 }
5808
5809 return r;
5810}
5811
5812static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5813 unsigned int ioctl,
5814 void __user *argp)
5815{
5816 struct kvm_device_attr attr;
5817 int r;
5818
5819 if (copy_from_user(&attr, argp, sizeof(attr)))
5820 return -EFAULT;
5821
5822 if (attr.group != KVM_VCPU_TSC_CTRL)
5823 return -ENXIO;
5824
5825 switch (ioctl) {
5826 case KVM_HAS_DEVICE_ATTR:
5827 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5828 break;
5829 case KVM_GET_DEVICE_ATTR:
5830 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5831 break;
5832 case KVM_SET_DEVICE_ATTR:
5833 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5834 break;
5835 }
5836
5837 return r;
5838}
5839
5c919412
AS
5840static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5841 struct kvm_enable_cap *cap)
5842{
5843 if (cap->flags)
5844 return -EINVAL;
5845
5846 switch (cap->cap) {
b4f69df0 5847#ifdef CONFIG_KVM_HYPERV
efc479e6
RK
5848 case KVM_CAP_HYPERV_SYNIC2:
5849 if (cap->args[0])
5850 return -EINVAL;
df561f66 5851 fallthrough;
b2869f28 5852
5c919412 5853 case KVM_CAP_HYPERV_SYNIC:
546d87e5
WL
5854 if (!irqchip_in_kernel(vcpu->kvm))
5855 return -EINVAL;
efc479e6
RK
5856 return kvm_hv_activate_synic(vcpu, cap->cap ==
5857 KVM_CAP_HYPERV_SYNIC2);
57b119da 5858 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
b4f69df0
VK
5859 {
5860 int r;
5861 uint16_t vmcs_version;
5862 void __user *user_ptr;
5863
5864 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5865 return -ENOTTY;
5866 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5867 if (!r) {
5868 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5869 if (copy_to_user(user_ptr, &vmcs_version,
5870 sizeof(vmcs_version)))
5871 r = -EFAULT;
5872 }
5873 return r;
57b119da 5874 }
344c6c80 5875 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
b83237ad 5876 if (!kvm_x86_ops.enable_l2_tlb_flush)
344c6c80
TL
5877 return -ENOTTY;
5878
89604647 5879 return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
57b119da 5880
644f7067
VK
5881 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5882 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
b4f69df0 5883#endif
644f7067 5884
66570e96
OU
5885 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5886 vcpu->arch.pv_cpuid.enforce = cap->args[0];
66570e96 5887 return 0;
5c919412
AS
5888 default:
5889 return -EINVAL;
5890 }
5891}
5892
313a3dc7
CO
5893long kvm_arch_vcpu_ioctl(struct file *filp,
5894 unsigned int ioctl, unsigned long arg)
5895{
5896 struct kvm_vcpu *vcpu = filp->private_data;
5897 void __user *argp = (void __user *)arg;
5898 int r;
d1ac91d8 5899 union {
6dba9403 5900 struct kvm_sregs2 *sregs2;
d1ac91d8
AK
5901 struct kvm_lapic_state *lapic;
5902 struct kvm_xsave *xsave;
5903 struct kvm_xcrs *xcrs;
5904 void *buffer;
5905 } u;
5906
9b062471
CD
5907 vcpu_load(vcpu);
5908
d1ac91d8 5909 u.buffer = NULL;
313a3dc7
CO
5910 switch (ioctl) {
5911 case KVM_GET_LAPIC: {
2204ae3c 5912 r = -EINVAL;
bce87cce 5913 if (!lapic_in_kernel(vcpu))
2204ae3c 5914 goto out;
dd103407 5915 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
313a3dc7 5916
b772ff36 5917 r = -ENOMEM;
d1ac91d8 5918 if (!u.lapic)
b772ff36 5919 goto out;
d1ac91d8 5920 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
313a3dc7
CO
5921 if (r)
5922 goto out;
5923 r = -EFAULT;
d1ac91d8 5924 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
313a3dc7
CO
5925 goto out;
5926 r = 0;
5927 break;
5928 }
5929 case KVM_SET_LAPIC: {
2204ae3c 5930 r = -EINVAL;
bce87cce 5931 if (!lapic_in_kernel(vcpu))
2204ae3c 5932 goto out;
ff5c2c03 5933 u.lapic = memdup_user(argp, sizeof(*u.lapic));
9b062471
CD
5934 if (IS_ERR(u.lapic)) {
5935 r = PTR_ERR(u.lapic);
5936 goto out_nofree;
5937 }
ff5c2c03 5938
d1ac91d8 5939 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
313a3dc7
CO
5940 break;
5941 }
f77bc6a4
ZX
5942 case KVM_INTERRUPT: {
5943 struct kvm_interrupt irq;
5944
5945 r = -EFAULT;
0e96f31e 5946 if (copy_from_user(&irq, argp, sizeof(irq)))
f77bc6a4
ZX
5947 goto out;
5948 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
f77bc6a4
ZX
5949 break;
5950 }
c4abb7c9
JK
5951 case KVM_NMI: {
5952 r = kvm_vcpu_ioctl_nmi(vcpu);
c4abb7c9
JK
5953 break;
5954 }
f077825a 5955 case KVM_SMI: {
b0b42197 5956 r = kvm_inject_smi(vcpu);
f077825a
PB
5957 break;
5958 }
313a3dc7
CO
5959 case KVM_SET_CPUID: {
5960 struct kvm_cpuid __user *cpuid_arg = argp;
5961 struct kvm_cpuid cpuid;
5962
5963 r = -EFAULT;
0e96f31e 5964 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
313a3dc7
CO
5965 goto out;
5966 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
313a3dc7
CO
5967 break;
5968 }
07716717
DK
5969 case KVM_SET_CPUID2: {
5970 struct kvm_cpuid2 __user *cpuid_arg = argp;
5971 struct kvm_cpuid2 cpuid;
5972
5973 r = -EFAULT;
0e96f31e 5974 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
5975 goto out;
5976 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
19355475 5977 cpuid_arg->entries);
07716717
DK
5978 break;
5979 }
5980 case KVM_GET_CPUID2: {
5981 struct kvm_cpuid2 __user *cpuid_arg = argp;
5982 struct kvm_cpuid2 cpuid;
5983
5984 r = -EFAULT;
0e96f31e 5985 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
5986 goto out;
5987 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
19355475 5988 cpuid_arg->entries);
07716717
DK
5989 if (r)
5990 goto out;
5991 r = -EFAULT;
0e96f31e 5992 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
07716717
DK
5993 goto out;
5994 r = 0;
5995 break;
5996 }
801e459a
TL
5997 case KVM_GET_MSRS: {
5998 int idx = srcu_read_lock(&vcpu->kvm->srcu);
609e36d3 5999 r = msr_io(vcpu, argp, do_get_msr, 1);
801e459a 6000 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 6001 break;
801e459a
TL
6002 }
6003 case KVM_SET_MSRS: {
6004 int idx = srcu_read_lock(&vcpu->kvm->srcu);
313a3dc7 6005 r = msr_io(vcpu, argp, do_set_msr, 0);
801e459a 6006 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 6007 break;
801e459a 6008 }
b209749f
AK
6009 case KVM_TPR_ACCESS_REPORTING: {
6010 struct kvm_tpr_access_ctl tac;
6011
6012 r = -EFAULT;
0e96f31e 6013 if (copy_from_user(&tac, argp, sizeof(tac)))
b209749f
AK
6014 goto out;
6015 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6016 if (r)
6017 goto out;
6018 r = -EFAULT;
0e96f31e 6019 if (copy_to_user(argp, &tac, sizeof(tac)))
b209749f
AK
6020 goto out;
6021 r = 0;
6022 break;
6023 };
b93463aa
AK
6024 case KVM_SET_VAPIC_ADDR: {
6025 struct kvm_vapic_addr va;
7301d6ab 6026 int idx;
b93463aa
AK
6027
6028 r = -EINVAL;
35754c98 6029 if (!lapic_in_kernel(vcpu))
b93463aa
AK
6030 goto out;
6031 r = -EFAULT;
0e96f31e 6032 if (copy_from_user(&va, argp, sizeof(va)))
b93463aa 6033 goto out;
7301d6ab 6034 idx = srcu_read_lock(&vcpu->kvm->srcu);
fda4e2e8 6035 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
7301d6ab 6036 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b93463aa
AK
6037 break;
6038 }
890ca9ae
HY
6039 case KVM_X86_SETUP_MCE: {
6040 u64 mcg_cap;
6041
6042 r = -EFAULT;
0e96f31e 6043 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
890ca9ae
HY
6044 goto out;
6045 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6046 break;
6047 }
6048 case KVM_X86_SET_MCE: {
6049 struct kvm_x86_mce mce;
6050
6051 r = -EFAULT;
0e96f31e 6052 if (copy_from_user(&mce, argp, sizeof(mce)))
890ca9ae
HY
6053 goto out;
6054 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6055 break;
6056 }
3cfc3092
JK
6057 case KVM_GET_VCPU_EVENTS: {
6058 struct kvm_vcpu_events events;
6059
6060 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6061
6062 r = -EFAULT;
6063 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6064 break;
6065 r = 0;
6066 break;
6067 }
6068 case KVM_SET_VCPU_EVENTS: {
6069 struct kvm_vcpu_events events;
6070
6071 r = -EFAULT;
6072 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6073 break;
6074
4bcdd831 6075 kvm_vcpu_srcu_read_lock(vcpu);
3cfc3092 6076 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4bcdd831 6077 kvm_vcpu_srcu_read_unlock(vcpu);
3cfc3092
JK
6078 break;
6079 }
a1efbe77
JK
6080 case KVM_GET_DEBUGREGS: {
6081 struct kvm_debugregs dbgregs;
6082
517987e3
PB
6083 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6084 if (r < 0)
6085 break;
a1efbe77
JK
6086
6087 r = -EFAULT;
6088 if (copy_to_user(argp, &dbgregs,
6089 sizeof(struct kvm_debugregs)))
6090 break;
6091 r = 0;
6092 break;
6093 }
6094 case KVM_SET_DEBUGREGS: {
6095 struct kvm_debugregs dbgregs;
6096
6097 r = -EFAULT;
6098 if (copy_from_user(&dbgregs, argp,
6099 sizeof(struct kvm_debugregs)))
6100 break;
6101
6102 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6103 break;
6104 }
2d5b5a66 6105 case KVM_GET_XSAVE: {
be50b206
GZ
6106 r = -EINVAL;
6107 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6108 break;
6109
dd103407 6110 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2d5b5a66 6111 r = -ENOMEM;
d1ac91d8 6112 if (!u.xsave)
2d5b5a66
SY
6113 break;
6114
517987e3
PB
6115 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6116 if (r < 0)
6117 break;
2d5b5a66
SY
6118
6119 r = -EFAULT;
d1ac91d8 6120 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2d5b5a66
SY
6121 break;
6122 r = 0;
6123 break;
6124 }
6125 case KVM_SET_XSAVE: {
be50b206
GZ
6126 int size = vcpu->arch.guest_fpu.uabi_size;
6127
6128 u.xsave = memdup_user(argp, size);
9b062471
CD
6129 if (IS_ERR(u.xsave)) {
6130 r = PTR_ERR(u.xsave);
6131 goto out_nofree;
6132 }
2d5b5a66 6133
d1ac91d8 6134 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2d5b5a66
SY
6135 break;
6136 }
be50b206
GZ
6137
6138 case KVM_GET_XSAVE2: {
6139 int size = vcpu->arch.guest_fpu.uabi_size;
6140
dd103407 6141 u.xsave = kzalloc(size, GFP_KERNEL);
be50b206
GZ
6142 r = -ENOMEM;
6143 if (!u.xsave)
6144 break;
6145
517987e3
PB
6146 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6147 if (r < 0)
6148 break;
be50b206
GZ
6149
6150 r = -EFAULT;
6151 if (copy_to_user(argp, u.xsave, size))
6152 break;
6153
6154 r = 0;
6155 break;
6156 }
6157
2d5b5a66 6158 case KVM_GET_XCRS: {
dd103407 6159 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2d5b5a66 6160 r = -ENOMEM;
d1ac91d8 6161 if (!u.xcrs)
2d5b5a66
SY
6162 break;
6163
517987e3
PB
6164 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6165 if (r < 0)
6166 break;
2d5b5a66
SY
6167
6168 r = -EFAULT;
d1ac91d8 6169 if (copy_to_user(argp, u.xcrs,
2d5b5a66
SY
6170 sizeof(struct kvm_xcrs)))
6171 break;
6172 r = 0;
6173 break;
6174 }
6175 case KVM_SET_XCRS: {
ff5c2c03 6176 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
9b062471
CD
6177 if (IS_ERR(u.xcrs)) {
6178 r = PTR_ERR(u.xcrs);
6179 goto out_nofree;
6180 }
2d5b5a66 6181
d1ac91d8 6182 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
6183 break;
6184 }
92a1f12d
JR
6185 case KVM_SET_TSC_KHZ: {
6186 u32 user_tsc_khz;
6187
6188 r = -EINVAL;
92a1f12d
JR
6189 user_tsc_khz = (u32)arg;
6190
938c8745
SC
6191 if (kvm_caps.has_tsc_control &&
6192 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
92a1f12d
JR
6193 goto out;
6194
cc578287
ZA
6195 if (user_tsc_khz == 0)
6196 user_tsc_khz = tsc_khz;
6197
381d585c
HZ
6198 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6199 r = 0;
92a1f12d 6200
92a1f12d
JR
6201 goto out;
6202 }
6203 case KVM_GET_TSC_KHZ: {
cc578287 6204 r = vcpu->arch.virtual_tsc_khz;
92a1f12d
JR
6205 goto out;
6206 }
1c0b28c2
EM
6207 case KVM_KVMCLOCK_CTRL: {
6208 r = kvm_set_guest_paused(vcpu);
6209 goto out;
6210 }
5c919412
AS
6211 case KVM_ENABLE_CAP: {
6212 struct kvm_enable_cap cap;
6213
6214 r = -EFAULT;
6215 if (copy_from_user(&cap, argp, sizeof(cap)))
6216 goto out;
6217 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6218 break;
6219 }
8fcc4b59
JM
6220 case KVM_GET_NESTED_STATE: {
6221 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6222 u32 user_data_size;
6223
6224 r = -EINVAL;
33b22172 6225 if (!kvm_x86_ops.nested_ops->get_state)
8fcc4b59
JM
6226 break;
6227
6228 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
26b471c7 6229 r = -EFAULT;
8fcc4b59 6230 if (get_user(user_data_size, &user_kvm_nested_state->size))
26b471c7 6231 break;
8fcc4b59 6232
33b22172
PB
6233 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6234 user_data_size);
8fcc4b59 6235 if (r < 0)
26b471c7 6236 break;
8fcc4b59
JM
6237
6238 if (r > user_data_size) {
6239 if (put_user(r, &user_kvm_nested_state->size))
26b471c7
LA
6240 r = -EFAULT;
6241 else
6242 r = -E2BIG;
6243 break;
8fcc4b59 6244 }
26b471c7 6245
8fcc4b59
JM
6246 r = 0;
6247 break;
6248 }
6249 case KVM_SET_NESTED_STATE: {
6250 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6251 struct kvm_nested_state kvm_state;
ad5996d9 6252 int idx;
8fcc4b59
JM
6253
6254 r = -EINVAL;
33b22172 6255 if (!kvm_x86_ops.nested_ops->set_state)
8fcc4b59
JM
6256 break;
6257
26b471c7 6258 r = -EFAULT;
8fcc4b59 6259 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
26b471c7 6260 break;
8fcc4b59 6261
26b471c7 6262 r = -EINVAL;
8fcc4b59 6263 if (kvm_state.size < sizeof(kvm_state))
26b471c7 6264 break;
8fcc4b59
JM
6265
6266 if (kvm_state.flags &
8cab6507 6267 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
cc440cda
PB
6268 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6269 | KVM_STATE_NESTED_GIF_SET))
26b471c7 6270 break;
8fcc4b59
JM
6271
6272 /* nested_run_pending implies guest_mode. */
8cab6507
VK
6273 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6274 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
26b471c7 6275 break;
8fcc4b59 6276
ad5996d9 6277 idx = srcu_read_lock(&vcpu->kvm->srcu);
33b22172 6278 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
ad5996d9 6279 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8fcc4b59
JM
6280 break;
6281 }
b4f69df0 6282#ifdef CONFIG_KVM_HYPERV
c21d54f0
VK
6283 case KVM_GET_SUPPORTED_HV_CPUID:
6284 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
2bc39970 6285 break;
b4f69df0 6286#endif
b59b153d 6287#ifdef CONFIG_KVM_XEN
3e324615
DW
6288 case KVM_XEN_VCPU_GET_ATTR: {
6289 struct kvm_xen_vcpu_attr xva;
6290
6291 r = -EFAULT;
6292 if (copy_from_user(&xva, argp, sizeof(xva)))
6293 goto out;
6294 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6295 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6296 r = -EFAULT;
6297 break;
6298 }
6299 case KVM_XEN_VCPU_SET_ATTR: {
6300 struct kvm_xen_vcpu_attr xva;
6301
6302 r = -EFAULT;
6303 if (copy_from_user(&xva, argp, sizeof(xva)))
6304 goto out;
6305 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6306 break;
6307 }
b59b153d 6308#endif
6dba9403 6309 case KVM_GET_SREGS2: {
517987e3
PB
6310 r = -EINVAL;
6311 if (vcpu->kvm->arch.has_protected_state &&
6312 vcpu->arch.guest_state_protected)
6313 goto out;
6314
6dba9403
ML
6315 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6316 r = -ENOMEM;
6317 if (!u.sregs2)
6318 goto out;
6319 __get_sregs2(vcpu, u.sregs2);
6320 r = -EFAULT;
6321 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6322 goto out;
6323 r = 0;
6324 break;
6325 }
6326 case KVM_SET_SREGS2: {
517987e3
PB
6327 r = -EINVAL;
6328 if (vcpu->kvm->arch.has_protected_state &&
6329 vcpu->arch.guest_state_protected)
6330 goto out;
6331
6dba9403
ML
6332 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6333 if (IS_ERR(u.sregs2)) {
6334 r = PTR_ERR(u.sregs2);
6335 u.sregs2 = NULL;
6336 goto out;
6337 }
6338 r = __set_sregs2(vcpu, u.sregs2);
6339 break;
6340 }
828ca896
OU
6341 case KVM_HAS_DEVICE_ATTR:
6342 case KVM_GET_DEVICE_ATTR:
6343 case KVM_SET_DEVICE_ATTR:
6344 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6345 break;
a50f673f
IY
6346 case KVM_MEMORY_ENCRYPT_OP:
6347 r = -ENOTTY;
6348 if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6349 goto out;
6350 r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6351 break;
313a3dc7
CO
6352 default:
6353 r = -EINVAL;
6354 }
6355out:
d1ac91d8 6356 kfree(u.buffer);
9b062471
CD
6357out_nofree:
6358 vcpu_put(vcpu);
313a3dc7
CO
6359 return r;
6360}
6361
1499fa80 6362vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5b1c1493
CO
6363{
6364 return VM_FAULT_SIGBUS;
6365}
6366
1fe779f8
CO
6367static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6368{
6369 int ret;
6370
6371 if (addr > (unsigned int)(-3 * PAGE_SIZE))
951179ce 6372 return -EINVAL;
89604647 6373 ret = kvm_x86_call(set_tss_addr)(kvm, addr);
1fe779f8
CO
6374 return ret;
6375}
6376
b927a3ce
SY
6377static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6378 u64 ident_addr)
6379{
89604647 6380 return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
b927a3ce
SY
6381}
6382
1fe779f8 6383static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
bc8a3d89 6384 unsigned long kvm_nr_mmu_pages)
1fe779f8
CO
6385{
6386 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6387 return -EINVAL;
6388
79fac95e 6389 mutex_lock(&kvm->slots_lock);
1fe779f8
CO
6390
6391 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
f05e70ac 6392 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1fe779f8 6393
79fac95e 6394 mutex_unlock(&kvm->slots_lock);
1fe779f8
CO
6395 return 0;
6396}
6397
1fe779f8
CO
6398static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6399{
90bca052 6400 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
6401 int r;
6402
6403 r = 0;
6404 switch (chip->chip_id) {
6405 case KVM_IRQCHIP_PIC_MASTER:
90bca052 6406 memcpy(&chip->chip.pic, &pic->pics[0],
1fe779f8
CO
6407 sizeof(struct kvm_pic_state));
6408 break;
6409 case KVM_IRQCHIP_PIC_SLAVE:
90bca052 6410 memcpy(&chip->chip.pic, &pic->pics[1],
1fe779f8
CO
6411 sizeof(struct kvm_pic_state));
6412 break;
6413 case KVM_IRQCHIP_IOAPIC:
33392b49 6414 kvm_get_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
6415 break;
6416 default:
6417 r = -EINVAL;
6418 break;
6419 }
6420 return r;
6421}
6422
6423static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6424{
90bca052 6425 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
6426 int r;
6427
6428 r = 0;
6429 switch (chip->chip_id) {
6430 case KVM_IRQCHIP_PIC_MASTER:
90bca052
DH
6431 spin_lock(&pic->lock);
6432 memcpy(&pic->pics[0], &chip->chip.pic,
1fe779f8 6433 sizeof(struct kvm_pic_state));
90bca052 6434 spin_unlock(&pic->lock);
1fe779f8
CO
6435 break;
6436 case KVM_IRQCHIP_PIC_SLAVE:
90bca052
DH
6437 spin_lock(&pic->lock);
6438 memcpy(&pic->pics[1], &chip->chip.pic,
1fe779f8 6439 sizeof(struct kvm_pic_state));
90bca052 6440 spin_unlock(&pic->lock);
1fe779f8
CO
6441 break;
6442 case KVM_IRQCHIP_IOAPIC:
33392b49 6443 kvm_set_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
6444 break;
6445 default:
6446 r = -EINVAL;
6447 break;
6448 }
90bca052 6449 kvm_pic_update_irq(pic);
1fe779f8
CO
6450 return r;
6451}
6452
e0f63cb9
SY
6453static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6454{
34f3941c
RK
6455 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6456
6457 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6458
6459 mutex_lock(&kps->lock);
6460 memcpy(ps, &kps->channels, sizeof(*ps));
6461 mutex_unlock(&kps->lock);
2da29bcc 6462 return 0;
e0f63cb9
SY
6463}
6464
6465static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6466{
0185604c 6467 int i;
09edea72
RK
6468 struct kvm_pit *pit = kvm->arch.vpit;
6469
6470 mutex_lock(&pit->pit_state.lock);
34f3941c 6471 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
0185604c 6472 for (i = 0; i < 3; i++)
09edea72
RK
6473 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6474 mutex_unlock(&pit->pit_state.lock);
2da29bcc 6475 return 0;
e9f42757
BK
6476}
6477
6478static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6479{
e9f42757
BK
6480 mutex_lock(&kvm->arch.vpit->pit_state.lock);
6481 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6482 sizeof(ps->channels));
6483 ps->flags = kvm->arch.vpit->pit_state.flags;
6484 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
97e69aa6 6485 memset(&ps->reserved, 0, sizeof(ps->reserved));
2da29bcc 6486 return 0;
e9f42757
BK
6487}
6488
6489static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6490{
2da29bcc 6491 int start = 0;
0185604c 6492 int i;
e9f42757 6493 u32 prev_legacy, cur_legacy;
09edea72
RK
6494 struct kvm_pit *pit = kvm->arch.vpit;
6495
6496 mutex_lock(&pit->pit_state.lock);
6497 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
e9f42757
BK
6498 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6499 if (!prev_legacy && cur_legacy)
6500 start = 1;
09edea72
RK
6501 memcpy(&pit->pit_state.channels, &ps->channels,
6502 sizeof(pit->pit_state.channels));
6503 pit->pit_state.flags = ps->flags;
0185604c 6504 for (i = 0; i < 3; i++)
09edea72 6505 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
e5e57e7a 6506 start && i == 0);
09edea72 6507 mutex_unlock(&pit->pit_state.lock);
2da29bcc 6508 return 0;
e0f63cb9
SY
6509}
6510
52d939a0
MT
6511static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6512 struct kvm_reinject_control *control)
6513{
71474e2f
RK
6514 struct kvm_pit *pit = kvm->arch.vpit;
6515
71474e2f
RK
6516 /* pit->pit_state.lock was overloaded to prevent userspace from getting
6517 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6518 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
6519 */
6520 mutex_lock(&pit->pit_state.lock);
6521 kvm_pit_set_reinject(pit, control->pit_reinject);
6522 mutex_unlock(&pit->pit_state.lock);
b39c90b6 6523
52d939a0
MT
6524 return 0;
6525}
6526
0dff0846 6527void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5bb064dc 6528{
a018eba5 6529
88178fd4 6530 /*
a018eba5
SC
6531 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6532 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6533 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6534 * VM-Exit.
88178fd4 6535 */
a018eba5 6536 struct kvm_vcpu *vcpu;
46808a4c 6537 unsigned long i;
a018eba5 6538
fbb4adad 6539 if (!kvm->arch.cpu_dirty_log_size)
3d30bfcb
DM
6540 return;
6541
a018eba5
SC
6542 kvm_for_each_vcpu(i, vcpu, kvm)
6543 kvm_vcpu_kick(vcpu);
5bb064dc
ZX
6544}
6545
aa2fbe6d
YZ
6546int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6547 bool line_status)
23d43cf9
CD
6548{
6549 if (!irqchip_in_kernel(kvm))
6550 return -ENXIO;
6551
6552 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
aa2fbe6d
YZ
6553 irq_event->irq, irq_event->level,
6554 line_status);
23d43cf9
CD
6555 return 0;
6556}
6557
e5d83c74
PB
6558int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6559 struct kvm_enable_cap *cap)
90de4a18
NA
6560{
6561 int r;
6562
6563 if (cap->flags)
6564 return -EINVAL;
6565
6566 switch (cap->cap) {
6d849191
OU
6567 case KVM_CAP_DISABLE_QUIRKS2:
6568 r = -EINVAL;
bd7d5362 6569 if (cap->args[0] & ~kvm_caps.supported_quirks)
6d849191
OU
6570 break;
6571 fallthrough;
90de4a18 6572 case KVM_CAP_DISABLE_QUIRKS:
bd7d5362 6573 kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
90de4a18
NA
6574 r = 0;
6575 break;
49df6397
SR
6576 case KVM_CAP_SPLIT_IRQCHIP: {
6577 mutex_lock(&kvm->lock);
b053b2ae
SR
6578 r = -EINVAL;
6579 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6580 goto split_irqchip_unlock;
49df6397
SR
6581 r = -EEXIST;
6582 if (irqchip_in_kernel(kvm))
6583 goto split_irqchip_unlock;
557abc40 6584 if (kvm->created_vcpus)
49df6397 6585 goto split_irqchip_unlock;
49df6397
SR
6586 /* Pairs with irqchip_in_kernel. */
6587 smp_wmb();
49776faf 6588 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
b053b2ae 6589 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
320af55a 6590 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
49df6397
SR
6591 r = 0;
6592split_irqchip_unlock:
6593 mutex_unlock(&kvm->lock);
6594 break;
6595 }
37131313
RK
6596 case KVM_CAP_X2APIC_API:
6597 r = -EINVAL;
6598 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6599 break;
6600
6601 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6602 kvm->arch.x2apic_format = true;
c519265f
RK
6603 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6604 kvm->arch.x2apic_broadcast_quirk_disabled = true;
37131313
RK
6605
6606 r = 0;
6607 break;
4d5422ce
WL
6608 case KVM_CAP_X86_DISABLE_EXITS:
6609 r = -EINVAL;
c829ccd4 6610 if (cap->args[0] & ~kvm_get_allowed_disable_exits())
4d5422ce
WL
6611 break;
6612
04cd8f86
SC
6613 mutex_lock(&kvm->lock);
6614 if (kvm->created_vcpus)
6615 goto disable_exits_unlock;
6f0f2d5e
TL
6616
6617#define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6618 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6619
c829ccd4
SC
6620 if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6621 cpu_smt_possible() &&
6622 (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6623 pr_warn_once(SMT_RSB_MSG);
6f0f2d5e 6624
c829ccd4
SC
6625 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6626 kvm->arch.pause_in_guest = true;
6627 if (cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT)
6628 kvm->arch.mwait_in_guest = true;
6629 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6630 kvm->arch.hlt_in_guest = true;
6631 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6632 kvm->arch.cstate_in_guest = true;
4d5422ce 6633 r = 0;
04cd8f86
SC
6634disable_exits_unlock:
6635 mutex_unlock(&kvm->lock);
4d5422ce 6636 break;
6fbbde9a
DS
6637 case KVM_CAP_MSR_PLATFORM_INFO:
6638 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6639 r = 0;
c4f55198
JM
6640 break;
6641 case KVM_CAP_EXCEPTION_PAYLOAD:
6642 kvm->arch.exception_payload_enabled = cap->args[0];
6643 r = 0;
6fbbde9a 6644 break;
ed235117
CQ
6645 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6646 kvm->arch.triple_fault_event = cap->args[0];
6647 r = 0;
6648 break;
1ae09954 6649 case KVM_CAP_X86_USER_SPACE_MSR:
cf5029d5 6650 r = -EINVAL;
db205f7e 6651 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
cf5029d5 6652 break;
1ae09954
AG
6653 kvm->arch.user_space_msr_mask = cap->args[0];
6654 r = 0;
6655 break;
fe6b6bc8
CQ
6656 case KVM_CAP_X86_BUS_LOCK_EXIT:
6657 r = -EINVAL;
6658 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6659 break;
6660
6661 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6662 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6663 break;
6664
938c8745 6665 if (kvm_caps.has_bus_lock_exit &&
fe6b6bc8
CQ
6666 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6667 kvm->arch.bus_lock_detection_enabled = true;
6668 r = 0;
6669 break;
fe7e9488
SC
6670#ifdef CONFIG_X86_SGX_KVM
6671 case KVM_CAP_SGX_ATTRIBUTE: {
6672 unsigned long allowed_attributes = 0;
6673
6674 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6675 if (r)
6676 break;
6677
6678 /* KVM only supports the PROVISIONKEY privileged attribute. */
6679 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6680 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6681 kvm->arch.sgx_provisioning_allowed = true;
6682 else
6683 r = -EINVAL;
6684 break;
6685 }
6686#endif
54526d1f
NT
6687 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6688 r = -EINVAL;
7ad02ef0
SC
6689 if (!kvm_x86_ops.vm_copy_enc_context_from)
6690 break;
6691
89604647 6692 r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
7ad02ef0 6693 break;
b5663931
PG
6694 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6695 r = -EINVAL;
7ad02ef0
SC
6696 if (!kvm_x86_ops.vm_move_enc_context_from)
6697 break;
6698
89604647 6699 r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
7ad02ef0 6700 break;
0dbb1123
AK
6701 case KVM_CAP_EXIT_HYPERCALL:
6702 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6703 r = -EINVAL;
6704 break;
6705 }
6706 kvm->arch.hypercall_exit_enabled = cap->args[0];
6707 r = 0;
6708 break;
19238e75
AL
6709 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6710 r = -EINVAL;
6711 if (cap->args[0] & ~1)
6712 break;
6713 kvm->arch.exit_on_emulation_error = cap->args[0];
6714 r = 0;
6715 break;
ba7bb663
DD
6716 case KVM_CAP_PMU_CAPABILITY:
6717 r = -EINVAL;
6718 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6719 break;
6720
6721 mutex_lock(&kvm->lock);
6722 if (!kvm->created_vcpus) {
6723 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6724 r = 0;
6725 }
6726 mutex_unlock(&kvm->lock);
6727 break;
35875316
ZG
6728 case KVM_CAP_MAX_VCPU_ID:
6729 r = -EINVAL;
6730 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6731 break;
6732
6733 mutex_lock(&kvm->lock);
d29bf2ca
SC
6734 if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6735 ;
6736 } else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
35875316
ZG
6737 r = 0;
6738 } else if (!kvm->arch.max_vcpu_ids) {
6739 kvm->arch.max_vcpu_ids = cap->args[0];
6740 r = 0;
6741 }
6742 mutex_unlock(&kvm->lock);
6743 break;
2f4073e0
TX
6744 case KVM_CAP_X86_NOTIFY_VMEXIT:
6745 r = -EINVAL;
6746 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6747 break;
6748 if (!kvm_caps.has_notify_vmexit)
6749 break;
6750 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6751 break;
6752 mutex_lock(&kvm->lock);
6753 if (!kvm->created_vcpus) {
6754 kvm->arch.notify_window = cap->args[0] >> 32;
6755 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6756 r = 0;
6757 }
6758 mutex_unlock(&kvm->lock);
6759 break;
084cc29f
BG
6760 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6761 r = -EINVAL;
6762
6763 /*
6764 * Since the risk of disabling NX hugepages is a guest crashing
6765 * the system, ensure the userspace process has permission to
6766 * reboot the system.
6767 *
6768 * Note that unlike the reboot() syscall, the process must have
6769 * this capability in the root namespace because exposing
6770 * /dev/kvm into a container does not limit the scope of the
6771 * iTLB multihit bug to that container. In other words,
6772 * this must use capable(), not ns_capable().
6773 */
6774 if (!capable(CAP_SYS_BOOT)) {
6775 r = -EPERM;
6776 break;
6777 }
6778
6779 if (cap->args[0])
6780 break;
6781
6782 mutex_lock(&kvm->lock);
6783 if (!kvm->created_vcpus) {
6784 kvm->arch.disable_nx_huge_pages = true;
6785 r = 0;
6786 }
6787 mutex_unlock(&kvm->lock);
6788 break;
6fef5185
IY
6789 case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6790 u64 bus_cycle_ns = cap->args[0];
6791 u64 unused;
6792
6793 /*
6794 * Guard against overflow in tmict_to_ns(). 128 is the highest
6795 * divide value that can be programmed in APIC_TDCR.
6796 */
6797 r = -EINVAL;
6798 if (!bus_cycle_ns ||
6799 check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6800 break;
6801
6802 r = 0;
6803 mutex_lock(&kvm->lock);
6804 if (!irqchip_in_kernel(kvm))
6805 r = -ENXIO;
6806 else if (kvm->created_vcpus)
6807 r = -EINVAL;
6808 else
6809 kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6810 mutex_unlock(&kvm->lock);
6811 break;
6812 }
90de4a18
NA
6813 default:
6814 r = -EINVAL;
6815 break;
6816 }
6817 return r;
6818}
6819
b318e8de
SC
6820static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6821{
6822 struct kvm_x86_msr_filter *msr_filter;
6823
6824 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6825 if (!msr_filter)
6826 return NULL;
6827
6828 msr_filter->default_allow = default_allow;
6829 return msr_filter;
6830}
6831
6832static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
1a155254
AG
6833{
6834 u32 i;
1a155254 6835
b318e8de
SC
6836 if (!msr_filter)
6837 return;
6838
6839 for (i = 0; i < msr_filter->count; i++)
6840 kfree(msr_filter->ranges[i].bitmap);
1a155254 6841
b318e8de 6842 kfree(msr_filter);
1a155254
AG
6843}
6844
b318e8de
SC
6845static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6846 struct kvm_msr_filter_range *user_range)
1a155254 6847{
392a5324 6848 unsigned long *bitmap;
1a155254 6849 size_t bitmap_size;
1a155254
AG
6850
6851 if (!user_range->nmsrs)
6852 return 0;
6853
8aff460f 6854 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
aca35288
SC
6855 return -EINVAL;
6856
6857 if (!user_range->flags)
6858 return -EINVAL;
6859
1a155254
AG
6860 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6861 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6862 return -EINVAL;
6863
6864 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6865 if (IS_ERR(bitmap))
6866 return PTR_ERR(bitmap);
6867
aca35288 6868 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
1a155254
AG
6869 .flags = user_range->flags,
6870 .base = user_range->base,
6871 .nmsrs = user_range->nmsrs,
6872 .bitmap = bitmap,
6873 };
6874
b318e8de 6875 msr_filter->count++;
1a155254 6876 return 0;
1a155254
AG
6877}
6878
2e3272bc
AG
6879static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6880 struct kvm_msr_filter *filter)
1a155254 6881{
b318e8de 6882 struct kvm_x86_msr_filter *new_filter, *old_filter;
1a155254 6883 bool default_allow;
043248b3 6884 bool empty = true;
4559e6cf 6885 int r;
1a155254
AG
6886 u32 i;
6887
c1340fe3 6888 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
cf5029d5
AL
6889 return -EINVAL;
6890
2e3272bc
AG
6891 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6892 empty &= !filter->ranges[i].nmsrs;
1a155254 6893
2e3272bc 6894 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
043248b3
PB
6895 if (empty && !default_allow)
6896 return -EINVAL;
6897
b318e8de
SC
6898 new_filter = kvm_alloc_msr_filter(default_allow);
6899 if (!new_filter)
6900 return -ENOMEM;
1a155254 6901
2e3272bc
AG
6902 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6903 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
b318e8de
SC
6904 if (r) {
6905 kvm_free_msr_filter(new_filter);
6906 return r;
6907 }
1a155254
AG
6908 }
6909
b318e8de 6910 mutex_lock(&kvm->lock);
1fdefb8b
ML
6911 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6912 mutex_is_locked(&kvm->lock));
708f799d 6913 mutex_unlock(&kvm->lock);
b318e8de
SC
6914 synchronize_srcu(&kvm->srcu);
6915
6916 kvm_free_msr_filter(old_filter);
6917
1a155254 6918 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
1a155254 6919
b318e8de 6920 return 0;
1a155254
AG
6921}
6922
1739c701
AG
6923#ifdef CONFIG_KVM_COMPAT
6924/* for KVM_X86_SET_MSR_FILTER */
6925struct kvm_msr_filter_range_compat {
6926 __u32 flags;
6927 __u32 nmsrs;
6928 __u32 base;
6929 __u32 bitmap;
6930};
6931
6932struct kvm_msr_filter_compat {
6933 __u32 flags;
6934 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6935};
6936
6937#define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6938
6939long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6940 unsigned long arg)
6941{
6942 void __user *argp = (void __user *)arg;
6943 struct kvm *kvm = filp->private_data;
6944 long r = -ENOTTY;
6945
6946 switch (ioctl) {
6947 case KVM_X86_SET_MSR_FILTER_COMPAT: {
6948 struct kvm_msr_filter __user *user_msr_filter = argp;
6949 struct kvm_msr_filter_compat filter_compat;
6950 struct kvm_msr_filter filter;
6951 int i;
6952
6953 if (copy_from_user(&filter_compat, user_msr_filter,
6954 sizeof(filter_compat)))
6955 return -EFAULT;
6956
6957 filter.flags = filter_compat.flags;
6958 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6959 struct kvm_msr_filter_range_compat *cr;
6960
6961 cr = &filter_compat.ranges[i];
6962 filter.ranges[i] = (struct kvm_msr_filter_range) {
6963 .flags = cr->flags,
6964 .nmsrs = cr->nmsrs,
6965 .base = cr->base,
6966 .bitmap = (__u8 *)(ulong)cr->bitmap,
6967 };
6968 }
6969
6970 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6971 break;
6972 }
6973 }
6974
6975 return r;
6976}
6977#endif
6978
7d62874f
SS
6979#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6980static int kvm_arch_suspend_notifier(struct kvm *kvm)
6981{
6982 struct kvm_vcpu *vcpu;
46808a4c 6983 unsigned long i;
7d62874f 6984
4198f38a
SC
6985 /*
6986 * Ignore the return, marking the guest paused only "fails" if the vCPU
6987 * isn't using kvmclock; continuing on is correct and desirable.
6988 */
6989 kvm_for_each_vcpu(i, vcpu, kvm)
6990 (void)kvm_set_guest_paused(vcpu);
7d62874f 6991
4198f38a 6992 return NOTIFY_DONE;
7d62874f
SS
6993}
6994
6995int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6996{
6997 switch (state) {
6998 case PM_HIBERNATION_PREPARE:
6999 case PM_SUSPEND_PREPARE:
7000 return kvm_arch_suspend_notifier(kvm);
7001 }
7002
7003 return NOTIFY_DONE;
7004}
7005#endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7006
45e6c2fa
PB
7007static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7008{
869b4421 7009 struct kvm_clock_data data = { 0 };
45e6c2fa 7010
55c0cefb 7011 get_kvmclock(kvm, &data);
45e6c2fa
PB
7012 if (copy_to_user(argp, &data, sizeof(data)))
7013 return -EFAULT;
7014
7015 return 0;
7016}
7017
7018static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7019{
7020 struct kvm_arch *ka = &kvm->arch;
7021 struct kvm_clock_data data;
c68dc1b5 7022 u64 now_raw_ns;
45e6c2fa
PB
7023
7024 if (copy_from_user(&data, argp, sizeof(data)))
7025 return -EFAULT;
7026
c68dc1b5
OU
7027 /*
7028 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7029 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7030 */
7031 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
45e6c2fa
PB
7032 return -EINVAL;
7033
42dcbe7d 7034 kvm_hv_request_tsc_page_update(kvm);
45e6c2fa
PB
7035 kvm_start_pvclock_update(kvm);
7036 pvclock_update_vm_gtod_copy(kvm);
7037
7038 /*
7039 * This pairs with kvm_guest_time_update(): when masterclock is
7040 * in use, we use master_kernel_ns + kvmclock_offset to set
7041 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7042 * is slightly ahead) here we risk going negative on unsigned
7043 * 'system_time' when 'data.clock' is very small.
7044 */
c68dc1b5
OU
7045 if (data.flags & KVM_CLOCK_REALTIME) {
7046 u64 now_real_ns = ktime_get_real_ns();
7047
7048 /*
7049 * Avoid stepping the kvmclock backwards.
7050 */
7051 if (now_real_ns > data.realtime)
7052 data.clock += now_real_ns - data.realtime;
7053 }
7054
7055 if (ka->use_master_clock)
7056 now_raw_ns = ka->master_kernel_ns;
45e6c2fa 7057 else
c68dc1b5
OU
7058 now_raw_ns = get_kvmclock_base_ns();
7059 ka->kvmclock_offset = data.clock - now_raw_ns;
45e6c2fa
PB
7060 kvm_end_pvclock_update(kvm);
7061 return 0;
7062}
7063
d8708b80 7064int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
1fe779f8
CO
7065{
7066 struct kvm *kvm = filp->private_data;
7067 void __user *argp = (void __user *)arg;
367e1319 7068 int r = -ENOTTY;
f0d66275
DH
7069 /*
7070 * This union makes it completely explicit to gcc-3.x
7071 * that these two variables' stack usage should be
7072 * combined, not added together.
7073 */
7074 union {
7075 struct kvm_pit_state ps;
e9f42757 7076 struct kvm_pit_state2 ps2;
c5ff41ce 7077 struct kvm_pit_config pit_config;
f0d66275 7078 } u;
1fe779f8
CO
7079
7080 switch (ioctl) {
7081 case KVM_SET_TSS_ADDR:
7082 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1fe779f8 7083 break;
b927a3ce
SY
7084 case KVM_SET_IDENTITY_MAP_ADDR: {
7085 u64 ident_addr;
7086
1af1ac91
DH
7087 mutex_lock(&kvm->lock);
7088 r = -EINVAL;
7089 if (kvm->created_vcpus)
7090 goto set_identity_unlock;
b927a3ce 7091 r = -EFAULT;
0e96f31e 7092 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
1af1ac91 7093 goto set_identity_unlock;
b927a3ce 7094 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
1af1ac91
DH
7095set_identity_unlock:
7096 mutex_unlock(&kvm->lock);
b927a3ce
SY
7097 break;
7098 }
1fe779f8
CO
7099 case KVM_SET_NR_MMU_PAGES:
7100 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1fe779f8 7101 break;
3ddea128 7102 case KVM_CREATE_IRQCHIP: {
3ddea128 7103 mutex_lock(&kvm->lock);
09941366 7104
3ddea128 7105 r = -EEXIST;
35e6eaa3 7106 if (irqchip_in_kernel(kvm))
3ddea128 7107 goto create_irqchip_unlock;
09941366 7108
3e515705 7109 r = -EINVAL;
557abc40 7110 if (kvm->created_vcpus)
3e515705 7111 goto create_irqchip_unlock;
09941366
RK
7112
7113 r = kvm_pic_init(kvm);
7114 if (r)
3ddea128 7115 goto create_irqchip_unlock;
09941366
RK
7116
7117 r = kvm_ioapic_init(kvm);
7118 if (r) {
09941366 7119 kvm_pic_destroy(kvm);
3ddea128 7120 goto create_irqchip_unlock;
09941366
RK
7121 }
7122
399ec807
AK
7123 r = kvm_setup_default_irq_routing(kvm);
7124 if (r) {
72bb2fcd 7125 kvm_ioapic_destroy(kvm);
09941366 7126 kvm_pic_destroy(kvm);
71ba994c 7127 goto create_irqchip_unlock;
399ec807 7128 }
49776faf 7129 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
71ba994c 7130 smp_wmb();
49776faf 7131 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
320af55a 7132 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
3ddea128
MT
7133 create_irqchip_unlock:
7134 mutex_unlock(&kvm->lock);
1fe779f8 7135 break;
3ddea128 7136 }
7837699f 7137 case KVM_CREATE_PIT:
c5ff41ce
JK
7138 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7139 goto create_pit;
7140 case KVM_CREATE_PIT2:
7141 r = -EFAULT;
7142 if (copy_from_user(&u.pit_config, argp,
7143 sizeof(struct kvm_pit_config)))
7144 goto out;
7145 create_pit:
250715a6 7146 mutex_lock(&kvm->lock);
269e05e4
AK
7147 r = -EEXIST;
7148 if (kvm->arch.vpit)
7149 goto create_pit_unlock;
9e05d9b0
TY
7150 r = -ENOENT;
7151 if (!pic_in_kernel(kvm))
7152 goto create_pit_unlock;
7837699f 7153 r = -ENOMEM;
c5ff41ce 7154 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7837699f
SY
7155 if (kvm->arch.vpit)
7156 r = 0;
269e05e4 7157 create_pit_unlock:
250715a6 7158 mutex_unlock(&kvm->lock);
7837699f 7159 break;
1fe779f8
CO
7160 case KVM_GET_IRQCHIP: {
7161 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 7162 struct kvm_irqchip *chip;
1fe779f8 7163
ff5c2c03
SL
7164 chip = memdup_user(argp, sizeof(*chip));
7165 if (IS_ERR(chip)) {
7166 r = PTR_ERR(chip);
1fe779f8 7167 goto out;
ff5c2c03
SL
7168 }
7169
1fe779f8 7170 r = -ENXIO;
826da321 7171 if (!irqchip_kernel(kvm))
f0d66275
DH
7172 goto get_irqchip_out;
7173 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1fe779f8 7174 if (r)
f0d66275 7175 goto get_irqchip_out;
1fe779f8 7176 r = -EFAULT;
0e96f31e 7177 if (copy_to_user(argp, chip, sizeof(*chip)))
f0d66275 7178 goto get_irqchip_out;
1fe779f8 7179 r = 0;
f0d66275
DH
7180 get_irqchip_out:
7181 kfree(chip);
1fe779f8
CO
7182 break;
7183 }
7184 case KVM_SET_IRQCHIP: {
7185 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 7186 struct kvm_irqchip *chip;
1fe779f8 7187
ff5c2c03
SL
7188 chip = memdup_user(argp, sizeof(*chip));
7189 if (IS_ERR(chip)) {
7190 r = PTR_ERR(chip);
1fe779f8 7191 goto out;
ff5c2c03
SL
7192 }
7193
1fe779f8 7194 r = -ENXIO;
826da321 7195 if (!irqchip_kernel(kvm))
f0d66275
DH
7196 goto set_irqchip_out;
7197 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
f0d66275
DH
7198 set_irqchip_out:
7199 kfree(chip);
1fe779f8
CO
7200 break;
7201 }
e0f63cb9 7202 case KVM_GET_PIT: {
e0f63cb9 7203 r = -EFAULT;
f0d66275 7204 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
7205 goto out;
7206 r = -ENXIO;
7207 if (!kvm->arch.vpit)
7208 goto out;
f0d66275 7209 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
e0f63cb9
SY
7210 if (r)
7211 goto out;
7212 r = -EFAULT;
f0d66275 7213 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
7214 goto out;
7215 r = 0;
7216 break;
7217 }
7218 case KVM_SET_PIT: {
e0f63cb9 7219 r = -EFAULT;
0e96f31e 7220 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
e0f63cb9 7221 goto out;
7289fdb5 7222 mutex_lock(&kvm->lock);
e0f63cb9
SY
7223 r = -ENXIO;
7224 if (!kvm->arch.vpit)
7289fdb5 7225 goto set_pit_out;
f0d66275 7226 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7289fdb5
SR
7227set_pit_out:
7228 mutex_unlock(&kvm->lock);
e0f63cb9
SY
7229 break;
7230 }
e9f42757
BK
7231 case KVM_GET_PIT2: {
7232 r = -ENXIO;
7233 if (!kvm->arch.vpit)
7234 goto out;
7235 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7236 if (r)
7237 goto out;
7238 r = -EFAULT;
7239 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7240 goto out;
7241 r = 0;
7242 break;
7243 }
7244 case KVM_SET_PIT2: {
7245 r = -EFAULT;
7246 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7247 goto out;
7289fdb5 7248 mutex_lock(&kvm->lock);
e9f42757
BK
7249 r = -ENXIO;
7250 if (!kvm->arch.vpit)
7289fdb5 7251 goto set_pit2_out;
e9f42757 7252 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7289fdb5
SR
7253set_pit2_out:
7254 mutex_unlock(&kvm->lock);
e9f42757
BK
7255 break;
7256 }
52d939a0
MT
7257 case KVM_REINJECT_CONTROL: {
7258 struct kvm_reinject_control control;
7259 r = -EFAULT;
7260 if (copy_from_user(&control, argp, sizeof(control)))
7261 goto out;
cad23e72
ML
7262 r = -ENXIO;
7263 if (!kvm->arch.vpit)
7264 goto out;
52d939a0 7265 r = kvm_vm_ioctl_reinject(kvm, &control);
52d939a0
MT
7266 break;
7267 }
d71ba788
PB
7268 case KVM_SET_BOOT_CPU_ID:
7269 r = 0;
7270 mutex_lock(&kvm->lock);
557abc40 7271 if (kvm->created_vcpus)
d71ba788 7272 r = -EBUSY;
7c305d51
MK
7273 else if (arg > KVM_MAX_VCPU_IDS ||
7274 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7275 r = -EINVAL;
d71ba788
PB
7276 else
7277 kvm->arch.bsp_vcpu_id = arg;
7278 mutex_unlock(&kvm->lock);
7279 break;
b59b153d 7280#ifdef CONFIG_KVM_XEN
ffde22ac 7281 case KVM_XEN_HVM_CONFIG: {
51776043 7282 struct kvm_xen_hvm_config xhc;
ffde22ac 7283 r = -EFAULT;
51776043 7284 if (copy_from_user(&xhc, argp, sizeof(xhc)))
ffde22ac 7285 goto out;
78e9878c 7286 r = kvm_xen_hvm_config(kvm, &xhc);
ffde22ac
ES
7287 break;
7288 }
a76b9641
JM
7289 case KVM_XEN_HVM_GET_ATTR: {
7290 struct kvm_xen_hvm_attr xha;
7291
7292 r = -EFAULT;
7293 if (copy_from_user(&xha, argp, sizeof(xha)))
ffde22ac 7294 goto out;
a76b9641
JM
7295 r = kvm_xen_hvm_get_attr(kvm, &xha);
7296 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7297 r = -EFAULT;
7298 break;
7299 }
7300 case KVM_XEN_HVM_SET_ATTR: {
7301 struct kvm_xen_hvm_attr xha;
7302
7303 r = -EFAULT;
7304 if (copy_from_user(&xha, argp, sizeof(xha)))
7305 goto out;
7306 r = kvm_xen_hvm_set_attr(kvm, &xha);
ffde22ac
ES
7307 break;
7308 }
35025735
DW
7309 case KVM_XEN_HVM_EVTCHN_SEND: {
7310 struct kvm_irq_routing_xen_evtchn uxe;
7311
7312 r = -EFAULT;
7313 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7314 goto out;
7315 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7316 break;
7317 }
b59b153d 7318#endif
45e6c2fa
PB
7319 case KVM_SET_CLOCK:
7320 r = kvm_vm_ioctl_set_clock(kvm, argp);
afbcf7ab 7321 break;
45e6c2fa
PB
7322 case KVM_GET_CLOCK:
7323 r = kvm_vm_ioctl_get_clock(kvm, argp);
afbcf7ab 7324 break;
ffbb61d0
DW
7325 case KVM_SET_TSC_KHZ: {
7326 u32 user_tsc_khz;
7327
7328 r = -EINVAL;
7329 user_tsc_khz = (u32)arg;
7330
938c8745
SC
7331 if (kvm_caps.has_tsc_control &&
7332 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
ffbb61d0
DW
7333 goto out;
7334
7335 if (user_tsc_khz == 0)
7336 user_tsc_khz = tsc_khz;
7337
7338 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7339 r = 0;
7340
7341 goto out;
7342 }
7343 case KVM_GET_TSC_KHZ: {
7344 r = READ_ONCE(kvm->arch.default_tsc_khz);
7345 goto out;
7346 }
f2d79933
SC
7347 case KVM_MEMORY_ENCRYPT_OP:
7348 r = -ENOTTY;
7349 if (!kvm_x86_ops.mem_enc_ioctl)
7350 goto out;
7351
89604647 7352 r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
5acc5c06 7353 break;
69eaedee
BS
7354 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7355 struct kvm_enc_region region;
7356
7357 r = -EFAULT;
7358 if (copy_from_user(&region, argp, sizeof(region)))
7359 goto out;
7360
7361 r = -ENOTTY;
03d004cd
SC
7362 if (!kvm_x86_ops.mem_enc_register_region)
7363 goto out;
7364
89604647 7365 r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
69eaedee
BS
7366 break;
7367 }
7368 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7369 struct kvm_enc_region region;
7370
7371 r = -EFAULT;
7372 if (copy_from_user(&region, argp, sizeof(region)))
7373 goto out;
7374
7375 r = -ENOTTY;
03d004cd
SC
7376 if (!kvm_x86_ops.mem_enc_unregister_region)
7377 goto out;
7378
89604647 7379 r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
69eaedee
BS
7380 break;
7381 }
b4f69df0 7382#ifdef CONFIG_KVM_HYPERV
faeb7833
RK
7383 case KVM_HYPERV_EVENTFD: {
7384 struct kvm_hyperv_eventfd hvevfd;
7385
7386 r = -EFAULT;
7387 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7388 goto out;
7389 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7390 break;
7391 }
b4f69df0 7392#endif
66bb8a06
EH
7393 case KVM_SET_PMU_EVENT_FILTER:
7394 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7395 break;
2e3272bc
AG
7396 case KVM_X86_SET_MSR_FILTER: {
7397 struct kvm_msr_filter __user *user_msr_filter = argp;
7398 struct kvm_msr_filter filter;
7399
7400 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7401 return -EFAULT;
7402
7403 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
1a155254 7404 break;
2e3272bc 7405 }
1fe779f8 7406 default:
ad6260da 7407 r = -ENOTTY;
1fe779f8
CO
7408 }
7409out:
7410 return r;
7411}
7412
9eb6ba31
SC
7413static void kvm_probe_feature_msr(u32 msr_index)
7414{
7075f163 7415 u64 data;
9eb6ba31 7416
7075f163 7417 if (kvm_get_feature_msr(NULL, msr_index, &data, true))
9eb6ba31
SC
7418 return;
7419
7420 msr_based_features[num_msr_based_features++] = msr_index;
7421}
7422
2374b731 7423static void kvm_probe_msr_to_save(u32 msr_index)
043405e1
CO
7424{
7425 u32 dummy[2];
2374b731
SC
7426
7427 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7428 return;
7429
7430 /*
7431 * Even MSRs that are valid in the host may not be exposed to guests in
7432 * some cases.
7433 */
7434 switch (msr_index) {
7435 case MSR_IA32_BNDCFGS:
7436 if (!kvm_mpx_supported())
7437 return;
7438 break;
7439 case MSR_TSC_AUX:
7440 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7441 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7442 return;
7443 break;
7444 case MSR_IA32_UMWAIT_CONTROL:
7445 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7446 return;
7447 break;
7448 case MSR_IA32_RTIT_CTL:
7449 case MSR_IA32_RTIT_STATUS:
7450 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7451 return;
7452 break;
7453 case MSR_IA32_RTIT_CR3_MATCH:
7454 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7455 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7456 return;
7457 break;
7458 case MSR_IA32_RTIT_OUTPUT_BASE:
7459 case MSR_IA32_RTIT_OUTPUT_MASK:
7460 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7461 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7462 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7463 return;
7464 break;
7465 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7466 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7467 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7468 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7469 return;
7470 break;
f287bef6
DM
7471 case MSR_ARCH_PERFMON_PERFCTR0 ...
7472 MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
2374b731
SC
7473 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7474 kvm_pmu_cap.num_counters_gp)
7475 return;
7476 break;
f287bef6
DM
7477 case MSR_ARCH_PERFMON_EVENTSEL0 ...
7478 MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
2374b731
SC
7479 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7480 kvm_pmu_cap.num_counters_gp)
7481 return;
7482 break;
f287bef6
DM
7483 case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7484 MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
e33b6d79
LX
7485 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7486 kvm_pmu_cap.num_counters_fixed)
7487 return;
7488 break;
4a277189
LX
7489 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7490 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7491 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7492 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7493 return;
7494 break;
2374b731
SC
7495 case MSR_IA32_XFD:
7496 case MSR_IA32_XFD_ERR:
7497 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7498 return;
7499 break;
b9846a69
MZ
7500 case MSR_IA32_TSX_CTRL:
7501 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7502 return;
7503 break;
2374b731
SC
7504 default:
7505 break;
7506 }
7507
7508 msrs_to_save[num_msrs_to_save++] = msr_index;
7509}
7510
b1932c5c 7511static void kvm_init_msr_lists(void)
2374b731 7512{
7a5ee6ed 7513 unsigned i;
043405e1 7514
f287bef6 7515 BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
2374b731 7516 "Please update the fixed PMCs in msrs_to_save_pmu[]");
24c29b7a 7517
6cbee2b9
XL
7518 num_msrs_to_save = 0;
7519 num_emulated_msrs = 0;
7520 num_msr_based_features = 0;
7521
2374b731
SC
7522 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7523 kvm_probe_msr_to_save(msrs_to_save_base[i]);
93c4adc7 7524
c3531edc
SC
7525 if (enable_pmu) {
7526 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7527 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
043405e1 7528 }
62ef68bb 7529
7a5ee6ed 7530 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
89604647
WW
7531 if (!kvm_x86_call(has_emulated_msr)(NULL,
7532 emulated_msrs_all[i]))
bc226f07 7533 continue;
62ef68bb 7534
7a5ee6ed 7535 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
62ef68bb 7536 }
801e459a 7537
9eb6ba31
SC
7538 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7539 kvm_probe_feature_msr(i);
801e459a 7540
9eb6ba31
SC
7541 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7542 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
043405e1
CO
7543}
7544
bda9020e
MT
7545static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7546 const void *v)
bbd9b64e 7547{
70252a10
AK
7548 int handled = 0;
7549 int n;
7550
7551 do {
7552 n = min(len, 8);
bce87cce 7553 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
7554 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7555 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10
AK
7556 break;
7557 handled += n;
7558 addr += n;
7559 len -= n;
7560 v += n;
7561 } while (len);
bbd9b64e 7562
70252a10 7563 return handled;
bbd9b64e
CO
7564}
7565
bda9020e 7566static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
bbd9b64e 7567{
70252a10
AK
7568 int handled = 0;
7569 int n;
7570
7571 do {
7572 n = min(len, 8);
bce87cce 7573 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
7574 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7575 addr, n, v))
7576 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10 7577 break;
e39d200f 7578 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
70252a10
AK
7579 handled += n;
7580 addr += n;
7581 len -= n;
7582 v += n;
7583 } while (len);
bbd9b64e 7584
70252a10 7585 return handled;
bbd9b64e
CO
7586}
7587
c53da4f3
PB
7588void kvm_set_segment(struct kvm_vcpu *vcpu,
7589 struct kvm_segment *var, int seg)
2dafc6c2 7590{
89604647 7591 kvm_x86_call(set_segment)(vcpu, var, seg);
2dafc6c2
GN
7592}
7593
7594void kvm_get_segment(struct kvm_vcpu *vcpu,
7595 struct kvm_segment *var, int seg)
7596{
89604647 7597 kvm_x86_call(get_segment)(vcpu, var, seg);
2dafc6c2
GN
7598}
7599
5b22bbe7 7600gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
54987b7a 7601 struct x86_exception *exception)
02f59dc9 7602{
1f5a21ee 7603 struct kvm_mmu *mmu = vcpu->arch.mmu;
02f59dc9 7604 gpa_t t_gpa;
02f59dc9
JR
7605
7606 BUG_ON(!mmu_is_nested(vcpu));
7607
7608 /* NPT walks are always user-walks */
7609 access |= PFERR_USER_MASK;
1f5a21ee 7610 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
02f59dc9
JR
7611
7612 return t_gpa;
7613}
7614
ab9ae313
AK
7615gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7616 struct x86_exception *exception)
1871c602 7617{
1f5a21ee
LJ
7618 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7619
89604647 7620 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
1f5a21ee 7621 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
1871c602 7622}
54f958cd 7623EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
1871c602 7624
ab9ae313
AK
7625gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7626 struct x86_exception *exception)
1871c602 7627{
1f5a21ee
LJ
7628 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7629
89604647 7630 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
1871c602 7631 access |= PFERR_WRITE_MASK;
1f5a21ee 7632 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
1871c602 7633}
54f958cd 7634EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
1871c602
GN
7635
7636/* uses this to access any guest's mapped memory without checking CPL */
ab9ae313
AK
7637gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7638 struct x86_exception *exception)
1871c602 7639{
1f5a21ee
LJ
7640 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7641
7642 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
1871c602
GN
7643}
7644
7645static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5b22bbe7 7646 struct kvm_vcpu *vcpu, u64 access,
bcc55cba 7647 struct x86_exception *exception)
bbd9b64e 7648{
1f5a21ee 7649 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
bbd9b64e 7650 void *data = val;
10589a46 7651 int r = X86EMUL_CONTINUE;
bbd9b64e
CO
7652
7653 while (bytes) {
1f5a21ee 7654 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
bbd9b64e 7655 unsigned offset = addr & (PAGE_SIZE-1);
77c2002e 7656 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
bbd9b64e
CO
7657 int ret;
7658
6e1d2a3f 7659 if (gpa == INVALID_GPA)
ab9ae313 7660 return X86EMUL_PROPAGATE_FAULT;
54bf36aa
PB
7661 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7662 offset, toread);
10589a46 7663 if (ret < 0) {
c3cd7ffa 7664 r = X86EMUL_IO_NEEDED;
10589a46
MT
7665 goto out;
7666 }
bbd9b64e 7667
77c2002e
IE
7668 bytes -= toread;
7669 data += toread;
7670 addr += toread;
bbd9b64e 7671 }
10589a46 7672out:
10589a46 7673 return r;
bbd9b64e 7674}
77c2002e 7675
1871c602 7676/* used for instruction fetching */
0f65dd70
AK
7677static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7678 gva_t addr, void *val, unsigned int bytes,
bcc55cba 7679 struct x86_exception *exception)
1871c602 7680{
0f65dd70 7681 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1f5a21ee 7682 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
89604647 7683 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
44583cba
PB
7684 unsigned offset;
7685 int ret;
0f65dd70 7686
44583cba 7687 /* Inline kvm_read_guest_virt_helper for speed. */
1f5a21ee
LJ
7688 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7689 exception);
6e1d2a3f 7690 if (unlikely(gpa == INVALID_GPA))
44583cba
PB
7691 return X86EMUL_PROPAGATE_FAULT;
7692
7693 offset = addr & (PAGE_SIZE-1);
7694 if (WARN_ON(offset + bytes > PAGE_SIZE))
7695 bytes = (unsigned)PAGE_SIZE - offset;
54bf36aa
PB
7696 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7697 offset, bytes);
44583cba
PB
7698 if (unlikely(ret < 0))
7699 return X86EMUL_IO_NEEDED;
7700
7701 return X86EMUL_CONTINUE;
1871c602
GN
7702}
7703
ce14e868 7704int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
0f65dd70 7705 gva_t addr, void *val, unsigned int bytes,
bcc55cba 7706 struct x86_exception *exception)
1871c602 7707{
89604647 7708 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70 7709
353c0956
PB
7710 /*
7711 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7712 * is returned, but our callers are not ready for that and they blindly
7713 * call kvm_inject_page_fault. Ensure that they at least do not leak
7714 * uninitialized kernel stack memory into cr2 and error code.
7715 */
7716 memset(exception, 0, sizeof(*exception));
1871c602 7717 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
bcc55cba 7718 exception);
1871c602 7719}
064aea77 7720EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
1871c602 7721
ce14e868
PB
7722static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7723 gva_t addr, void *val, unsigned int bytes,
3c9fa24c 7724 struct x86_exception *exception, bool system)
1871c602 7725{
0f65dd70 7726 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5b22bbe7 7727 u64 access = 0;
3c9fa24c 7728
4f4aa80e
LJ
7729 if (system)
7730 access |= PFERR_IMPLICIT_ACCESS;
89604647 7731 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
3c9fa24c
PB
7732 access |= PFERR_USER_MASK;
7733
7734 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
1871c602
GN
7735}
7736
ce14e868 7737static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5b22bbe7 7738 struct kvm_vcpu *vcpu, u64 access,
ce14e868 7739 struct x86_exception *exception)
77c2002e 7740{
1f5a21ee 7741 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
77c2002e
IE
7742 void *data = val;
7743 int r = X86EMUL_CONTINUE;
7744
7745 while (bytes) {
1f5a21ee 7746 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
77c2002e
IE
7747 unsigned offset = addr & (PAGE_SIZE-1);
7748 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7749 int ret;
7750
6e1d2a3f 7751 if (gpa == INVALID_GPA)
ab9ae313 7752 return X86EMUL_PROPAGATE_FAULT;
54bf36aa 7753 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
77c2002e 7754 if (ret < 0) {
c3cd7ffa 7755 r = X86EMUL_IO_NEEDED;
77c2002e
IE
7756 goto out;
7757 }
7758
7759 bytes -= towrite;
7760 data += towrite;
7761 addr += towrite;
7762 }
7763out:
7764 return r;
7765}
ce14e868
PB
7766
7767static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
3c9fa24c
PB
7768 unsigned int bytes, struct x86_exception *exception,
7769 bool system)
ce14e868
PB
7770{
7771 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5b22bbe7 7772 u64 access = PFERR_WRITE_MASK;
3c9fa24c 7773
4f4aa80e
LJ
7774 if (system)
7775 access |= PFERR_IMPLICIT_ACCESS;
89604647 7776 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
3c9fa24c 7777 access |= PFERR_USER_MASK;
ce14e868
PB
7778
7779 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
3c9fa24c 7780 access, exception);
ce14e868
PB
7781}
7782
7783int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7784 unsigned int bytes, struct x86_exception *exception)
7785{
c595ceee
PB
7786 /* kvm_write_guest_virt_system can pull in tons of pages. */
7787 vcpu->arch.l1tf_flush_l1d = true;
7788
ce14e868
PB
7789 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7790 PFERR_WRITE_MASK, exception);
7791}
6a4d7550 7792EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
77c2002e 7793
aeb904f6
SC
7794static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7795 void *insn, int insn_len)
4d31d9ef 7796{
89604647
WW
7797 return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7798 insn, insn_len);
4d31d9ef
SC
7799}
7800
082d06ed
WL
7801int handle_ud(struct kvm_vcpu *vcpu)
7802{
b3dc0695 7803 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
40aaa5b6 7804 int fep_flags = READ_ONCE(force_emulation_prefix);
6c86eedc 7805 int emul_type = EMULTYPE_TRAP_UD;
6c86eedc
WL
7806 char sig[5]; /* ud2; .ascii "kvm" */
7807 struct x86_exception e;
aeb904f6 7808 int r;
6c86eedc 7809
aeb904f6
SC
7810 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7811 if (r != X86EMUL_CONTINUE)
09e3e2a1
SC
7812 return 1;
7813
40aaa5b6 7814 if (fep_flags &&
3c9fa24c
PB
7815 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7816 sig, sizeof(sig), &e) == 0 &&
b3dc0695 7817 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
40aaa5b6 7818 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
d500e1ed 7819 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
6c86eedc 7820 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
b4000606 7821 emul_type = EMULTYPE_TRAP_UD_FORCED;
6c86eedc 7822 }
082d06ed 7823
60fc3d02 7824 return kvm_emulate_instruction(vcpu, emul_type);
082d06ed
WL
7825}
7826EXPORT_SYMBOL_GPL(handle_ud);
7827
0f89b207
TL
7828static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7829 gpa_t gpa, bool write)
7830{
7831 /* For APIC access vmexit */
7832 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7833 return 1;
7834
7835 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7836 trace_vcpu_match_mmio(gva, gpa, write, true);
7837 return 1;
7838 }
7839
7840 return 0;
7841}
7842
af7cc7d1
XG
7843static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7844 gpa_t *gpa, struct x86_exception *exception,
7845 bool write)
7846{
1f5a21ee 7847 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
89604647
WW
7848 u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7849 | (write ? PFERR_WRITE_MASK : 0);
af7cc7d1 7850
be94f6b7
HH
7851 /*
7852 * currently PKRU is only applied to ept enabled guest so
7853 * there is no pkey in EPT page table for L1 guest or EPT
7854 * shadow page table for L2 guest.
7855 */
908b7d43
SC
7856 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7857 !permission_fault(vcpu, vcpu->arch.walk_mmu,
7858 vcpu->arch.mmio_access, 0, access))) {
bebb106a
XG
7859 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7860 (gva & (PAGE_SIZE - 1));
4f022648 7861 trace_vcpu_match_mmio(gva, *gpa, write, false);
bebb106a
XG
7862 return 1;
7863 }
7864
1f5a21ee 7865 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
af7cc7d1 7866
6e1d2a3f 7867 if (*gpa == INVALID_GPA)
af7cc7d1
XG
7868 return -1;
7869
0f89b207 7870 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
af7cc7d1
XG
7871}
7872
3200f405 7873int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
bcc55cba 7874 const void *val, int bytes)
bbd9b64e
CO
7875{
7876 int ret;
7877
54bf36aa 7878 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
9f811285 7879 if (ret < 0)
bbd9b64e 7880 return 0;
0eb05bf2 7881 kvm_page_track_write(vcpu, gpa, val, bytes);
bbd9b64e
CO
7882 return 1;
7883}
7884
77d197b2
XG
7885struct read_write_emulator_ops {
7886 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7887 int bytes);
7888 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7889 void *val, int bytes);
7890 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7891 int bytes, void *val);
7892 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7893 void *val, int bytes);
7894 bool write;
7895};
7896
7897static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7898{
7899 if (vcpu->mmio_read_completed) {
77d197b2 7900 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
e39d200f 7901 vcpu->mmio_fragments[0].gpa, val);
77d197b2
XG
7902 vcpu->mmio_read_completed = 0;
7903 return 1;
7904 }
7905
7906 return 0;
7907}
7908
7909static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7910 void *val, int bytes)
7911{
54bf36aa 7912 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
77d197b2
XG
7913}
7914
7915static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7916 void *val, int bytes)
7917{
7918 return emulator_write_phys(vcpu, gpa, val, bytes);
7919}
7920
7921static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7922{
e39d200f 7923 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
77d197b2
XG
7924 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7925}
7926
7927static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7928 void *val, int bytes)
7929{
e39d200f 7930 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
77d197b2
XG
7931 return X86EMUL_IO_NEEDED;
7932}
7933
7934static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7935 void *val, int bytes)
7936{
f78146b0
AK
7937 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7938
87da7e66 7939 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
77d197b2
XG
7940 return X86EMUL_CONTINUE;
7941}
7942
0fbe9b0b 7943static const struct read_write_emulator_ops read_emultor = {
77d197b2
XG
7944 .read_write_prepare = read_prepare,
7945 .read_write_emulate = read_emulate,
7946 .read_write_mmio = vcpu_mmio_read,
7947 .read_write_exit_mmio = read_exit_mmio,
7948};
7949
0fbe9b0b 7950static const struct read_write_emulator_ops write_emultor = {
77d197b2
XG
7951 .read_write_emulate = write_emulate,
7952 .read_write_mmio = write_mmio,
7953 .read_write_exit_mmio = write_exit_mmio,
7954 .write = true,
7955};
7956
22388a3c
XG
7957static int emulator_read_write_onepage(unsigned long addr, void *val,
7958 unsigned int bytes,
7959 struct x86_exception *exception,
7960 struct kvm_vcpu *vcpu,
0fbe9b0b 7961 const struct read_write_emulator_ops *ops)
bbd9b64e 7962{
af7cc7d1
XG
7963 gpa_t gpa;
7964 int handled, ret;
22388a3c 7965 bool write = ops->write;
f78146b0 7966 struct kvm_mmio_fragment *frag;
c9b8b07c 7967 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
0f89b207
TL
7968
7969 /*
7970 * If the exit was due to a NPF we may already have a GPA.
7971 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7972 * Note, this cannot be used on string operations since string
7973 * operation using rep will only have the initial GPA from the NPF
7974 * occurred.
7975 */
744e699c
SC
7976 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7977 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7978 gpa = ctxt->gpa_val;
618232e2
BS
7979 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7980 } else {
7981 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7982 if (ret < 0)
7983 return X86EMUL_PROPAGATE_FAULT;
0f89b207 7984 }
10589a46 7985
618232e2 7986 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
bbd9b64e
CO
7987 return X86EMUL_CONTINUE;
7988
bbd9b64e
CO
7989 /*
7990 * Is this MMIO handled locally?
7991 */
22388a3c 7992 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
70252a10 7993 if (handled == bytes)
bbd9b64e 7994 return X86EMUL_CONTINUE;
bbd9b64e 7995
70252a10
AK
7996 gpa += handled;
7997 bytes -= handled;
7998 val += handled;
7999
87da7e66
XG
8000 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8001 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8002 frag->gpa = gpa;
8003 frag->data = val;
8004 frag->len = bytes;
f78146b0 8005 return X86EMUL_CONTINUE;
bbd9b64e
CO
8006}
8007
52eb5a6d
XL
8008static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8009 unsigned long addr,
22388a3c
XG
8010 void *val, unsigned int bytes,
8011 struct x86_exception *exception,
0fbe9b0b 8012 const struct read_write_emulator_ops *ops)
bbd9b64e 8013{
0f65dd70 8014 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
f78146b0
AK
8015 gpa_t gpa;
8016 int rc;
8017
8018 if (ops->read_write_prepare &&
8019 ops->read_write_prepare(vcpu, val, bytes))
8020 return X86EMUL_CONTINUE;
8021
8022 vcpu->mmio_nr_fragments = 0;
0f65dd70 8023
bbd9b64e
CO
8024 /* Crossing a page boundary? */
8025 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
f78146b0 8026 int now;
bbd9b64e
CO
8027
8028 now = -addr & ~PAGE_MASK;
22388a3c
XG
8029 rc = emulator_read_write_onepage(addr, val, now, exception,
8030 vcpu, ops);
8031
bbd9b64e
CO
8032 if (rc != X86EMUL_CONTINUE)
8033 return rc;
8034 addr += now;
bac15531
NA
8035 if (ctxt->mode != X86EMUL_MODE_PROT64)
8036 addr = (u32)addr;
bbd9b64e
CO
8037 val += now;
8038 bytes -= now;
8039 }
22388a3c 8040
f78146b0
AK
8041 rc = emulator_read_write_onepage(addr, val, bytes, exception,
8042 vcpu, ops);
8043 if (rc != X86EMUL_CONTINUE)
8044 return rc;
8045
8046 if (!vcpu->mmio_nr_fragments)
f804dc6a 8047 return X86EMUL_CONTINUE;
f78146b0
AK
8048
8049 gpa = vcpu->mmio_fragments[0].gpa;
8050
8051 vcpu->mmio_needed = 1;
8052 vcpu->mmio_cur_fragment = 0;
8053
87da7e66 8054 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
f78146b0
AK
8055 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8056 vcpu->run->exit_reason = KVM_EXIT_MMIO;
8057 vcpu->run->mmio.phys_addr = gpa;
8058
8059 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
22388a3c
XG
8060}
8061
8062static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8063 unsigned long addr,
8064 void *val,
8065 unsigned int bytes,
8066 struct x86_exception *exception)
8067{
8068 return emulator_read_write(ctxt, addr, val, bytes,
8069 exception, &read_emultor);
8070}
8071
52eb5a6d 8072static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
22388a3c
XG
8073 unsigned long addr,
8074 const void *val,
8075 unsigned int bytes,
8076 struct x86_exception *exception)
8077{
8078 return emulator_read_write(ctxt, addr, (void *)val, bytes,
8079 exception, &write_emultor);
bbd9b64e 8080}
bbd9b64e 8081
1c2361f6
SC
8082#define emulator_try_cmpxchg_user(t, ptr, old, new) \
8083 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
daea3e73 8084
0f65dd70
AK
8085static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8086 unsigned long addr,
bbd9b64e
CO
8087 const void *old,
8088 const void *new,
8089 unsigned int bytes,
0f65dd70 8090 struct x86_exception *exception)
bbd9b64e 8091{
0f65dd70 8092 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9de6fe3c 8093 u64 page_line_mask;
1c2361f6 8094 unsigned long hva;
daea3e73 8095 gpa_t gpa;
1c2361f6 8096 int r;
2bacc55c 8097
daea3e73
AK
8098 /* guests cmpxchg8b have to be emulated atomically */
8099 if (bytes > 8 || (bytes & (bytes - 1)))
8100 goto emul_write;
10589a46 8101
daea3e73 8102 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
2bacc55c 8103
6e1d2a3f 8104 if (gpa == INVALID_GPA ||
daea3e73
AK
8105 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8106 goto emul_write;
2bacc55c 8107
9de6fe3c
XL
8108 /*
8109 * Emulate the atomic as a straight write to avoid #AC if SLD is
8110 * enabled in the host and the access splits a cache line.
8111 */
8112 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8113 page_line_mask = ~(cache_line_size() - 1);
8114 else
8115 page_line_mask = PAGE_MASK;
8116
8117 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
daea3e73 8118 goto emul_write;
72dc67a6 8119
1c2361f6 8120 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
33fbe6be 8121 if (kvm_is_error_hva(hva))
c19b8bd6 8122 goto emul_write;
72dc67a6 8123
1c2361f6 8124 hva += offset_in_page(gpa);
42e35f80 8125
daea3e73
AK
8126 switch (bytes) {
8127 case 1:
1c2361f6 8128 r = emulator_try_cmpxchg_user(u8, hva, old, new);
daea3e73
AK
8129 break;
8130 case 2:
1c2361f6 8131 r = emulator_try_cmpxchg_user(u16, hva, old, new);
daea3e73
AK
8132 break;
8133 case 4:
1c2361f6 8134 r = emulator_try_cmpxchg_user(u32, hva, old, new);
daea3e73
AK
8135 break;
8136 case 8:
1c2361f6 8137 r = emulator_try_cmpxchg_user(u64, hva, old, new);
daea3e73
AK
8138 break;
8139 default:
8140 BUG();
2bacc55c 8141 }
42e35f80 8142
1c2361f6 8143 if (r < 0)
5d6c7de6 8144 return X86EMUL_UNHANDLEABLE;
910c57df
SC
8145
8146 /*
8147 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8148 * successful, as the old value is written back on failure. Note, for
8149 * live migration, this is unnecessarily conservative as CMPXCHG writes
8150 * back the original value and the access is atomic, but KVM's ABI is
8151 * that all writes are dirty logged, regardless of the value written.
8152 */
8153 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8154
1c2361f6 8155 if (r)
daea3e73
AK
8156 return X86EMUL_CMPXCHG_FAILED;
8157
0eb05bf2 8158 kvm_page_track_write(vcpu, gpa, new, bytes);
8f6abd06
GN
8159
8160 return X86EMUL_CONTINUE;
4a5f48f6 8161
3200f405 8162emul_write:
8d20bd63 8163 pr_warn_once("emulating exchange as write\n");
2bacc55c 8164
0f65dd70 8165 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
bbd9b64e
CO
8166}
8167
6f6fbe98 8168static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
30d583fd 8169 unsigned short port, void *data,
6f6fbe98 8170 unsigned int count, bool in)
cf8f70bf 8171{
0f87ac23
PB
8172 unsigned i;
8173 int r;
cf8f70bf 8174
30d583fd 8175 WARN_ON_ONCE(vcpu->arch.pio.count);
0f87ac23
PB
8176 for (i = 0; i < count; i++) {
8177 if (in)
8178 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
cbfc6c91 8179 else
0f87ac23 8180 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
35ab3b77
PB
8181
8182 if (r) {
8183 if (i == 0)
8184 goto userspace_io;
8185
8186 /*
8187 * Userspace must have unregistered the device while PIO
0c05e10b 8188 * was running. Drop writes / read as 0.
35ab3b77 8189 */
0c05e10b
PB
8190 if (in)
8191 memset(data, 0, size * (count - i));
cbfc6c91 8192 break;
35ab3b77
PB
8193 }
8194
0f87ac23 8195 data += size;
cbfc6c91 8196 }
0f87ac23 8197 return 1;
cf8f70bf 8198
0f87ac23 8199userspace_io:
cf8f70bf 8200 vcpu->arch.pio.port = port;
6f6fbe98 8201 vcpu->arch.pio.in = in;
0c05e10b 8202 vcpu->arch.pio.count = count;
cf8f70bf
GN
8203 vcpu->arch.pio.size = size;
8204
0c05e10b
PB
8205 if (in)
8206 memset(vcpu->arch.pio_data, 0, size * count);
8207 else
8208 memcpy(vcpu->arch.pio_data, data, size * count);
cf8f70bf
GN
8209
8210 vcpu->run->exit_reason = KVM_EXIT_IO;
6f6fbe98 8211 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
cf8f70bf
GN
8212 vcpu->run->io.size = size;
8213 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8214 vcpu->run->io.count = count;
8215 vcpu->run->io.port = port;
cf8f70bf
GN
8216 return 0;
8217}
8218
f35cee4a
PB
8219static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8220 unsigned short port, void *val, unsigned int count)
cf8f70bf 8221{
0c05e10b
PB
8222 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8223 if (r)
8224 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8225
8226 return r;
3b27de27 8227}
ca1d4a9e 8228
6b5efc93 8229static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
3b27de27 8230{
6b5efc93 8231 int size = vcpu->arch.pio.size;
0c05e10b 8232 unsigned int count = vcpu->arch.pio.count;
6b5efc93
PB
8233 memcpy(val, vcpu->arch.pio_data, size * count);
8234 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
3b27de27
PB
8235 vcpu->arch.pio.count = 0;
8236}
cf8f70bf 8237
f35cee4a
PB
8238static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8239 int size, unsigned short port, void *val,
8240 unsigned int count)
3b27de27 8241{
f35cee4a 8242 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3b27de27 8243 if (vcpu->arch.pio.count) {
d07898ea
SC
8244 /*
8245 * Complete a previous iteration that required userspace I/O.
8246 * Note, @count isn't guaranteed to match pio.count as userspace
8247 * can modify ECX before rerunning the vCPU. Ignore any such
8248 * shenanigans as KVM doesn't support modifying the rep count,
8249 * and the emulator ensures @count doesn't overflow the buffer.
8250 */
0c05e10b
PB
8251 complete_emulator_pio_in(vcpu, val);
8252 return 1;
cf8f70bf
GN
8253 }
8254
f35cee4a 8255 return emulator_pio_in(vcpu, size, port, val, count);
2e3bb4d8 8256}
6f6fbe98 8257
2e3bb4d8
SC
8258static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8259 unsigned short port, const void *val,
8260 unsigned int count)
8261{
30d583fd 8262 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
0c05e10b 8263 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6f6fbe98
XG
8264}
8265
2e3bb4d8
SC
8266static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8267 int size, unsigned short port,
8268 const void *val, unsigned int count)
8269{
8270 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8271}
8272
bbd9b64e
CO
8273static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8274{
89604647 8275 return kvm_x86_call(get_segment_base)(vcpu, seg);
bbd9b64e
CO
8276}
8277
3cb16fe7 8278static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
bbd9b64e 8279{
3cb16fe7 8280 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
bbd9b64e
CO
8281}
8282
ae6a2375 8283static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
f5f48ee1
SY
8284{
8285 if (!need_emulate_wbinvd(vcpu))
8286 return X86EMUL_CONTINUE;
8287
89604647 8288 if (kvm_x86_call(has_wbinvd_exit)()) {
2eec7343
JK
8289 int cpu = get_cpu();
8290
8291 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
c2162e13 8292 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
f5f48ee1 8293 wbinvd_ipi, NULL, 1);
2eec7343 8294 put_cpu();
f5f48ee1 8295 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
2eec7343
JK
8296 } else
8297 wbinvd();
f5f48ee1
SY
8298 return X86EMUL_CONTINUE;
8299}
5cb56059
JS
8300
8301int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8302{
6affcbed
KH
8303 kvm_emulate_wbinvd_noskip(vcpu);
8304 return kvm_skip_emulated_instruction(vcpu);
5cb56059 8305}
f5f48ee1
SY
8306EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8307
5cb56059
JS
8308
8309
bcaf5cc5
AK
8310static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8311{
5cb56059 8312 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
bcaf5cc5
AK
8313}
8314
fc5375dd 8315static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
bbd9b64e 8316{
fc5375dd 8317 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
bbd9b64e
CO
8318}
8319
52eb5a6d
XL
8320static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8321 unsigned long value)
bbd9b64e 8322{
338dbc97 8323
996ff542 8324 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
bbd9b64e
CO
8325}
8326
52a46617 8327static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5fdbf976 8328{
52a46617 8329 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5fdbf976
MT
8330}
8331
717746e3 8332static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
bbd9b64e 8333{
717746e3 8334 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
52a46617
GN
8335 unsigned long value;
8336
8337 switch (cr) {
8338 case 0:
8339 value = kvm_read_cr0(vcpu);
8340 break;
8341 case 2:
8342 value = vcpu->arch.cr2;
8343 break;
8344 case 3:
9f8fe504 8345 value = kvm_read_cr3(vcpu);
52a46617
GN
8346 break;
8347 case 4:
8348 value = kvm_read_cr4(vcpu);
8349 break;
8350 case 8:
8351 value = kvm_get_cr8(vcpu);
8352 break;
8353 default:
a737f256 8354 kvm_err("%s: unexpected cr %u\n", __func__, cr);
52a46617
GN
8355 return 0;
8356 }
8357
8358 return value;
8359}
8360
717746e3 8361static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
52a46617 8362{
717746e3 8363 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
0f12244f
GN
8364 int res = 0;
8365
52a46617
GN
8366 switch (cr) {
8367 case 0:
49a9b07e 8368 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
52a46617
GN
8369 break;
8370 case 2:
8371 vcpu->arch.cr2 = val;
8372 break;
8373 case 3:
2390218b 8374 res = kvm_set_cr3(vcpu, val);
52a46617
GN
8375 break;
8376 case 4:
a83b29c6 8377 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
52a46617
GN
8378 break;
8379 case 8:
eea1cff9 8380 res = kvm_set_cr8(vcpu, val);
52a46617
GN
8381 break;
8382 default:
a737f256 8383 kvm_err("%s: unexpected cr %u\n", __func__, cr);
0f12244f 8384 res = -1;
52a46617 8385 }
0f12244f
GN
8386
8387 return res;
52a46617
GN
8388}
8389
717746e3 8390static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
9c537244 8391{
89604647 8392 return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
9c537244
GN
8393}
8394
4bff1e86 8395static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
2dafc6c2 8396{
89604647 8397 kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
2dafc6c2
GN
8398}
8399
4bff1e86 8400static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
160ce1f1 8401{
89604647 8402 kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
160ce1f1
MG
8403}
8404
1ac9d0cf
AK
8405static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8406{
89604647 8407 kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
8408}
8409
8410static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8411{
89604647 8412 kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
8413}
8414
4bff1e86
AK
8415static unsigned long emulator_get_cached_segment_base(
8416 struct x86_emulate_ctxt *ctxt, int seg)
5951c442 8417{
4bff1e86 8418 return get_segment_base(emul_to_vcpu(ctxt), seg);
5951c442
GN
8419}
8420
1aa36616
AK
8421static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8422 struct desc_struct *desc, u32 *base3,
8423 int seg)
2dafc6c2
GN
8424{
8425 struct kvm_segment var;
8426
4bff1e86 8427 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
1aa36616 8428 *selector = var.selector;
2dafc6c2 8429
378a8b09
GN
8430 if (var.unusable) {
8431 memset(desc, 0, sizeof(*desc));
f0367ee1
RK
8432 if (base3)
8433 *base3 = 0;
2dafc6c2 8434 return false;
378a8b09 8435 }
2dafc6c2
GN
8436
8437 if (var.g)
8438 var.limit >>= 12;
8439 set_desc_limit(desc, var.limit);
8440 set_desc_base(desc, (unsigned long)var.base);
5601d05b
GN
8441#ifdef CONFIG_X86_64
8442 if (base3)
8443 *base3 = var.base >> 32;
8444#endif
2dafc6c2
GN
8445 desc->type = var.type;
8446 desc->s = var.s;
8447 desc->dpl = var.dpl;
8448 desc->p = var.present;
8449 desc->avl = var.avl;
8450 desc->l = var.l;
8451 desc->d = var.db;
8452 desc->g = var.g;
8453
8454 return true;
8455}
8456
1aa36616
AK
8457static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8458 struct desc_struct *desc, u32 base3,
8459 int seg)
2dafc6c2 8460{
4bff1e86 8461 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
2dafc6c2
GN
8462 struct kvm_segment var;
8463
1aa36616 8464 var.selector = selector;
2dafc6c2 8465 var.base = get_desc_base(desc);
5601d05b
GN
8466#ifdef CONFIG_X86_64
8467 var.base |= ((u64)base3) << 32;
8468#endif
2dafc6c2
GN
8469 var.limit = get_desc_limit(desc);
8470 if (desc->g)
8471 var.limit = (var.limit << 12) | 0xfff;
8472 var.type = desc->type;
2dafc6c2
GN
8473 var.dpl = desc->dpl;
8474 var.db = desc->d;
8475 var.s = desc->s;
8476 var.l = desc->l;
8477 var.g = desc->g;
8478 var.avl = desc->avl;
8479 var.present = desc->p;
8480 var.unusable = !var.present;
8481 var.padding = 0;
8482
8483 kvm_set_segment(vcpu, &var, seg);
8484 return;
8485}
8486
ac8d6cad
HW
8487static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8488 u32 msr_index, u64 *pdata)
717746e3 8489{
1ae09954
AG
8490 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8491 int r;
8492
ac8d6cad 8493 r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
36d546d5
HW
8494 if (r < 0)
8495 return X86EMUL_UNHANDLEABLE;
1ae09954 8496
36d546d5
HW
8497 if (r) {
8498 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8499 complete_emulated_rdmsr, r))
8500 return X86EMUL_IO_NEEDED;
794663e1
HW
8501
8502 trace_kvm_msr_read_ex(msr_index);
36d546d5 8503 return X86EMUL_PROPAGATE_FAULT;
1ae09954
AG
8504 }
8505
794663e1 8506 trace_kvm_msr_read(msr_index, *pdata);
36d546d5 8507 return X86EMUL_CONTINUE;
717746e3
AK
8508}
8509
ac8d6cad
HW
8510static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8511 u32 msr_index, u64 data)
717746e3 8512{
1ae09954
AG
8513 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8514 int r;
8515
ac8d6cad 8516 r = kvm_set_msr_with_filter(vcpu, msr_index, data);
36d546d5
HW
8517 if (r < 0)
8518 return X86EMUL_UNHANDLEABLE;
1ae09954 8519
36d546d5
HW
8520 if (r) {
8521 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8522 complete_emulated_msr_access, r))
8523 return X86EMUL_IO_NEEDED;
794663e1
HW
8524
8525 trace_kvm_msr_write_ex(msr_index, data);
36d546d5 8526 return X86EMUL_PROPAGATE_FAULT;
1ae09954
AG
8527 }
8528
794663e1 8529 trace_kvm_msr_write(msr_index, data);
36d546d5 8530 return X86EMUL_CONTINUE;
717746e3
AK
8531}
8532
ac8d6cad
HW
8533static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8534 u32 msr_index, u64 *pdata)
8535{
8536 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8537}
8538
7bb7fce1 8539static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
67f4d428 8540{
7bb7fce1 8541 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
67f4d428
NA
8542}
8543
222d21aa
AK
8544static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8545 u32 pmc, u64 *pdata)
8546{
c6702c9d 8547 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
222d21aa
AK
8548}
8549
6c3287f7
AK
8550static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8551{
8552 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8553}
8554
2953538e 8555static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8a76d7f2 8556 struct x86_instruction_info *info,
c4f035c6
AK
8557 enum x86_intercept_stage stage)
8558{
89604647
WW
8559 return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8560 &ctxt->exception);
c4f035c6
AK
8561}
8562
e911eb3b 8563static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
f91af517
SC
8564 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8565 bool exact_only)
bdb42f5a 8566{
f91af517 8567 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
bdb42f5a
SB
8568}
8569
5ae78e95
SC
8570static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8571{
8f2a2775 8572 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
5ae78e95
SC
8573}
8574
8575static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8576{
8f2a2775 8577 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
5ae78e95
SC
8578}
8579
a836839c
HW
8580static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8581{
8f2a2775 8582 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
a836839c
HW
8583}
8584
d99e4cb2
SC
8585static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8586{
8587 return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8588}
8589
dd856efa
AK
8590static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8591{
27b4a9c4 8592 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
dd856efa
AK
8593}
8594
8595static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8596{
27b4a9c4 8597 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
dd856efa
AK
8598}
8599
801806d9
NA
8600static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8601{
89604647 8602 kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
801806d9
NA
8603}
8604
32e69f23 8605static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
6ed071f0 8606{
32e69f23
ML
8607 return is_smm(emul_to_vcpu(ctxt));
8608}
8609
8610static bool emulator_is_guest_mode(struct x86_emulate_ctxt *ctxt)
6ed071f0 8611{
32e69f23 8612 return is_guest_mode(emul_to_vcpu(ctxt));
6ed071f0
LP
8613}
8614
4b8e1b32
PB
8615#ifndef CONFIG_KVM_SMM
8616static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
6ed071f0 8617{
4b8e1b32
PB
8618 WARN_ON_ONCE(1);
8619 return X86EMUL_UNHANDLEABLE;
0234bf88 8620}
4b8e1b32 8621#endif
0234bf88 8622
25b17226
SC
8623static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8624{
8625 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8626}
8627
02d4160f
VK
8628static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8629{
8630 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8631}
8632
1cca2f8c
SC
8633static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8634{
8635 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8636
8637 if (!kvm->vm_bugged)
8638 kvm_vm_bugged(kvm);
8639}
8640
37a41847
BW
8641static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8642 gva_t addr, unsigned int flags)
8643{
8644 if (!kvm_x86_ops.get_untagged_addr)
8645 return addr;
8646
89604647
WW
8647 return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8648 addr, flags);
37a41847
BW
8649}
8650
16ccadef 8651static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
c534b37b 8652 gva_t addr, unsigned int flags)
16ccadef 8653{
9245fd6b 8654 return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
16ccadef
ML
8655}
8656
0225fb50 8657static const struct x86_emulate_ops emulate_ops = {
1cca2f8c 8658 .vm_bugged = emulator_vm_bugged,
dd856efa
AK
8659 .read_gpr = emulator_read_gpr,
8660 .write_gpr = emulator_write_gpr,
ce14e868
PB
8661 .read_std = emulator_read_std,
8662 .write_std = emulator_write_std,
1871c602 8663 .fetch = kvm_fetch_guest_virt,
bbd9b64e
CO
8664 .read_emulated = emulator_read_emulated,
8665 .write_emulated = emulator_write_emulated,
8666 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3cb16fe7 8667 .invlpg = emulator_invlpg,
cf8f70bf
GN
8668 .pio_in_emulated = emulator_pio_in_emulated,
8669 .pio_out_emulated = emulator_pio_out_emulated,
1aa36616
AK
8670 .get_segment = emulator_get_segment,
8671 .set_segment = emulator_set_segment,
5951c442 8672 .get_cached_segment_base = emulator_get_cached_segment_base,
2dafc6c2 8673 .get_gdt = emulator_get_gdt,
160ce1f1 8674 .get_idt = emulator_get_idt,
1ac9d0cf
AK
8675 .set_gdt = emulator_set_gdt,
8676 .set_idt = emulator_set_idt,
52a46617
GN
8677 .get_cr = emulator_get_cr,
8678 .set_cr = emulator_set_cr,
9c537244 8679 .cpl = emulator_get_cpl,
35aa5375
GN
8680 .get_dr = emulator_get_dr,
8681 .set_dr = emulator_set_dr,
ac8d6cad
HW
8682 .set_msr_with_filter = emulator_set_msr_with_filter,
8683 .get_msr_with_filter = emulator_get_msr_with_filter,
717746e3 8684 .get_msr = emulator_get_msr,
7bb7fce1 8685 .check_rdpmc_early = emulator_check_rdpmc_early,
222d21aa 8686 .read_pmc = emulator_read_pmc,
6c3287f7 8687 .halt = emulator_halt,
bcaf5cc5 8688 .wbinvd = emulator_wbinvd,
d6aa1000 8689 .fix_hypercall = emulator_fix_hypercall,
c4f035c6 8690 .intercept = emulator_intercept,
bdb42f5a 8691 .get_cpuid = emulator_get_cpuid,
5ae78e95
SC
8692 .guest_has_movbe = emulator_guest_has_movbe,
8693 .guest_has_fxsr = emulator_guest_has_fxsr,
a836839c 8694 .guest_has_rdpid = emulator_guest_has_rdpid,
d99e4cb2 8695 .guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
801806d9 8696 .set_nmi_mask = emulator_set_nmi_mask,
32e69f23
ML
8697 .is_smm = emulator_is_smm,
8698 .is_guest_mode = emulator_is_guest_mode,
ecc513e5 8699 .leave_smm = emulator_leave_smm,
25b17226 8700 .triple_fault = emulator_triple_fault,
02d4160f 8701 .set_xcr = emulator_set_xcr,
37a41847 8702 .get_untagged_addr = emulator_get_untagged_addr,
16ccadef 8703 .is_canonical_addr = emulator_is_canonical_addr,
bbd9b64e
CO
8704};
8705
95cb2295
GN
8706static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8707{
89604647 8708 u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
95cb2295
GN
8709 /*
8710 * an sti; sti; sequence only disable interrupts for the first
8711 * instruction. So, if the last instruction, be it emulated or
8712 * not, left the system with the INT_STI flag enabled, it
8713 * means that the last instruction is an sti. We should not
8714 * leave the flag on in this case. The same goes for mov ss
8715 */
37ccdcbe
PB
8716 if (int_shadow & mask)
8717 mask = 0;
6addfc42 8718 if (unlikely(int_shadow || mask)) {
89604647 8719 kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
6addfc42
PB
8720 if (!mask)
8721 kvm_make_request(KVM_REQ_EVENT, vcpu);
8722 }
95cb2295
GN
8723}
8724
7709aba8 8725static void inject_emulated_exception(struct kvm_vcpu *vcpu)
54b8486f 8726{
c9b8b07c 8727 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
ef54bcfe 8728
7709aba8
SC
8729 if (ctxt->exception.vector == PF_VECTOR)
8730 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8731 else if (ctxt->exception.error_code_valid)
da9cb575
AK
8732 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8733 ctxt->exception.error_code);
54b8486f 8734 else
da9cb575 8735 kvm_queue_exception(vcpu, ctxt->exception.vector);
54b8486f
GN
8736}
8737
c9b8b07c
SC
8738static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8739{
8740 struct x86_emulate_ctxt *ctxt;
8741
8742 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8743 if (!ctxt) {
8d20bd63 8744 pr_err("failed to allocate vcpu's emulator\n");
c9b8b07c
SC
8745 return NULL;
8746 }
8747
8748 ctxt->vcpu = vcpu;
8749 ctxt->ops = &emulate_ops;
8750 vcpu->arch.emulate_ctxt = ctxt;
8751
8752 return ctxt;
8753}
8754
8ec4722d
MG
8755static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8756{
c9b8b07c 8757 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d
MG
8758 int cs_db, cs_l;
8759
89604647 8760 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8ec4722d 8761
744e699c 8762 ctxt->gpa_available = false;
adf52235 8763 ctxt->eflags = kvm_get_rflags(vcpu);
c8401dda
PB
8764 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8765
adf52235
TY
8766 ctxt->eip = kvm_rip_read(vcpu);
8767 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8768 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
42bf549f 8769 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
adf52235
TY
8770 cs_db ? X86EMUL_MODE_PROT32 :
8771 X86EMUL_MODE_PROT16;
da6393cd
WL
8772 ctxt->interruptibility = 0;
8773 ctxt->have_exception = false;
8774 ctxt->exception.vector = -1;
8775 ctxt->perm_ok = false;
8776
dd856efa 8777 init_decode_cache(ctxt);
7ae441ea 8778 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8ec4722d
MG
8779}
8780
9497e1f2 8781void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
63995653 8782{
c9b8b07c 8783 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
63995653
MG
8784 int ret;
8785
8786 init_emulate_ctxt(vcpu);
8787
9dac77fa
AK
8788 ctxt->op_bytes = 2;
8789 ctxt->ad_bytes = 2;
8790 ctxt->_eip = ctxt->eip + inc_eip;
9d74191a 8791 ret = emulate_int_real(ctxt, irq);
63995653 8792
9497e1f2
SC
8793 if (ret != X86EMUL_CONTINUE) {
8794 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8795 } else {
8796 ctxt->eip = ctxt->_eip;
8797 kvm_rip_write(vcpu, ctxt->eip);
8798 kvm_set_rflags(vcpu, ctxt->eflags);
8799 }
63995653
MG
8800}
8801EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8802
e615e355
DE
8803static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8804 u8 ndata, u8 *insn_bytes, u8 insn_size)
19238e75 8805{
19238e75 8806 struct kvm_run *run = vcpu->run;
e615e355
DE
8807 u64 info[5];
8808 u8 info_start;
8809
8810 /*
8811 * Zero the whole array used to retrieve the exit info, as casting to
8812 * u32 for select entries will leave some chunks uninitialized.
8813 */
8814 memset(&info, 0, sizeof(info));
8815
89604647
WW
8816 kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
8817 (u32 *)&info[3], (u32 *)&info[4]);
19238e75
AL
8818
8819 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8820 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
e615e355
DE
8821
8822 /*
8823 * There's currently space for 13 entries, but 5 are used for the exit
8824 * reason and info. Restrict to 4 to reduce the maintenance burden
8825 * when expanding kvm_run.emulation_failure in the future.
8826 */
8827 if (WARN_ON_ONCE(ndata > 4))
8828 ndata = 4;
8829
8830 /* Always include the flags as a 'data' entry. */
8831 info_start = 1;
19238e75
AL
8832 run->emulation_failure.flags = 0;
8833
8834 if (insn_size) {
e615e355
DE
8835 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8836 sizeof(run->emulation_failure.insn_bytes) != 16));
8837 info_start += 2;
19238e75
AL
8838 run->emulation_failure.flags |=
8839 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8840 run->emulation_failure.insn_size = insn_size;
8841 memset(run->emulation_failure.insn_bytes, 0x90,
8842 sizeof(run->emulation_failure.insn_bytes));
e615e355 8843 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
19238e75 8844 }
e615e355
DE
8845
8846 memcpy(&run->internal.data[info_start], info, sizeof(info));
8847 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8848 ndata * sizeof(data[0]));
8849
8850 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
19238e75
AL
8851}
8852
e615e355
DE
8853static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8854{
8855 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8856
8857 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8858 ctxt->fetch.end - ctxt->fetch.data);
8859}
8860
8861void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8862 u8 ndata)
8863{
8864 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
19238e75 8865}
e615e355
DE
8866EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8867
8868void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8869{
8870 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8871}
8872EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
19238e75 8873
11c98fa0
IO
8874void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
8875{
8876 u32 reason, intr_info, error_code;
8877 struct kvm_run *run = vcpu->run;
8878 u64 info1, info2;
8879 int ndata = 0;
8880
8881 kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
8882 &intr_info, &error_code);
8883
8884 run->internal.data[ndata++] = info2;
8885 run->internal.data[ndata++] = reason;
8886 run->internal.data[ndata++] = info1;
8887 run->internal.data[ndata++] = gpa;
8888 run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
8889
8890 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8891 run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8892 run->internal.ndata = ndata;
8893}
8894EXPORT_SYMBOL_GPL(kvm_prepare_event_vectoring_exit);
8895
e2366171 8896static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6d77dbfc 8897{
19238e75
AL
8898 struct kvm *kvm = vcpu->kvm;
8899
6d77dbfc
GN
8900 ++vcpu->stat.insn_emulation_fail;
8901 trace_kvm_emulate_insn_failed(vcpu);
e2366171 8902
42cbf068
SC
8903 if (emulation_type & EMULTYPE_VMWARE_GP) {
8904 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 8905 return 1;
42cbf068 8906 }
e2366171 8907
19238e75
AL
8908 if (kvm->arch.exit_on_emulation_error ||
8909 (emulation_type & EMULTYPE_SKIP)) {
e615e355 8910 prepare_emulation_ctxt_failure_exit(vcpu);
60fc3d02 8911 return 0;
738fece4
SC
8912 }
8913
22da61c9
SC
8914 kvm_queue_exception(vcpu, UD_VECTOR);
8915
89604647 8916 if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
e615e355 8917 prepare_emulation_ctxt_failure_exit(vcpu);
60fc3d02 8918 return 0;
fc3a9157 8919 }
e2366171 8920
60fc3d02 8921 return 1;
6d77dbfc
GN
8922}
8923
2876624e
SC
8924static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
8925 gpa_t cr2_or_gpa,
8926 int emulation_type)
a6f177ef 8927{
92daa48b 8928 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
991eebf9
GN
8929 return false;
8930
93c05d3e 8931 /*
515c18a6
SC
8932 * If the failed instruction faulted on an access to page tables that
8933 * are used to translate any part of the instruction, KVM can't resolve
8934 * the issue by unprotecting the gfn, as zapping the shadow page will
8935 * result in the instruction taking a !PRESENT page fault and thus put
8936 * the vCPU into an infinite loop of page faults. E.g. KVM will create
8937 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8938 * then zap the SPTE to unprotect the gfn, and then do it all over
8939 * again. Report the error to userspace.
93c05d3e 8940 */
19ab2c8b
SC
8941 if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
8942 return false;
1cb3f3ae
XG
8943
8944 /*
515c18a6
SC
8945 * If emulation may have been triggered by a write to a shadowed page
8946 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8947 * guest to let the CPU re-execute the instruction in the hope that the
8948 * CPU can cleanly execute the instruction that KVM failed to emulate.
1cb3f3ae 8949 */
4df68566 8950 __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
1cb3f3ae 8951
93c05d3e 8952 /*
19ab2c8b
SC
8953 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
8954 * all SPTEs were already zapped by a different task. The alternative
8955 * is to report the error to userspace and likely terminate the guest,
8956 * and the last_retry_{eip,addr} checks will prevent retrying the page
8957 * fault indefinitely, i.e. there's nothing to lose by retrying.
93c05d3e 8958 */
1cb3f3ae
XG
8959 return true;
8960}
8961
716d51ab
GN
8962static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8963static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8964
4a1e10d5
PB
8965static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8966 unsigned long *db)
8967{
8968 u32 dr6 = 0;
8969 int i;
8970 u32 enable, rwlen;
8971
8972 enable = dr7;
8973 rwlen = dr7 >> 16;
8974 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8975 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8976 dr6 |= (1 << i);
8977 return dr6;
8978}
8979
120c2c4f 8980static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
663f4c61
PB
8981{
8982 struct kvm_run *kvm_run = vcpu->run;
8983
c8401dda 8984 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9a3ecd5e 8985 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
d5d260c5 8986 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
c8401dda
PB
8987 kvm_run->debug.arch.exception = DB_VECTOR;
8988 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 8989 return 0;
663f4c61 8990 }
120c2c4f 8991 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
60fc3d02 8992 return 1;
663f4c61
PB
8993}
8994
6affcbed
KH
8995int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8996{
89604647 8997 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
f8ea7c60 8998 int r;
6affcbed 8999
89604647 9000 r = kvm_x86_call(skip_emulated_instruction)(vcpu);
60fc3d02 9001 if (unlikely(!r))
f8ea7c60 9002 return 0;
c8401dda 9003
f19063b1 9004 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9cd803d4 9005
c8401dda
PB
9006 /*
9007 * rflags is the old, "raw" value of the flags. The new value has
9008 * not been saved yet.
9009 *
9010 * This is correct even for TF set by the guest, because "the
9011 * processor will not generate this exception after the instruction
9012 * that sets the TF flag".
9013 */
9014 if (unlikely(rflags & X86_EFLAGS_TF))
120c2c4f 9015 r = kvm_vcpu_do_singlestep(vcpu);
60fc3d02 9016 return r;
6affcbed
KH
9017}
9018EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
9019
baf67ca8 9020static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
4a1e10d5 9021{
baf67ca8
SC
9022 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9023 return true;
9024
9025 /*
c092fc87
SC
9026 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9027 * active, but AMD compatible CPUs do not.
baf67ca8 9028 */
c092fc87
SC
9029 if (!guest_cpuid_is_intel_compatible(vcpu))
9030 return false;
9031
89604647 9032 return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
baf67ca8
SC
9033}
9034
750f8fcb
SC
9035static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9036 int emulation_type, int *r)
4a1e10d5 9037{
750f8fcb
SC
9038 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9039
9040 /*
9041 * Do not check for code breakpoints if hardware has already done the
9042 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9043 * the instruction has passed all exception checks, and all intercepted
9044 * exceptions that trigger emulation have lower priority than code
9045 * breakpoints, i.e. the fact that the intercepted exception occurred
9046 * means any code breakpoints have already been serviced.
9047 *
9048 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9049 * hardware has checked the RIP of the magic prefix, but not the RIP of
9050 * the instruction being emulated. The intent of forced emulation is
9051 * to behave as if KVM intercepted the instruction without an exception
9052 * and without a prefix.
9053 */
9054 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9055 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9056 return false;
9057
4a1e10d5
PB
9058 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9059 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
82b32774
NA
9060 struct kvm_run *kvm_run = vcpu->run;
9061 unsigned long eip = kvm_get_linear_rip(vcpu);
9062 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
9063 vcpu->arch.guest_debug_dr7,
9064 vcpu->arch.eff_db);
9065
9066 if (dr6 != 0) {
9a3ecd5e 9067 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
82b32774 9068 kvm_run->debug.arch.pc = eip;
4a1e10d5
PB
9069 kvm_run->debug.arch.exception = DB_VECTOR;
9070 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 9071 *r = 0;
4a1e10d5
PB
9072 return true;
9073 }
9074 }
9075
4161a569 9076 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
baf67ca8 9077 !kvm_is_code_breakpoint_inhibited(vcpu)) {
82b32774
NA
9078 unsigned long eip = kvm_get_linear_rip(vcpu);
9079 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
9080 vcpu->arch.dr7,
9081 vcpu->arch.db);
9082
9083 if (dr6 != 0) {
4d5523cf 9084 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
60fc3d02 9085 *r = 1;
4a1e10d5
PB
9086 return true;
9087 }
9088 }
9089
9090 return false;
9091}
9092
04789b66
LA
9093static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9094{
2d7921c4
AM
9095 switch (ctxt->opcode_len) {
9096 case 1:
9097 switch (ctxt->b) {
9098 case 0xe4: /* IN */
9099 case 0xe5:
9100 case 0xec:
9101 case 0xed:
9102 case 0xe6: /* OUT */
9103 case 0xe7:
9104 case 0xee:
9105 case 0xef:
9106 case 0x6c: /* INS */
9107 case 0x6d:
9108 case 0x6e: /* OUTS */
9109 case 0x6f:
9110 return true;
9111 }
9112 break;
9113 case 2:
9114 switch (ctxt->b) {
9115 case 0x33: /* RDPMC */
9116 return true;
9117 }
9118 break;
04789b66
LA
9119 }
9120
9121 return false;
9122}
9123
4aa2691d 9124/*
fee060cd
SC
9125 * Decode an instruction for emulation. The caller is responsible for handling
9126 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9127 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9128 * code breakpoints have higher priority and thus have already been done by
9129 * hardware.
9130 *
9131 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9132 * response to a machine check.
4aa2691d
WH
9133 */
9134int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9135 void *insn, int insn_len)
9136{
4aa2691d 9137 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
fee060cd 9138 int r;
4aa2691d
WH
9139
9140 init_emulate_ctxt(vcpu);
9141
b35491e6 9142 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
4aa2691d
WH
9143
9144 trace_kvm_emulate_insn_start(vcpu);
9145 ++vcpu->stat.insn_emulation;
9146
9147 return r;
9148}
9149EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9150
736c291c
SC
9151int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9152 int emulation_type, void *insn, int insn_len)
bbd9b64e 9153{
95cb2295 9154 int r;
c9b8b07c 9155 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7ae441ea 9156 bool writeback = true;
09e3e2a1 9157
41e6e367
SC
9158 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9159 (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9160 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9161 emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9162
aeb904f6 9163 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
00682995
SC
9164 if (r != X86EMUL_CONTINUE) {
9165 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9166 return 1;
9167
704fc602
IO
9168 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9169 emulation_type))
9170 return 1;
9171
5c9cfc48
IO
9172 if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9173 kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9174 return 0;
9175 }
9176
00682995
SC
9177 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9178 return handle_emulation_failure(vcpu, emulation_type);
9179 }
bbd9b64e 9180
c595ceee
PB
9181 vcpu->arch.l1tf_flush_l1d = true;
9182
571008da 9183 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4aa2691d 9184 kvm_clear_exception_queue(vcpu);
4a1e10d5 9185
fee060cd
SC
9186 /*
9187 * Return immediately if RIP hits a code breakpoint, such #DBs
9188 * are fault-like and are higher priority than any faults on
9189 * the code fetch itself.
9190 */
750f8fcb 9191 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
fee060cd
SC
9192 return r;
9193
4aa2691d
WH
9194 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9195 insn, insn_len);
1d2887e2 9196 if (r != EMULATION_OK) {
b4000606 9197 if ((emulation_type & EMULTYPE_TRAP_UD) ||
c83fad65
SC
9198 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9199 kvm_queue_exception(vcpu, UD_VECTOR);
60fc3d02 9200 return 1;
c83fad65 9201 }
2876624e
SC
9202 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9203 emulation_type))
60fc3d02 9204 return 1;
17122c06
SC
9205
9206 if (ctxt->have_exception &&
9207 !(emulation_type & EMULTYPE_SKIP)) {
c8848cee
JD
9208 /*
9209 * #UD should result in just EMULATION_FAILED, and trap-like
9210 * exception should not be encountered during decode.
9211 */
9212 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9213 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8530a79c 9214 inject_emulated_exception(vcpu);
60fc3d02 9215 return 1;
8530a79c 9216 }
e2366171 9217 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
9218 }
9219 }
9220
42cbf068
SC
9221 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9222 !is_vmware_backdoor_opcode(ctxt)) {
9223 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 9224 return 1;
42cbf068 9225 }
04789b66 9226
1957aa63 9227 /*
906fa904
HW
9228 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9229 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9230 * The caller is responsible for updating interruptibility state and
9231 * injecting single-step #DBs.
1957aa63 9232 */
ba8afb6b 9233 if (emulation_type & EMULTYPE_SKIP) {
5e854864
SC
9234 if (ctxt->mode != X86EMUL_MODE_PROT64)
9235 ctxt->eip = (u32)ctxt->_eip;
9236 else
9237 ctxt->eip = ctxt->_eip;
9238
906fa904
HW
9239 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9240 r = 1;
9241 goto writeback;
9242 }
9243
5e854864 9244 kvm_rip_write(vcpu, ctxt->eip);
bb663c7a
NA
9245 if (ctxt->eflags & X86_EFLAGS_RF)
9246 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
60fc3d02 9247 return 1;
ba8afb6b
GN
9248 }
9249
2df354e3
SC
9250 /*
9251 * If emulation was caused by a write-protection #PF on a non-page_table
9252 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9253 * and retry the instruction, as the vCPU is likely no longer using the
9254 * gfn as a page table.
9255 */
9256 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9257 !x86_page_table_writing_insn(ctxt) &&
9258 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
60fc3d02 9259 return 1;
1cb3f3ae 9260
7ae441ea 9261 /* this is needed for vmware backdoor interface to work since it
4d2179e1 9262 changes registers values during IO operation */
7ae441ea
GN
9263 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9264 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
dd856efa 9265 emulator_invalidate_register_cache(ctxt);
7ae441ea 9266 }
4d2179e1 9267
5cd21917 9268restart:
92daa48b
SC
9269 if (emulation_type & EMULTYPE_PF) {
9270 /* Save the faulting GPA (cr2) in the address field */
9271 ctxt->exception.address = cr2_or_gpa;
9272
9273 /* With shadow page tables, cr2 contains a GVA or nGPA. */
347a0d0d 9274 if (vcpu->arch.mmu->root_role.direct) {
744e699c
SC
9275 ctxt->gpa_available = true;
9276 ctxt->gpa_val = cr2_or_gpa;
92daa48b
SC
9277 }
9278 } else {
9279 /* Sanitize the address out of an abundance of paranoia. */
9280 ctxt->exception.address = 0;
9281 }
0f89b207 9282
9d74191a 9283 r = x86_emulate_insn(ctxt);
bbd9b64e 9284
775fde86 9285 if (r == EMULATION_INTERCEPTED)
60fc3d02 9286 return 1;
775fde86 9287
d2ddd1c4 9288 if (r == EMULATION_FAILED) {
2876624e
SC
9289 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9290 emulation_type))
60fc3d02 9291 return 1;
c3cd7ffa 9292
e2366171 9293 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
9294 }
9295
9d74191a 9296 if (ctxt->have_exception) {
0dc90226
SC
9297 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9298 vcpu->mmio_needed = false;
60fc3d02 9299 r = 1;
7709aba8 9300 inject_emulated_exception(vcpu);
d2ddd1c4 9301 } else if (vcpu->arch.pio.count) {
0912c977
PB
9302 if (!vcpu->arch.pio.in) {
9303 /* FIXME: return into emulator if single-stepping. */
3457e419 9304 vcpu->arch.pio.count = 0;
0912c977 9305 } else {
7ae441ea 9306 writeback = false;
716d51ab
GN
9307 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9308 }
60fc3d02 9309 r = 0;
7ae441ea 9310 } else if (vcpu->mmio_needed) {
bc8a0aaf
SC
9311 ++vcpu->stat.mmio_exits;
9312
7ae441ea
GN
9313 if (!vcpu->mmio_is_write)
9314 writeback = false;
60fc3d02 9315 r = 0;
716d51ab 9316 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
adbfb12d
HW
9317 } else if (vcpu->arch.complete_userspace_io) {
9318 writeback = false;
9319 r = 0;
7ae441ea 9320 } else if (r == EMULATION_RESTART)
5cd21917 9321 goto restart;
d2ddd1c4 9322 else
60fc3d02 9323 r = 1;
f850e2e6 9324
906fa904 9325writeback:
7ae441ea 9326 if (writeback) {
89604647 9327 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9d74191a 9328 toggle_interruptibility(vcpu, ctxt->interruptibility);
7ae441ea 9329 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5623f751
SC
9330
9331 /*
9332 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9333 * only supports code breakpoints and general detect #DB, both
9334 * of which are fault-like.
9335 */
38827dbd 9336 if (!ctxt->have_exception ||
75ee23b3 9337 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
f19063b1 9338 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
018d70ff 9339 if (ctxt->is_branch)
f19063b1 9340 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
75ee23b3 9341 kvm_rip_write(vcpu, ctxt->eip);
384dea1c 9342 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
120c2c4f 9343 r = kvm_vcpu_do_singlestep(vcpu);
89604647 9344 kvm_x86_call(update_emulated_instruction)(vcpu);
38827dbd 9345 __kvm_set_rflags(vcpu, ctxt->eflags);
75ee23b3 9346 }
6addfc42
PB
9347
9348 /*
9349 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9350 * do nothing, and it will be requested again as soon as
9351 * the shadow expires. But we still need to check here,
9352 * because POPF has no interrupt shadow.
9353 */
9354 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9355 kvm_make_request(KVM_REQ_EVENT, vcpu);
7ae441ea
GN
9356 } else
9357 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
e85d28f8
GN
9358
9359 return r;
de7d789a 9360}
c60658d1
SC
9361
9362int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9363{
9364 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9365}
9366EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9367
9368int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9369 void *insn, int insn_len)
9370{
9371 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9372}
9373EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
de7d789a 9374
8764ed55
SC
9375static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9376{
9377 vcpu->arch.pio.count = 0;
9378 return 1;
9379}
9380
45def77e
SC
9381static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9382{
9383 vcpu->arch.pio.count = 0;
9384
e9628b01 9385 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
45def77e
SC
9386 return 1;
9387
9388 return kvm_skip_emulated_instruction(vcpu);
9389}
9390
dca7f128
SC
9391static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9392 unsigned short port)
de7d789a 9393{
de3cd117 9394 unsigned long val = kvm_rax_read(vcpu);
2e3bb4d8
SC
9395 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9396
8764ed55
SC
9397 if (ret)
9398 return ret;
45def77e 9399
8764ed55
SC
9400 /*
9401 * Workaround userspace that relies on old KVM behavior of %rip being
9402 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9403 */
9404 if (port == 0x7e &&
9405 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9406 vcpu->arch.complete_userspace_io =
9407 complete_fast_pio_out_port_0x7e;
9408 kvm_skip_emulated_instruction(vcpu);
9409 } else {
e9628b01 9410 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
45def77e
SC
9411 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9412 }
8764ed55 9413 return 0;
de7d789a 9414}
de7d789a 9415
8370c3d0
TL
9416static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9417{
9418 unsigned long val;
9419
9420 /* We should only ever be called with arch.pio.count equal to 1 */
9421 BUG_ON(vcpu->arch.pio.count != 1);
9422
e9628b01 9423 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
45def77e
SC
9424 vcpu->arch.pio.count = 0;
9425 return 1;
9426 }
9427
8370c3d0 9428 /* For size less than 4 we merge, else we zero extend */
de3cd117 9429 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0 9430
7a6177d6 9431 complete_emulator_pio_in(vcpu, &val);
de3cd117 9432 kvm_rax_write(vcpu, val);
8370c3d0 9433
45def77e 9434 return kvm_skip_emulated_instruction(vcpu);
8370c3d0
TL
9435}
9436
dca7f128
SC
9437static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9438 unsigned short port)
8370c3d0
TL
9439{
9440 unsigned long val;
9441 int ret;
9442
9443 /* For size less than 4 we merge, else we zero extend */
de3cd117 9444 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0 9445
2e3bb4d8 9446 ret = emulator_pio_in(vcpu, size, port, &val, 1);
8370c3d0 9447 if (ret) {
de3cd117 9448 kvm_rax_write(vcpu, val);
8370c3d0
TL
9449 return ret;
9450 }
9451
e9628b01 9452 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
8370c3d0
TL
9453 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9454
9455 return 0;
9456}
dca7f128
SC
9457
9458int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9459{
45def77e 9460 int ret;
dca7f128 9461
dca7f128 9462 if (in)
45def77e 9463 ret = kvm_fast_pio_in(vcpu, size, port);
dca7f128 9464 else
45def77e
SC
9465 ret = kvm_fast_pio_out(vcpu, size, port);
9466 return ret && kvm_skip_emulated_instruction(vcpu);
dca7f128
SC
9467}
9468EXPORT_SYMBOL_GPL(kvm_fast_pio);
8370c3d0 9469
251a5fd6 9470static int kvmclock_cpu_down_prep(unsigned int cpu)
8cfdc000 9471{
0a3aee0d 9472 __this_cpu_write(cpu_tsc_khz, 0);
251a5fd6 9473 return 0;
8cfdc000
ZA
9474}
9475
9476static void tsc_khz_changed(void *data)
c8076604 9477{
8cfdc000 9478 struct cpufreq_freqs *freq = data;
392a5324 9479 unsigned long khz;
8cfdc000 9480
3ebcbd22
AR
9481 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9482
8cfdc000
ZA
9483 if (data)
9484 khz = freq->new;
3ebcbd22 9485 else
8cfdc000
ZA
9486 khz = cpufreq_quick_get(raw_smp_processor_id());
9487 if (!khz)
9488 khz = tsc_khz;
0a3aee0d 9489 __this_cpu_write(cpu_tsc_khz, khz);
c8076604
GH
9490}
9491
5fa4ec9c 9492#ifdef CONFIG_X86_64
0092e434
VK
9493static void kvm_hyperv_tsc_notifier(void)
9494{
0092e434 9495 struct kvm *kvm;
0092e434
VK
9496 int cpu;
9497
0d9ce162 9498 mutex_lock(&kvm_lock);
0092e434
VK
9499 list_for_each_entry(kvm, &vm_list, vm_list)
9500 kvm_make_mclock_inprogress_request(kvm);
9501
6b6fcd28 9502 /* no guest entries from this point */
0092e434
VK
9503 hyperv_stop_tsc_emulation();
9504
9505 /* TSC frequency always matches when on Hyper-V */
3ebcbd22
AR
9506 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9507 for_each_present_cpu(cpu)
9508 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9509 }
938c8745 9510 kvm_caps.max_guest_tsc_khz = tsc_khz;
0092e434
VK
9511
9512 list_for_each_entry(kvm, &vm_list, vm_list) {
869b4421 9513 __kvm_start_pvclock_update(kvm);
0092e434 9514 pvclock_update_vm_gtod_copy(kvm);
6b6fcd28 9515 kvm_end_pvclock_update(kvm);
0092e434 9516 }
6b6fcd28 9517
0d9ce162 9518 mutex_unlock(&kvm_lock);
0092e434 9519}
5fa4ec9c 9520#endif
0092e434 9521
df24014a 9522static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
c8076604 9523{
c8076604
GH
9524 struct kvm *kvm;
9525 struct kvm_vcpu *vcpu;
46808a4c
MZ
9526 int send_ipi = 0;
9527 unsigned long i;
c8076604 9528
8cfdc000
ZA
9529 /*
9530 * We allow guests to temporarily run on slowing clocks,
9531 * provided we notify them after, or to run on accelerating
9532 * clocks, provided we notify them before. Thus time never
9533 * goes backwards.
9534 *
9535 * However, we have a problem. We can't atomically update
9536 * the frequency of a given CPU from this function; it is
9537 * merely a notifier, which can be called from any CPU.
9538 * Changing the TSC frequency at arbitrary points in time
9539 * requires a recomputation of local variables related to
9540 * the TSC for each VCPU. We must flag these local variables
9541 * to be updated and be sure the update takes place with the
9542 * new frequency before any guests proceed.
9543 *
9544 * Unfortunately, the combination of hotplug CPU and frequency
9545 * change creates an intractable locking scenario; the order
9546 * of when these callouts happen is undefined with respect to
9547 * CPU hotplug, and they can race with each other. As such,
9548 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9549 * undefined; you can actually have a CPU frequency change take
9550 * place in between the computation of X and the setting of the
9551 * variable. To protect against this problem, all updates of
9552 * the per_cpu tsc_khz variable are done in an interrupt
9553 * protected IPI, and all callers wishing to update the value
9554 * must wait for a synchronous IPI to complete (which is trivial
9555 * if the caller is on the CPU already). This establishes the
9556 * necessary total order on variable updates.
9557 *
9558 * Note that because a guest time update may take place
9559 * anytime after the setting of the VCPU's request bit, the
9560 * correct TSC value must be set before the request. However,
9561 * to ensure the update actually makes it to any guest which
9562 * starts running in hardware virtualization between the set
9563 * and the acquisition of the spinlock, we must also ping the
9564 * CPU after setting the request bit.
9565 *
9566 */
9567
df24014a 9568 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 9569
0d9ce162 9570 mutex_lock(&kvm_lock);
c8076604 9571 list_for_each_entry(kvm, &vm_list, vm_list) {
988a2cae 9572 kvm_for_each_vcpu(i, vcpu, kvm) {
df24014a 9573 if (vcpu->cpu != cpu)
c8076604 9574 continue;
c285545f 9575 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0d9ce162 9576 if (vcpu->cpu != raw_smp_processor_id())
8cfdc000 9577 send_ipi = 1;
c8076604
GH
9578 }
9579 }
0d9ce162 9580 mutex_unlock(&kvm_lock);
c8076604
GH
9581
9582 if (freq->old < freq->new && send_ipi) {
9583 /*
9584 * We upscale the frequency. Must make the guest
9585 * doesn't see old kvmclock values while running with
9586 * the new frequency, otherwise we risk the guest sees
9587 * time go backwards.
9588 *
9589 * In case we update the frequency for another cpu
9590 * (which might be in guest context) send an interrupt
9591 * to kick the cpu out of guest context. Next time
9592 * guest context is entered kvmclock will be updated,
9593 * so the guest will not see stale values.
9594 */
df24014a 9595 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 9596 }
df24014a
VK
9597}
9598
9599static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9600 void *data)
9601{
9602 struct cpufreq_freqs *freq = data;
9603 int cpu;
9604
9605 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9606 return 0;
9607 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9608 return 0;
9609
9610 for_each_cpu(cpu, freq->policy->cpus)
9611 __kvmclock_cpufreq_notifier(freq, cpu);
9612
c8076604
GH
9613 return 0;
9614}
9615
9616static struct notifier_block kvmclock_cpufreq_notifier_block = {
8cfdc000
ZA
9617 .notifier_call = kvmclock_cpufreq_notifier
9618};
9619
251a5fd6 9620static int kvmclock_cpu_online(unsigned int cpu)
8cfdc000 9621{
251a5fd6
SAS
9622 tsc_khz_changed(NULL);
9623 return 0;
8cfdc000
ZA
9624}
9625
b820cc0c
ZA
9626static void kvm_timer_init(void)
9627{
b820cc0c 9628 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
741e511b
SC
9629 max_tsc_khz = tsc_khz;
9630
9631 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9632 struct cpufreq_policy *policy;
9633 int cpu;
9634
9635 cpu = get_cpu();
9636 policy = cpufreq_cpu_get(cpu);
9637 if (policy) {
9638 if (policy->cpuinfo.max_freq)
9639 max_tsc_khz = policy->cpuinfo.max_freq;
9640 cpufreq_cpu_put(policy);
9641 }
9642 put_cpu();
9a11997e 9643 }
b820cc0c
ZA
9644 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9645 CPUFREQ_TRANSITION_NOTIFIER);
460dd42e 9646
3ebcbd22
AR
9647 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9648 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9649 }
b820cc0c
ZA
9650}
9651
16e8d74d
MT
9652#ifdef CONFIG_X86_64
9653static void pvclock_gtod_update_fn(struct work_struct *work)
9654{
d828199e 9655 struct kvm *kvm;
d828199e 9656 struct kvm_vcpu *vcpu;
46808a4c 9657 unsigned long i;
d828199e 9658
0d9ce162 9659 mutex_lock(&kvm_lock);
d828199e
MT
9660 list_for_each_entry(kvm, &vm_list, vm_list)
9661 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 9662 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
d828199e 9663 atomic_set(&kvm_guest_has_master_clock, 0);
0d9ce162 9664 mutex_unlock(&kvm_lock);
16e8d74d
MT
9665}
9666
9667static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9668
3f804f6d
TG
9669/*
9670 * Indirection to move queue_work() out of the tk_core.seq write held
9671 * region to prevent possible deadlocks against time accessors which
9672 * are invoked with work related locks held.
9673 */
9674static void pvclock_irq_work_fn(struct irq_work *w)
9675{
9676 queue_work(system_long_wq, &pvclock_gtod_work);
9677}
9678
9679static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9680
16e8d74d
MT
9681/*
9682 * Notification about pvclock gtod data update.
9683 */
9684static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9685 void *priv)
9686{
9687 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9688 struct timekeeper *tk = priv;
9689
9690 update_pvclock_gtod(tk);
9691
3f804f6d
TG
9692 /*
9693 * Disable master clock if host does not trust, or does not use,
9694 * TSC based clocksource. Delegate queue_work() to irq_work as
9695 * this is invoked with tk_core.seq write held.
16e8d74d 9696 */
b0c39dc6 9697 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
16e8d74d 9698 atomic_read(&kvm_guest_has_master_clock) != 0)
3f804f6d 9699 irq_work_queue(&pvclock_irq_work);
16e8d74d
MT
9700 return 0;
9701}
9702
9703static struct notifier_block pvclock_gtod_notifier = {
9704 .notifier_call = pvclock_gtod_notify,
9705};
9706#endif
9707
b7483387
SC
9708static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9709{
9710 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9711
9712#define __KVM_X86_OP(func) \
9713 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9714#define KVM_X86_OP(func) \
9715 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9716#define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9717#define KVM_X86_OP_OPTIONAL_RET0(func) \
9718 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9719 (void *)__static_call_return0);
9720#include <asm/kvm-x86-ops.h>
9721#undef __KVM_X86_OP
9722
9723 kvm_pmu_ops_update(ops->pmu_ops);
9724}
9725
d83420c2 9726static int kvm_x86_check_processor_compatibility(void)
3045c483 9727{
e4aa7f88
CG
9728 int cpu = smp_processor_id();
9729 struct cpuinfo_x86 *c = &cpu_data(cpu);
9730
9731 /*
9732 * Compatibility checks are done when loading KVM and when enabling
9733 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9734 * compatible, i.e. KVM should never perform a compatibility check on
9735 * an offline CPU.
9736 */
9737 WARN_ON(!cpu_online(cpu));
3045c483 9738
3045c483
SC
9739 if (__cr4_reserved_bits(cpu_has, c) !=
9740 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9741 return -EIO;
9742
89604647 9743 return kvm_x86_call(check_processor_compatibility)();
3045c483
SC
9744}
9745
d83420c2 9746static void kvm_x86_check_cpu_compat(void *ret)
3045c483 9747{
d83420c2 9748 *(int *)ret = kvm_x86_check_processor_compatibility();
3045c483
SC
9749}
9750
955997e8 9751int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
043405e1 9752{
94bda2f4 9753 u64 host_pat;
3045c483 9754 int r, cpu;
f8c16bba 9755
955997e8
NB
9756 guard(mutex)(&vendor_module_lock);
9757
0617a769 9758 if (kvm_x86_ops.enable_virtualization_cpu) {
8d20bd63 9759 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
82ffad2d 9760 return -EEXIST;
f8c16bba
ZX
9761 }
9762
b666a4b6
MO
9763 /*
9764 * KVM explicitly assumes that the guest has an FPU and
9765 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9766 * vCPU's FPU state as a fxregs_state struct.
9767 */
9768 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
8d20bd63 9769 pr_err("inadequate fpu\n");
82ffad2d 9770 return -EOPNOTSUPP;
b666a4b6
MO
9771 }
9772
5e17b2ee
TG
9773 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9774 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
82ffad2d 9775 return -EOPNOTSUPP;
b666a4b6
MO
9776 }
9777
94bda2f4
SC
9778 /*
9779 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9780 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
9781 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
9782 * with an exception. PAT[0] is set to WB on RESET and also by the
9783 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9784 */
6fe22aba 9785 if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
94bda2f4 9786 (host_pat & GENMASK(2, 0)) != 6) {
8d20bd63 9787 pr_err("host PAT[0] is not WB\n");
82ffad2d 9788 return -EIO;
94bda2f4 9789 }
b666a4b6 9790
40269c03
SC
9791 memset(&kvm_caps, 0, sizeof(kvm_caps));
9792
c9b8b07c
SC
9793 x86_emulator_cache = kvm_alloc_emulator_cache();
9794 if (!x86_emulator_cache) {
8d20bd63 9795 pr_err("failed to allocate cache for x86 emulator\n");
82ffad2d 9796 return -ENOMEM;
c9b8b07c
SC
9797 }
9798
7e34fbd0
SC
9799 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9800 if (!user_return_msrs) {
8d20bd63 9801 pr_err("failed to allocate percpu kvm_user_return_msrs\n");
82ffad2d 9802 r = -ENOMEM;
c9b8b07c 9803 goto out_free_x86_emulator_cache;
013f6a5d 9804 }
e5fda4bb 9805 kvm_nr_uret_msrs = 0;
013f6a5d 9806
1d0e8480 9807 r = kvm_mmu_vendor_module_init();
97db56ce 9808 if (r)
013f6a5d 9809 goto out_free_percpu;
97db56ce 9810
c43ad190 9811 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
555485bd 9812 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
c43ad190 9813
cfc48181 9814 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7974c064
SC
9815 kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9816 kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
cfc48181 9817 }
bd7d5362 9818 kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
a4dae7c7 9819 kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
2acf923e 9820
6fe22aba 9821 rdmsrq_safe(MSR_EFER, &kvm_host.efer);
b7483387
SC
9822
9823 if (boot_cpu_has(X86_FEATURE_XSAVES))
c435e608 9824 rdmsrq(MSR_IA32_XSS, kvm_host.xss);
b7483387 9825
8911ce66 9826 kvm_init_pmu_capability(ops->pmu_ops);
b7483387 9827
a2fd5d02 9828 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
c435e608 9829 rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
a2fd5d02 9830
b7483387
SC
9831 r = ops->hardware_setup();
9832 if (r != 0)
9833 goto out_mmu_exit;
9834
459074cf
SC
9835 enable_device_posted_irqs &= enable_apicv &&
9836 irq_remapping_cap(IRQ_POSTING_CAP);
9837
d83420c2
SC
9838 kvm_ops_update(ops);
9839
3045c483 9840 for_each_online_cpu(cpu) {
d83420c2 9841 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
3045c483 9842 if (r < 0)
d83420c2 9843 goto out_unwind_ops;
3045c483
SC
9844 }
9845
b7483387
SC
9846 /*
9847 * Point of no return! DO NOT add error paths below this point unless
9848 * absolutely necessary, as most operations from this point forward
9849 * require unwinding.
9850 */
1935542a
SC
9851 kvm_timer_init();
9852
0c5f81da 9853 if (pi_inject_timer == -1)
04d4e665 9854 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
16e8d74d
MT
9855#ifdef CONFIG_X86_64
9856 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
0092e434 9857
5fa4ec9c 9858 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434 9859 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
16e8d74d
MT
9860#endif
9861
b7483387
SC
9862 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9863
2a955c4d
PB
9864 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9865 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9866
c9c1e20b
YZ
9867 /* KVM always ignores guest PAT for shadow paging. */
9868 if (!tdp_enabled)
9869 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
9870
b7483387
SC
9871 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9872 kvm_caps.supported_xss = 0;
9873
b7483387
SC
9874 if (kvm_caps.has_tsc_control) {
9875 /*
9876 * Make sure the user can only configure tsc_khz values that
9877 * fit into a signed integer.
9878 * A min value is not calculated because it will always
9879 * be 1 on all machines.
9880 */
9881 u64 max = min(0x7fffffffULL,
9882 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9883 kvm_caps.max_guest_tsc_khz = max;
9884 }
9885 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
b1932c5c 9886 kvm_init_msr_lists();
f8c16bba 9887 return 0;
56c6d28a 9888
d83420c2 9889out_unwind_ops:
0617a769 9890 kvm_x86_ops.enable_virtualization_cpu = NULL;
89604647 9891 kvm_x86_call(hardware_unsetup)();
b7483387
SC
9892out_mmu_exit:
9893 kvm_mmu_vendor_module_exit();
013f6a5d 9894out_free_percpu:
7e34fbd0 9895 free_percpu(user_return_msrs);
c9b8b07c
SC
9896out_free_x86_emulator_cache:
9897 kmem_cache_destroy(x86_emulator_cache);
56c6d28a 9898 return r;
043405e1 9899}
4f8396b9 9900EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
8776e519 9901
4f8396b9 9902void kvm_x86_vendor_exit(void)
f8c16bba 9903{
b7483387
SC
9904 kvm_unregister_perf_callbacks();
9905
0092e434 9906#ifdef CONFIG_X86_64
5fa4ec9c 9907 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434
VK
9908 clear_hv_tscchange_cb();
9909#endif
cef84c30 9910 kvm_lapic_exit();
647daca2 9911
3ebcbd22 9912 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
888d256e
JK
9913 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9914 CPUFREQ_TRANSITION_NOTIFIER);
3ebcbd22
AR
9915 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9916 }
16e8d74d
MT
9917#ifdef CONFIG_X86_64
9918 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
3f804f6d 9919 irq_work_sync(&pvclock_irq_work);
594b27e6 9920 cancel_work_sync(&pvclock_gtod_work);
16e8d74d 9921#endif
89604647 9922 kvm_x86_call(hardware_unsetup)();
1d0e8480 9923 kvm_mmu_vendor_module_exit();
7e34fbd0 9924 free_percpu(user_return_msrs);
dfdc0a71 9925 kmem_cache_destroy(x86_emulator_cache);
b59b153d 9926#ifdef CONFIG_KVM_XEN
c462f859 9927 static_key_deferred_flush(&kvm_xen_enabled);
7d6bbebb 9928 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
b59b153d 9929#endif
3af4a9e6 9930 mutex_lock(&vendor_module_lock);
41786cc5 9931 kvm_x86_ops.enable_virtualization_cpu = NULL;
3af4a9e6 9932 mutex_unlock(&vendor_module_lock);
647daca2 9933}
4f8396b9 9934EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
647daca2 9935
8ef81a9a 9936#ifdef CONFIG_X86_64
55dd00a7
MT
9937static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9938 unsigned long clock_type)
9939{
9940 struct kvm_clock_pairing clock_pairing;
899a31f5 9941 struct timespec64 ts;
80fbd89c 9942 u64 cycle;
55dd00a7
MT
9943 int ret;
9944
9945 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9946 return -KVM_EOPNOTSUPP;
9947
3a55f729
AR
9948 /*
9949 * When tsc is in permanent catchup mode guests won't be able to use
9950 * pvclock_read_retry loop to get consistent view of pvclock
9951 */
9952 if (vcpu->arch.tsc_always_catchup)
9953 return -KVM_EOPNOTSUPP;
9954
7ca7f3b9 9955 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
55dd00a7
MT
9956 return -KVM_EOPNOTSUPP;
9957
9958 clock_pairing.sec = ts.tv_sec;
9959 clock_pairing.nsec = ts.tv_nsec;
9960 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9961 clock_pairing.flags = 0;
bcbfbd8e 9962 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
55dd00a7
MT
9963
9964 ret = 0;
9965 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9966 sizeof(struct kvm_clock_pairing)))
9967 ret = -KVM_EFAULT;
9968
9969 return ret;
9970}
8ef81a9a 9971#endif
55dd00a7 9972
6aef266c
SV
9973/*
9974 * kvm_pv_kick_cpu_op: Kick a vcpu.
9975 *
9976 * @apicid - apicid of vcpu to be kicked.
9977 */
9d68c6f6 9978static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
6aef266c 9979{
8a414f94
VK
9980 /*
9981 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9982 * common code, e.g. for tracing. Defer initialization to the compiler.
9983 */
9984 struct kvm_lapic_irq lapic_irq = {
9985 .delivery_mode = APIC_DM_REMRD,
9986 .dest_mode = APIC_DEST_PHYSICAL,
9987 .shorthand = APIC_DEST_NOSHORT,
9988 .dest_id = apicid,
9989 };
6aef266c 9990
795a149e 9991 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6aef266c
SV
9992}
9993
4e19c36f
SS
9994bool kvm_apicv_activated(struct kvm *kvm)
9995{
9996 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9997}
9998EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9999
d5fa597e
ML
10000bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10001{
10002 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
89604647
WW
10003 ulong vcpu_reasons =
10004 kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
d5fa597e
ML
10005
10006 return (vm_reasons | vcpu_reasons) == 0;
10007}
10008EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
4f4c4a3e
SC
10009
10010static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10011 enum kvm_apicv_inhibit reason, bool set)
10012{
69148cce
AJ
10013 const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10014
10015 BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10016
4f4c4a3e
SC
10017 if (set)
10018 __set_bit(reason, inhibits);
10019 else
10020 __clear_bit(reason, inhibits);
10021
10022 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10023}
10024
4651fc56 10025static void kvm_apicv_init(struct kvm *kvm)
4e19c36f 10026{
6982b34c 10027 enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
f9925721 10028 APICV_INHIBIT_REASON_DISABLED;
4f4c4a3e 10029
6982b34c 10030 set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
4f4c4a3e 10031
6982b34c 10032 init_rwsem(&kvm->arch.apicv_update_lock);
4e19c36f 10033}
4e19c36f 10034
4a7132ef 10035static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
71506297
WL
10036{
10037 struct kvm_vcpu *target = NULL;
10038 struct kvm_apic_map *map;
10039
4a7132ef
WL
10040 vcpu->stat.directed_yield_attempted++;
10041
72b268a8
WL
10042 if (single_task_running())
10043 goto no_yield;
10044
71506297 10045 rcu_read_lock();
4a7132ef 10046 map = rcu_dereference(vcpu->kvm->arch.apic_map);
71506297
WL
10047
10048 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
10049 target = map->phys_map[dest_id]->vcpu;
10050
10051 rcu_read_unlock();
10052
4a7132ef
WL
10053 if (!target || !READ_ONCE(target->ready))
10054 goto no_yield;
10055
a1fa4cbd
WL
10056 /* Ignore requests to yield to self */
10057 if (vcpu == target)
10058 goto no_yield;
10059
4a7132ef
WL
10060 if (kvm_vcpu_yield_to(target) <= 0)
10061 goto no_yield;
10062
10063 vcpu->stat.directed_yield_successful++;
10064
10065no_yield:
10066 return;
71506297
WL
10067}
10068
0dbb1123
AK
10069static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10070{
10071 u64 ret = vcpu->run->hypercall.ret;
10072
9b42d1e8 10073 if (!is_64_bit_hypercall(vcpu))
0dbb1123
AK
10074 ret = (u32)ret;
10075 kvm_rax_write(vcpu, ret);
0dbb1123
AK
10076 return kvm_skip_emulated_instruction(vcpu);
10077}
10078
6162b373 10079int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
c50be1c9 10080 int (*complete_hypercall)(struct kvm_vcpu *))
8776e519 10081{
e913ef15 10082 unsigned long ret;
6162b373
BW
10083 unsigned long nr = kvm_rax_read(vcpu);
10084 unsigned long a0 = kvm_rbx_read(vcpu);
10085 unsigned long a1 = kvm_rcx_read(vcpu);
10086 unsigned long a2 = kvm_rdx_read(vcpu);
10087 unsigned long a3 = kvm_rsi_read(vcpu);
10088 int op_64_bit = is_64_bit_hypercall(vcpu);
8776e519 10089
05a518b4
SC
10090 ++vcpu->stat.hypercalls;
10091
229456fc 10092 trace_kvm_hypercall(nr, a0, a1, a2, a3);
2714d1d3 10093
a449c7aa 10094 if (!op_64_bit) {
8776e519
HB
10095 nr &= 0xFFFFFFFF;
10096 a0 &= 0xFFFFFFFF;
10097 a1 &= 0xFFFFFFFF;
10098 a2 &= 0xFFFFFFFF;
10099 a3 &= 0xFFFFFFFF;
10100 }
10101
e913ef15 10102 if (cpl) {
07708c4a 10103 ret = -KVM_EPERM;
696ca779 10104 goto out;
07708c4a
JK
10105 }
10106
66570e96
OU
10107 ret = -KVM_ENOSYS;
10108
8776e519 10109 switch (nr) {
b93463aa
AK
10110 case KVM_HC_VAPIC_POLL_IRQ:
10111 ret = 0;
10112 break;
6aef266c 10113 case KVM_HC_KICK_CPU:
66570e96
OU
10114 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10115 break;
10116
9d68c6f6 10117 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
4a7132ef 10118 kvm_sched_yield(vcpu, a1);
6aef266c
SV
10119 ret = 0;
10120 break;
8ef81a9a 10121#ifdef CONFIG_X86_64
55dd00a7
MT
10122 case KVM_HC_CLOCK_PAIRING:
10123 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10124 break;
1ed199a4 10125#endif
4180bf1b 10126 case KVM_HC_SEND_IPI:
66570e96
OU
10127 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10128 break;
10129
4180bf1b
WL
10130 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10131 break;
71506297 10132 case KVM_HC_SCHED_YIELD:
66570e96
OU
10133 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10134 break;
10135
4a7132ef 10136 kvm_sched_yield(vcpu, a0);
71506297
WL
10137 ret = 0;
10138 break;
0dbb1123
AK
10139 case KVM_HC_MAP_GPA_RANGE: {
10140 u64 gpa = a0, npages = a1, attrs = a2;
10141
10142 ret = -KVM_ENOSYS;
c4c083d9 10143 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
0dbb1123
AK
10144 break;
10145
10146 if (!PAGE_ALIGNED(gpa) || !npages ||
10147 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10148 ret = -KVM_EINVAL;
10149 break;
10150 }
10151
10152 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10153 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
9a1dfeff
PB
10154 /*
10155 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10156 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10157 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
10158 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10159 */
10160 vcpu->run->hypercall.ret = 0;
0dbb1123
AK
10161 vcpu->run->hypercall.args[0] = gpa;
10162 vcpu->run->hypercall.args[1] = npages;
10163 vcpu->run->hypercall.args[2] = attrs;
e65733b5
OU
10164 vcpu->run->hypercall.flags = 0;
10165 if (op_64_bit)
10166 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10167
10168 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
d9eb86a6 10169 vcpu->arch.complete_userspace_io = complete_hypercall;
0dbb1123
AK
10170 return 0;
10171 }
8776e519
HB
10172 default:
10173 ret = -KVM_ENOSYS;
10174 break;
10175 }
e913ef15 10176
696ca779 10177out:
d9eb86a6 10178 vcpu->run->hypercall.ret = ret;
c50be1c9 10179 return 1;
e913ef15 10180}
c50be1c9 10181EXPORT_SYMBOL_GPL(____kvm_emulate_hypercall);
e913ef15
SC
10182
10183int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10184{
e913ef15
SC
10185 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10186 return kvm_xen_hypercall(vcpu);
10187
10188 if (kvm_hv_hypercall_enabled(vcpu))
10189 return kvm_hv_hypercall(vcpu);
10190
6162b373 10191 return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
d9eb86a6 10192 complete_hypercall_exit);
8776e519
HB
10193}
10194EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10195
b6785def 10196static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8776e519 10197{
d6aa1000 10198 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8776e519 10199 char instruction[3];
5fdbf976 10200 unsigned long rip = kvm_rip_read(vcpu);
8776e519 10201
f1a9761f
OU
10202 /*
10203 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10204 * the pieces.
10205 */
10206 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10207 ctxt->exception.error_code_valid = false;
10208 ctxt->exception.vector = UD_VECTOR;
10209 ctxt->have_exception = true;
10210 return X86EMUL_PROPAGATE_FAULT;
10211 }
10212
89604647 10213 kvm_x86_call(patch_hypercall)(vcpu, instruction);
8776e519 10214
ce2e852e
DV
10215 return emulator_write_emulated(ctxt, rip, instruction, 3,
10216 &ctxt->exception);
8776e519
HB
10217}
10218
851ba692 10219static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
b6c7a5dc 10220{
782d422b
MG
10221 return vcpu->run->request_interrupt_window &&
10222 likely(!pic_in_kernel(vcpu->kvm));
b6c7a5dc
HB
10223}
10224
8d25b7be 10225/* Called within kvm->srcu read side. */
851ba692 10226static void post_kvm_run_save(struct kvm_vcpu *vcpu)
b6c7a5dc 10227{
851ba692
AK
10228 struct kvm_run *kvm_run = vcpu->run;
10229
89604647 10230 kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
2d3ad1f4 10231 kvm_run->cr8 = kvm_get_cr8(vcpu);
d91060e3 10232 kvm_run->apic_base = vcpu->arch.apic_base;
f3d1436d 10233
127a457a
MG
10234 kvm_run->ready_for_interrupt_injection =
10235 pic_in_kernel(vcpu->kvm) ||
782d422b 10236 kvm_vcpu_ready_for_interrupt_injection(vcpu);
15aad3be
CQ
10237
10238 if (is_smm(vcpu))
10239 kvm_run->flags |= KVM_RUN_X86_SMM;
85542adb
TP
10240 if (is_guest_mode(vcpu))
10241 kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
b6c7a5dc
HB
10242}
10243
95ba8273
GN
10244static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10245{
10246 int max_irr, tpr;
10247
afaf0b2f 10248 if (!kvm_x86_ops.update_cr8_intercept)
95ba8273
GN
10249 return;
10250
bce87cce 10251 if (!lapic_in_kernel(vcpu))
88c808fd
AK
10252 return;
10253
ce0a58f4 10254 if (vcpu->arch.apic->apicv_active)
d62caabb
AS
10255 return;
10256
8db3baa2
GN
10257 if (!vcpu->arch.apic->vapic_addr)
10258 max_irr = kvm_lapic_find_highest_irr(vcpu);
10259 else
10260 max_irr = -1;
95ba8273
GN
10261
10262 if (max_irr != -1)
10263 max_irr >>= 4;
10264
10265 tpr = kvm_lapic_get_cr8(vcpu);
10266
89604647 10267 kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
95ba8273
GN
10268}
10269
b97f0745 10270
cb6a32c2
SC
10271int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10272{
92e7d5c8 10273 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
cb6a32c2
SC
10274 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10275 return 1;
10276 }
10277
10278 return kvm_x86_ops.nested_ops->check_events(vcpu);
10279}
10280
b97f0745
ML
10281static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10282{
6c41468c
SC
10283 /*
10284 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10285 * exceptions don't report error codes. The presence of an error code
10286 * is carried with the exception and only stripped when the exception
10287 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10288 * report an error code despite the CPU being in Real Mode.
10289 */
10290 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10291
d4963e31 10292 trace_kvm_inj_exception(vcpu->arch.exception.vector,
a61d7c54
SC
10293 vcpu->arch.exception.has_error_code,
10294 vcpu->arch.exception.error_code,
10295 vcpu->arch.exception.injected);
10296
89604647 10297 kvm_x86_call(inject_exception)(vcpu);
b97f0745
ML
10298}
10299
e746c1f1
SC
10300/*
10301 * Check for any event (interrupt or exception) that is ready to be injected,
10302 * and if there is at least one event, inject the event with the highest
10303 * priority. This handles both "pending" events, i.e. events that have never
10304 * been injected into the guest, and "injected" events, i.e. events that were
10305 * injected as part of a previous VM-Enter, but weren't successfully delivered
10306 * and need to be re-injected.
10307 *
10308 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10309 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10310 * be able to inject exceptions in the "middle" of an instruction, and so must
10311 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10312 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10313 * boundaries is necessary and correct.
10314 *
10315 * For simplicity, KVM uses a single path to inject all events (except events
10316 * that are injected directly from L1 to L2) and doesn't explicitly track
10317 * instruction boundaries for asynchronous events. However, because VM-Exits
10318 * that can occur during instruction execution typically result in KVM skipping
10319 * the instruction or injecting an exception, e.g. instruction and exception
10320 * intercepts, and because pending exceptions have higher priority than pending
10321 * interrupts, KVM still honors instruction boundaries in most scenarios.
10322 *
10323 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10324 * the instruction or inject an exception, then KVM can incorrecty inject a new
54aa699e 10325 * asynchronous event if the event became pending after the CPU fetched the
e746c1f1
SC
10326 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10327 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10328 * injected on the restarted instruction instead of being deferred until the
10329 * instruction completes.
10330 *
10331 * In practice, this virtualization hole is unlikely to be observed by the
10332 * guest, and even less likely to cause functional problems. To detect the
10333 * hole, the guest would have to trigger an event on a side effect of an early
10334 * phase of instruction execution, e.g. on the instruction fetch from memory.
10335 * And for it to be a functional problem, the guest would need to depend on the
10336 * ordering between that side effect, the instruction completing, _and_ the
10337 * delivery of the asynchronous event.
10338 */
10339static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10340 bool *req_immediate_exit)
95ba8273 10341{
28360f88 10342 bool can_inject;
b6b8a145
JK
10343 int r;
10344
6c593b52 10345 /*
54aa699e 10346 * Process nested events first, as nested VM-Exit supersedes event
6c593b52
SC
10347 * re-injection. If there's an event queued for re-injection, it will
10348 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10349 */
10350 if (is_guest_mode(vcpu))
10351 r = kvm_check_nested_events(vcpu);
10352 else
10353 r = 0;
664f8e26
WL
10354
10355 /*
6c593b52
SC
10356 * Re-inject exceptions and events *especially* if immediate entry+exit
10357 * to/from L2 is needed, as any event that has already been injected
10358 * into L2 needs to complete its lifecycle before injecting a new event.
10359 *
10360 * Don't re-inject an NMI or interrupt if there is a pending exception.
10361 * This collision arises if an exception occurred while vectoring the
10362 * injected event, KVM intercepted said exception, and KVM ultimately
10363 * determined the fault belongs to the guest and queues the exception
10364 * for injection back into the guest.
10365 *
10366 * "Injected" interrupts can also collide with pending exceptions if
10367 * userspace ignores the "ready for injection" flag and blindly queues
10368 * an interrupt. In that case, prioritizing the exception is correct,
10369 * as the exception "occurred" before the exit to userspace. Trap-like
10370 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10371 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10372 * priority, they're only generated (pended) during instruction
10373 * execution, and interrupts are recognized at instruction boundaries.
10374 * Thus a pending fault-like exception means the fault occurred on the
10375 * *previous* instruction and must be serviced prior to recognizing any
10376 * new events in order to fully complete the previous instruction.
664f8e26 10377 */
6c593b52
SC
10378 if (vcpu->arch.exception.injected)
10379 kvm_inject_exception(vcpu);
7709aba8 10380 else if (kvm_is_exception_pending(vcpu))
6c593b52
SC
10381 ; /* see above */
10382 else if (vcpu->arch.nmi_injected)
89604647 10383 kvm_x86_call(inject_nmi)(vcpu);
6c593b52 10384 else if (vcpu->arch.interrupt.injected)
89604647 10385 kvm_x86_call(inject_irq)(vcpu, true);
664f8e26 10386
6c593b52
SC
10387 /*
10388 * Exceptions that morph to VM-Exits are handled above, and pending
10389 * exceptions on top of injected exceptions that do not VM-Exit should
10390 * either morph to #DF or, sadly, override the injected exception.
10391 */
3b82b8d7
SC
10392 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10393 vcpu->arch.exception.pending);
10394
1a680e35 10395 /*
6c593b52
SC
10396 * Bail if immediate entry+exit to/from the guest is needed to complete
10397 * nested VM-Enter or event re-injection so that a different pending
10398 * event can be serviced (or if KVM needs to exit to userspace).
10399 *
10400 * Otherwise, continue processing events even if VM-Exit occurred. The
10401 * VM-Exit will have cleared exceptions that were meant for L2, but
10402 * there may now be events that can be injected into L1.
1a680e35 10403 */
6c593b52
SC
10404 if (r < 0)
10405 goto out;
664f8e26 10406
7709aba8
SC
10407 /*
10408 * A pending exception VM-Exit should either result in nested VM-Exit
10409 * or force an immediate re-entry and exit to/from L2, and exception
10410 * VM-Exits cannot be injected (flag should _never_ be set).
10411 */
10412 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10413 vcpu->arch.exception_vmexit.pending);
10414
28360f88
SC
10415 /*
10416 * New events, other than exceptions, cannot be injected if KVM needs
10417 * to re-inject a previous event. See above comments on re-injecting
10418 * for why pending exceptions get priority.
10419 */
10420 can_inject = !kvm_event_needs_reinjection(vcpu);
664f8e26 10421
b59bb7bd 10422 if (vcpu->arch.exception.pending) {
5623f751
SC
10423 /*
10424 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10425 * value pushed on the stack. Trap-like exception and all #DBs
10426 * leave RF as-is (KVM follows Intel's behavior in this regard;
10427 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10428 *
10429 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10430 * describe the behavior of General Detect #DBs, which are
10431 * fault-like. They do _not_ set RF, a la code breakpoints.
10432 */
d4963e31 10433 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
d6e8c854
NA
10434 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10435 X86_EFLAGS_RF);
10436
d4963e31
SC
10437 if (vcpu->arch.exception.vector == DB_VECTOR) {
10438 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
f10c729f
JM
10439 if (vcpu->arch.dr7 & DR7_GD) {
10440 vcpu->arch.dr7 &= ~DR7_GD;
10441 kvm_update_dr7(vcpu);
10442 }
6bdf0662
NA
10443 }
10444
b97f0745 10445 kvm_inject_exception(vcpu);
a61d7c54
SC
10446
10447 vcpu->arch.exception.pending = false;
10448 vcpu->arch.exception.injected = true;
10449
c6b22f59 10450 can_inject = false;
1a680e35
LA
10451 }
10452
61e5f69e
ML
10453 /* Don't inject interrupts if the user asked to avoid doing so */
10454 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10455 return 0;
10456
c9d40913
PB
10457 /*
10458 * Finally, inject interrupt events. If an event cannot be injected
10459 * due to architectural conditions (e.g. IF=0) a window-open exit
10460 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10461 * and can architecturally be injected, but we cannot do it right now:
10462 * an interrupt could have arrived just now and we have to inject it
10463 * as a vmexit, or there could already an event in the queue, which is
10464 * indicated by can_inject. In that case we request an immediate exit
10465 * in order to make progress and get back here for another iteration.
10466 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10467 */
31e83e21 10468#ifdef CONFIG_KVM_SMM
c9d40913 10469 if (vcpu->arch.smi_pending) {
89604647
WW
10470 r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10471 -EBUSY;
c9d40913 10472 if (r < 0)
a5f6909a 10473 goto out;
c9d40913
PB
10474 if (r) {
10475 vcpu->arch.smi_pending = false;
10476 ++vcpu->arch.smi_count;
10477 enter_smm(vcpu);
10478 can_inject = false;
10479 } else
89604647 10480 kvm_x86_call(enable_smi_window)(vcpu);
c9d40913 10481 }
31e83e21 10482#endif
c9d40913
PB
10483
10484 if (vcpu->arch.nmi_pending) {
89604647
WW
10485 r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10486 -EBUSY;
c9d40913 10487 if (r < 0)
a5f6909a 10488 goto out;
c9d40913
PB
10489 if (r) {
10490 --vcpu->arch.nmi_pending;
10491 vcpu->arch.nmi_injected = true;
89604647 10492 kvm_x86_call(inject_nmi)(vcpu);
c9d40913 10493 can_inject = false;
89604647 10494 WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
c9d40913
PB
10495 }
10496 if (vcpu->arch.nmi_pending)
89604647 10497 kvm_x86_call(enable_nmi_window)(vcpu);
c9d40913 10498 }
1a680e35 10499
c9d40913 10500 if (kvm_cpu_has_injectable_intr(vcpu)) {
89604647
WW
10501 r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10502 -EBUSY;
c9d40913 10503 if (r < 0)
a5f6909a 10504 goto out;
c9d40913 10505 if (r) {
bf672720
ML
10506 int irq = kvm_cpu_get_interrupt(vcpu);
10507
10508 if (!WARN_ON_ONCE(irq == -1)) {
10509 kvm_queue_interrupt(vcpu, irq, false);
89604647
WW
10510 kvm_x86_call(inject_irq)(vcpu, false);
10511 WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
bf672720 10512 }
c9d40913
PB
10513 }
10514 if (kvm_cpu_has_injectable_intr(vcpu))
89604647 10515 kvm_x86_call(enable_irq_window)(vcpu);
95ba8273 10516 }
ee2cd4b7 10517
c9d40913 10518 if (is_guest_mode(vcpu) &&
5b4ac1a1 10519 kvm_x86_ops.nested_ops->has_events &&
32f55e47 10520 kvm_x86_ops.nested_ops->has_events(vcpu, true))
c9d40913
PB
10521 *req_immediate_exit = true;
10522
dea0d5a2
SC
10523 /*
10524 * KVM must never queue a new exception while injecting an event; KVM
10525 * is done emulating and should only propagate the to-be-injected event
10526 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10527 * infinite loop as KVM will bail from VM-Enter to inject the pending
10528 * exception and start the cycle all over.
10529 *
10530 * Exempt triple faults as they have special handling and won't put the
10531 * vCPU into an infinite loop. Triple fault can be queued when running
10532 * VMX without unrestricted guest, as that requires KVM to emulate Real
10533 * Mode events (see kvm_inject_realmode_interrupt()).
10534 */
10535 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10536 vcpu->arch.exception_vmexit.pending);
a5f6909a 10537 return 0;
c9d40913 10538
a5f6909a
JM
10539out:
10540 if (r == -EBUSY) {
10541 *req_immediate_exit = true;
10542 r = 0;
10543 }
10544 return r;
95ba8273
GN
10545}
10546
7460fb4a
AK
10547static void process_nmi(struct kvm_vcpu *vcpu)
10548{
400fee8c 10549 unsigned int limit;
7460fb4a
AK
10550
10551 /*
400fee8c
SC
10552 * x86 is limited to one NMI pending, but because KVM can't react to
10553 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10554 * scheduled out, KVM needs to play nice with two queued NMIs showing
10555 * up at the same time. To handle this scenario, allow two NMIs to be
10556 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10557 * waiting for a previous NMI injection to complete (which effectively
10558 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10559 * will request an NMI window to handle the second NMI.
7460fb4a 10560 */
89604647 10561 if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
7460fb4a 10562 limit = 1;
400fee8c
SC
10563 else
10564 limit = 2;
7460fb4a 10565
fa4c027a
SS
10566 /*
10567 * Adjust the limit to account for pending virtual NMIs, which aren't
10568 * tracked in vcpu->arch.nmi_pending.
10569 */
89604647 10570 if (kvm_x86_call(is_vnmi_pending)(vcpu))
fa4c027a 10571 limit--;
7460fb4a
AK
10572
10573 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10574 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
2cb93173 10575
fa4c027a 10576 if (vcpu->arch.nmi_pending &&
89604647 10577 (kvm_x86_call(set_vnmi_pending)(vcpu)))
fa4c027a
SS
10578 vcpu->arch.nmi_pending--;
10579
2cb93173
SC
10580 if (vcpu->arch.nmi_pending)
10581 kvm_make_request(KVM_REQ_EVENT, vcpu);
7460fb4a
AK
10582}
10583
fa4c027a
SS
10584/* Return total number of NMIs pending injection to the VM */
10585int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10586{
10587 return vcpu->arch.nmi_pending +
89604647 10588 kvm_x86_call(is_vnmi_pending)(vcpu);
7460fb4a
AK
10589}
10590
7ee30bc1
NNL
10591void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10592 unsigned long *vcpu_bitmap)
10593{
620b2438 10594 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
7ee30bc1
NNL
10595}
10596
2860c4b1
PB
10597void kvm_make_scan_ioapic_request(struct kvm *kvm)
10598{
10599 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10600}
10601
2008fab3 10602void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8df14af4 10603{
ce0a58f4 10604 struct kvm_lapic *apic = vcpu->arch.apic;
06ef8134
ML
10605 bool activate;
10606
8df14af4
SS
10607 if (!lapic_in_kernel(vcpu))
10608 return;
10609
187c8833 10610 down_read(&vcpu->kvm->arch.apicv_update_lock);
66c768d3 10611 preempt_disable();
b0a1637f 10612
8fc9c7a3
SS
10613 /* Do not activate APICV when APIC is disabled */
10614 activate = kvm_vcpu_apicv_activated(vcpu) &&
10615 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
d5fa597e 10616
ce0a58f4 10617 if (apic->apicv_active == activate)
06ef8134
ML
10618 goto out;
10619
ce0a58f4 10620 apic->apicv_active = activate;
8df14af4 10621 kvm_apic_update_apicv(vcpu);
89604647 10622 kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
bca66dbc
VK
10623
10624 /*
10625 * When APICv gets disabled, we may still have injected interrupts
10626 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10627 * still active when the interrupt got accepted. Make sure
e746c1f1 10628 * kvm_check_and_inject_events() is called to check for that.
bca66dbc 10629 */
ce0a58f4 10630 if (!apic->apicv_active)
bca66dbc 10631 kvm_make_request(KVM_REQ_EVENT, vcpu);
b0a1637f 10632
06ef8134 10633out:
66c768d3 10634 preempt_enable();
187c8833 10635 up_read(&vcpu->kvm->arch.apicv_update_lock);
8df14af4 10636}
2008fab3
SC
10637EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10638
10639static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10640{
10641 if (!lapic_in_kernel(vcpu))
10642 return;
10643
10644 /*
10645 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10646 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10647 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
10648 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
ef86fe03
KH
10649 * this case so that KVM can use the AVIC doorbell to inject interrupts
10650 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
2008fab3
SC
10651 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10652 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
10653 * access page is sticky.
10654 */
10655 if (apic_x2apic_mode(vcpu->arch.apic) &&
10656 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10657 kvm_inhibit_apic_access_page(vcpu);
10658
10659 __kvm_vcpu_update_apicv(vcpu);
10660}
8df14af4 10661
320af55a
SC
10662void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10663 enum kvm_apicv_inhibit reason, bool set)
8df14af4 10664{
b0a1637f 10665 unsigned long old, new;
8e205a6b 10666
187c8833
SC
10667 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10668
b3f257a8 10669 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
ef8efd7a
SS
10670 return;
10671
b0a1637f
ML
10672 old = new = kvm->arch.apicv_inhibit_reasons;
10673
4f4c4a3e 10674 set_or_clear_apicv_inhibit(&new, reason, set);
8e205a6b 10675
36222b11 10676 if (!!old != !!new) {
ee49a893
SC
10677 /*
10678 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
6e44d242 10679 * false positives in the sanity check WARN in vcpu_enter_guest().
ee49a893
SC
10680 * This task will wait for all vCPUs to ack the kick IRQ before
10681 * updating apicv_inhibit_reasons, and all other vCPUs will
10682 * block on acquiring apicv_update_lock so that vCPUs can't
6e44d242 10683 * redo vcpu_enter_guest() without seeing the new inhibit state.
ee49a893
SC
10684 *
10685 * Note, holding apicv_update_lock and taking it in the read
10686 * side (handling the request) also prevents other vCPUs from
10687 * servicing the request with a stale apicv_inhibit_reasons.
10688 */
36222b11 10689 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
b0a1637f 10690 kvm->arch.apicv_inhibit_reasons = new;
36222b11
ML
10691 if (new) {
10692 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
074c0080
BG
10693 int idx = srcu_read_lock(&kvm->srcu);
10694
36222b11 10695 kvm_zap_gfn_range(kvm, gfn, gfn+1);
074c0080 10696 srcu_read_unlock(&kvm->srcu, idx);
36222b11 10697 }
7491b7b2 10698 } else {
b0a1637f 10699 kvm->arch.apicv_inhibit_reasons = new;
7491b7b2 10700 }
b0a1637f 10701}
7d611233 10702
320af55a
SC
10703void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10704 enum kvm_apicv_inhibit reason, bool set)
b0a1637f 10705{
f1575642
SC
10706 if (!enable_apicv)
10707 return;
10708
187c8833 10709 down_write(&kvm->arch.apicv_update_lock);
320af55a 10710 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
187c8833 10711 up_write(&kvm->arch.apicv_update_lock);
8df14af4 10712}
320af55a 10713EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
8df14af4 10714
3d81bc7e 10715static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
c7c9c56c 10716{
dcbd3e49 10717 if (!kvm_apic_present(vcpu))
3d81bc7e 10718 return;
c7c9c56c 10719
6308630b 10720 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
87e4951e 10721 vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
c7c9c56c 10722
89604647 10723 kvm_x86_call(sync_pir_to_irr)(vcpu);
f3ced000 10724
b053b2ae 10725 if (irqchip_split(vcpu->kvm))
6308630b 10726 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
f3ced000
SC
10727 else if (ioapic_in_kernel(vcpu->kvm))
10728 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
e40ff1d6
LA
10729
10730 if (is_guest_mode(vcpu))
10731 vcpu->arch.load_eoi_exitmap_pending = true;
10732 else
10733 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10734}
10735
10736static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10737{
e40ff1d6
LA
10738 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10739 return;
10740
b4f69df0 10741#ifdef CONFIG_KVM_HYPERV
c5adbb3a 10742 if (to_hv_vcpu(vcpu)) {
b4f69df0
VK
10743 u64 eoi_exit_bitmap[4];
10744
f2bc14b6
VK
10745 bitmap_or((ulong *)eoi_exit_bitmap,
10746 vcpu->arch.ioapic_handled_vectors,
10747 to_hv_synic(vcpu)->vec_bitmap, 256);
89604647 10748 kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
c5adbb3a 10749 return;
10750 }
b4f69df0 10751#endif
89604647 10752 kvm_x86_call(load_eoi_exitmap)(
c5adbb3a 10753 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
c7c9c56c
YZ
10754}
10755
683412cc
MZ
10756void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10757{
89604647 10758 kvm_x86_call(guest_memory_reclaimed)(kvm);
683412cc
MZ
10759}
10760
d081a343 10761static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
4256f43f 10762{
35754c98 10763 if (!lapic_in_kernel(vcpu))
f439ed27
PB
10764 return;
10765
89604647 10766 kvm_x86_call(set_apic_access_page_addr)(vcpu);
4256f43f 10767}
4256f43f 10768
9357d939 10769/*
8d25b7be 10770 * Called within kvm->srcu read side.
362c698f 10771 * Returns 1 to let vcpu_run() continue the guest execution loop without
9357d939
TY
10772 * exiting to the userspace. Otherwise, the value will be returned to the
10773 * userspace.
10774 */
851ba692 10775static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
b6c7a5dc
HB
10776{
10777 int r;
62a193ed
MG
10778 bool req_int_win =
10779 dm_request_for_irq_injection(vcpu) &&
10780 kvm_cpu_accept_dm_intr(vcpu);
404d5d7b 10781 fastpath_t exit_fastpath;
62a193ed 10782
730dca42 10783 bool req_immediate_exit = false;
b6c7a5dc 10784
2fa6e1e1 10785 if (kvm_request_pending(vcpu)) {
f4d31653 10786 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
67369273
SC
10787 r = -EIO;
10788 goto out;
10789 }
cf87ac73
GS
10790
10791 if (kvm_dirty_ring_check_request(vcpu)) {
10792 r = 0;
10793 goto out;
10794 }
10795
729c15c2 10796 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
9a78e158 10797 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
671ddc70
JM
10798 r = 0;
10799 goto out;
10800 }
10801 }
527d5cd7
SC
10802 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10803 kvm_mmu_free_obsolete_roots(vcpu);
a8eeb04a 10804 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
2f599714 10805 __kvm_migrate_timers(vcpu);
d828199e 10806 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6b6fcd28 10807 kvm_update_masterclock(vcpu->kvm);
0061d53d
MT
10808 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10809 kvm_gen_kvmclock_update(vcpu);
34c238a1
ZA
10810 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10811 r = kvm_guest_time_update(vcpu);
8cfdc000
ZA
10812 if (unlikely(r))
10813 goto out;
10814 }
a8eeb04a 10815 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4731d4c7 10816 kvm_mmu_sync_roots(vcpu);
727a7e27
PB
10817 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10818 kvm_mmu_load_pgd(vcpu);
e94cea09
SC
10819
10820 /*
10821 * Note, the order matters here, as flushing "all" TLB entries
10822 * also flushes the "current" TLB entries, i.e. servicing the
10823 * flush "all" will clear any request to flush "current".
10824 */
10825 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7780938c 10826 kvm_vcpu_flush_tlb_all(vcpu);
eeeb4f67 10827
40e5f908 10828 kvm_service_local_tlb_flush_requests(vcpu);
eeeb4f67 10829
0823570f
VK
10830 /*
10831 * Fall back to a "full" guest flush if Hyper-V's precise
10832 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
10833 * the flushes are considered "remote" and not "local" because
10834 * the requests can be initiated from other vCPUs.
10835 */
b4f69df0 10836#ifdef CONFIG_KVM_HYPERV
0823570f
VK
10837 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10838 kvm_hv_vcpu_flush_tlb(vcpu))
adc43caa 10839 kvm_vcpu_flush_tlb_guest(vcpu);
b4f69df0 10840#endif
adc43caa 10841
a8eeb04a 10842 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
851ba692 10843 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
b93463aa
AK
10844 r = 0;
10845 goto out;
10846 }
92e7d5c8
ML
10847 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10848 if (is_guest_mode(vcpu))
cb6a32c2 10849 kvm_x86_ops.nested_ops->triple_fault(vcpu);
92e7d5c8
ML
10850
10851 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
cb6a32c2
SC
10852 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10853 vcpu->mmio_needed = 0;
10854 r = 0;
e542baf3 10855 goto out;
cb6a32c2 10856 }
71c4dfaf 10857 }
af585b92
GN
10858 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10859 /* Page is swapped out. Do synthetic halt */
10860 vcpu->arch.apf.halted = true;
10861 r = 1;
10862 goto out;
10863 }
c9aaa895
GC
10864 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10865 record_steal_time(vcpu);
fad505b2
MZ
10866 if (kvm_check_request(KVM_REQ_PMU, vcpu))
10867 kvm_pmu_handle_event(vcpu);
10868 if (kvm_check_request(KVM_REQ_PMI, vcpu))
10869 kvm_pmu_deliver_pmi(vcpu);
cf7316d0 10870#ifdef CONFIG_KVM_SMM
64d60670
PB
10871 if (kvm_check_request(KVM_REQ_SMI, vcpu))
10872 process_smi(vcpu);
cf7316d0 10873#endif
7460fb4a
AK
10874 if (kvm_check_request(KVM_REQ_NMI, vcpu))
10875 process_nmi(vcpu);
7543a635
SR
10876 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10877 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10878 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6308630b 10879 vcpu->arch.ioapic_handled_vectors)) {
7543a635
SR
10880 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10881 vcpu->run->eoi.vector =
10882 vcpu->arch.pending_ioapic_eoi;
10883 r = 0;
10884 goto out;
10885 }
10886 }
3d81bc7e
YZ
10887 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10888 vcpu_scan_ioapic(vcpu);
e40ff1d6
LA
10889 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10890 vcpu_load_eoi_exitmap(vcpu);
4256f43f
TC
10891 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10892 kvm_vcpu_reload_apic_access_page(vcpu);
b4f69df0 10893#ifdef CONFIG_KVM_HYPERV
2ce79189
AS
10894 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10895 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10896 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
d495f942 10897 vcpu->run->system_event.ndata = 0;
2ce79189
AS
10898 r = 0;
10899 goto out;
10900 }
e516cebb
AS
10901 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10902 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10903 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
d495f942 10904 vcpu->run->system_event.ndata = 0;
e516cebb
AS
10905 r = 0;
10906 goto out;
10907 }
db397571 10908 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
9ff5e030
VK
10909 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10910
db397571 10911 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
9ff5e030 10912 vcpu->run->hyperv = hv_vcpu->exit;
db397571
AS
10913 r = 0;
10914 goto out;
10915 }
f3b138c5
AS
10916
10917 /*
10918 * KVM_REQ_HV_STIMER has to be processed after
10919 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10920 * depend on the guest clock being up-to-date
10921 */
1f4b34f8
AS
10922 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10923 kvm_hv_process_stimers(vcpu);
b4f69df0 10924#endif
8df14af4
SS
10925 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10926 kvm_vcpu_update_apicv(vcpu);
557a961a
VK
10927 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10928 kvm_check_async_pf_completion(vcpu);
1a155254 10929 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
89604647 10930 kvm_x86_call(msr_filter_changed)(vcpu);
a85863c2
MS
10931
10932 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
89604647 10933 kvm_x86_call(update_cpu_dirty_logging)(vcpu);
e366f92e
TL
10934
10935 if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
10936 kvm_vcpu_reset(vcpu, true);
10937 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
10938 r = 1;
10939 goto out;
10940 }
10941 }
2f52d58c 10942 }
b93463aa 10943
40da8ccd
DW
10944 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10945 kvm_xen_has_interrupt(vcpu)) {
0f1e261e 10946 ++vcpu->stat.req_event;
4fe09bcf
JM
10947 r = kvm_apic_accept_events(vcpu);
10948 if (r < 0) {
10949 r = 0;
10950 goto out;
10951 }
66450a21
JK
10952 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10953 r = 1;
10954 goto out;
10955 }
10956
e746c1f1 10957 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
a5f6909a
JM
10958 if (r < 0) {
10959 r = 0;
10960 goto out;
10961 }
c9d40913 10962 if (req_int_win)
89604647 10963 kvm_x86_call(enable_irq_window)(vcpu);
b463a6f7
AK
10964
10965 if (kvm_lapic_enabled(vcpu)) {
10966 update_cr8_intercept(vcpu);
10967 kvm_lapic_sync_to_vapic(vcpu);
10968 }
10969 }
10970
d8368af8
AK
10971 r = kvm_mmu_reload(vcpu);
10972 if (unlikely(r)) {
d905c069 10973 goto cancel_injection;
d8368af8
AK
10974 }
10975
b6c7a5dc
HB
10976 preempt_disable();
10977
89604647 10978 kvm_x86_call(prepare_switch_to_guest)(vcpu);
b95234c8
PB
10979
10980 /*
10981 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
10982 * IPI are then delayed after guest entry, which ensures that they
10983 * result in virtual interrupt delivery.
10984 */
10985 local_irq_disable();
66fa226c
ML
10986
10987 /* Store vcpu->apicv_active before vcpu->mode. */
10988 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
6b7e2d09 10989
2031f287 10990 kvm_vcpu_srcu_read_unlock(vcpu);
01b71917 10991
0f127d12 10992 /*
b95234c8 10993 * 1) We should set ->mode before checking ->requests. Please see
cde9af6e 10994 * the comment in kvm_vcpu_exiting_guest_mode().
b95234c8 10995 *
81b01667 10996 * 2) For APICv, we should set ->mode before checking PID.ON. This
b95234c8
PB
10997 * pairs with the memory barrier implicit in pi_test_and_set_on
10998 * (see vmx_deliver_posted_interrupt).
10999 *
11000 * 3) This also orders the write to mode from any reads to the page
11001 * tables done while the VCPU is running. Please see the comment
11002 * in kvm_flush_remote_tlbs.
6b7e2d09 11003 */
01b71917 11004 smp_mb__after_srcu_read_unlock();
b6c7a5dc 11005
b95234c8 11006 /*
0f65a9d3
SC
11007 * Process pending posted interrupts to handle the case where the
11008 * notification IRQ arrived in the host, or was never sent (because the
11009 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11010 * status, KVM doesn't update assigned devices when APICv is inhibited,
11011 * i.e. they can post interrupts even if APICv is temporarily disabled.
b95234c8 11012 */
37c4dbf3 11013 if (kvm_lapic_enabled(vcpu))
89604647 11014 kvm_x86_call(sync_pir_to_irr)(vcpu);
32f88400 11015
5a9f5443 11016 if (kvm_vcpu_exit_request(vcpu)) {
6b7e2d09 11017 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 11018 smp_wmb();
6c142801
AK
11019 local_irq_enable();
11020 preempt_enable();
2031f287 11021 kvm_vcpu_srcu_read_lock(vcpu);
6c142801 11022 r = 1;
d905c069 11023 goto cancel_injection;
6c142801
AK
11024 }
11025
0ec3d6d1 11026 if (req_immediate_exit)
c43203ca 11027 kvm_make_request(KVM_REQ_EVENT, vcpu);
d6185f20 11028
2620fe26
SC
11029 fpregs_assert_state_consistent();
11030 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11031 switch_fpu_return();
5f409e20 11032
ec5be88a 11033 if (vcpu->arch.guest_fpu.xfd_err)
78255eb2 11034 wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
ec5be88a 11035
484612f1
IY
11036 if (unlikely(vcpu->arch.switch_db_regs &&
11037 !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
fa7d0f83 11038 set_debugreg(DR7_FIXED_1, 7);
42dbaa5a
JK
11039 set_debugreg(vcpu->arch.eff_db[0], 0);
11040 set_debugreg(vcpu->arch.eff_db[1], 1);
11041 set_debugreg(vcpu->arch.eff_db[2], 2);
11042 set_debugreg(vcpu->arch.eff_db[3], 3);
c2fee09f
SC
11043 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11044 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11045 kvm_x86_call(set_dr6)(vcpu, vcpu->arch.dr6);
f85d4016 11046 } else if (unlikely(hw_breakpoint_active())) {
fa7d0f83 11047 set_debugreg(DR7_FIXED_1, 7);
42dbaa5a 11048 }
b6c7a5dc 11049
189ecdb3
SC
11050 vcpu->arch.host_debugctl = get_debugctlmsr();
11051
b2d2af7e
MR
11052 guest_timing_enter_irqoff();
11053
d89d04ab 11054 for (;;) {
ee49a893
SC
11055 /*
11056 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11057 * update must kick and wait for all vCPUs before toggling the
54aa699e 11058 * per-VM state, and responding vCPUs must wait for the update
ee49a893
SC
11059 * to complete before servicing KVM_REQ_APICV_UPDATE.
11060 */
f8d8ac21
SS
11061 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11062 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
ee49a893 11063
89604647
WW
11064 exit_fastpath = kvm_x86_call(vcpu_run)(vcpu,
11065 req_immediate_exit);
d89d04ab
PB
11066 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11067 break;
11068
37c4dbf3 11069 if (kvm_lapic_enabled(vcpu))
89604647 11070 kvm_x86_call(sync_pir_to_irr)(vcpu);
de7cd3f6
PB
11071
11072 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
d89d04ab
PB
11073 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11074 break;
11075 }
8b703a49
SC
11076
11077 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11078 ++vcpu->stat.exits;
de7cd3f6 11079 }
b6c7a5dc 11080
c77fb5fe
PB
11081 /*
11082 * Do this here before restoring debug registers on the host. And
11083 * since we do this before handling the vmexit, a DR access vmexit
11084 * can (a) read the correct value of the debug registers, (b) set
11085 * KVM_DEBUGREG_WONT_EXIT again.
11086 */
11087 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
c77fb5fe 11088 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
484612f1 11089 WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
89604647 11090 kvm_x86_call(sync_dirty_debug_regs)(vcpu);
70e4da7a 11091 kvm_update_dr0123(vcpu);
70e4da7a 11092 kvm_update_dr7(vcpu);
c77fb5fe
PB
11093 }
11094
24f1e32c
FW
11095 /*
11096 * If the guest has used debug registers, at least dr7
11097 * will be disabled while returning to the host.
11098 * If we don't have active breakpoints in the host, we don't
11099 * care about the messed up debug address registers. But if
11100 * we have some of them active, restore the old state.
11101 */
59d8eb53 11102 if (hw_breakpoint_active())
24f1e32c 11103 hw_breakpoint_restore();
42dbaa5a 11104
c967118d 11105 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
4ba76538 11106 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1d5f066e 11107
6b7e2d09 11108 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 11109 smp_wmb();
a547c6db 11110
b5274b1b
KT
11111 /*
11112 * Sync xfd before calling handle_exit_irqoff() which may
11113 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11114 * in #NM irqoff handler).
11115 */
11116 if (vcpu->arch.xfd_no_write_intercept)
11117 fpu_sync_guest_vmexit_xfd_state();
11118
89604647 11119 kvm_x86_call(handle_exit_irqoff)(vcpu);
b6c7a5dc 11120
ec5be88a 11121 if (vcpu->arch.guest_fpu.xfd_err)
78255eb2 11122 wrmsrq(MSR_IA32_XFD_ERR, 0);
ec5be88a 11123
d7a08882
SC
11124 /*
11125 * Consume any pending interrupts, including the possible source of
11126 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11127 * An instruction is required after local_irq_enable() to fully unblock
11128 * interrupts on processors that implement an interrupt shadow, the
11129 * stat.exits increment will do nicely.
11130 */
db215756 11131 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
d7a08882 11132 local_irq_enable();
b6c7a5dc 11133 ++vcpu->stat.exits;
d7a08882
SC
11134 local_irq_disable();
11135 kvm_after_interrupt(vcpu);
b6c7a5dc 11136
16045714
WL
11137 /*
11138 * Wait until after servicing IRQs to account guest time so that any
11139 * ticks that occurred while running the guest are properly accounted
11140 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11141 * of accounting via context tracking, but the loss of accuracy is
11142 * acceptable for all known use cases.
11143 */
b2d2af7e 11144 guest_timing_exit_irqoff();
16045714 11145
f2485b3e 11146 local_irq_enable();
b6c7a5dc
HB
11147 preempt_enable();
11148
2031f287 11149 kvm_vcpu_srcu_read_lock(vcpu);
3200f405 11150
65a4de0f
YZ
11151 /*
11152 * Call this to ensure WC buffers in guest are evicted after each VM
11153 * Exit, so that the evicted WC writes can be snooped across all cpus
11154 */
11155 smp_mb__after_srcu_read_lock();
11156
b6c7a5dc
HB
11157 /*
11158 * Profile KVM exit RIPs:
11159 */
38e93267
AH
11160 if (unlikely(prof_on == KVM_PROFILING &&
11161 !vcpu->arch.guest_state_protected)) {
5fdbf976
MT
11162 unsigned long rip = kvm_rip_read(vcpu);
11163 profile_hit(KVM_PROFILING, (void *)rip);
b6c7a5dc
HB
11164 }
11165
cc578287
ZA
11166 if (unlikely(vcpu->arch.tsc_always_catchup))
11167 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
298101da 11168
5cfb1d5a
MT
11169 if (vcpu->arch.apic_attention)
11170 kvm_lapic_sync_from_vapic(vcpu);
b93463aa 11171
f7f39c50
SC
11172 if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11173 return 0;
11174
89604647 11175 r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
d905c069
MT
11176 return r;
11177
11178cancel_injection:
8081ad06
SC
11179 if (req_immediate_exit)
11180 kvm_make_request(KVM_REQ_EVENT, vcpu);
89604647 11181 kvm_x86_call(cancel_injection)(vcpu);
ae7a2a3f
MT
11182 if (unlikely(vcpu->arch.apic_attention))
11183 kvm_lapic_sync_from_vapic(vcpu);
d7690175
MT
11184out:
11185 return r;
11186}
b6c7a5dc 11187
70cdd238
SC
11188static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11189{
11190 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11191 !vcpu->arch.apf.halted);
11192}
11193
44428e49 11194bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
70cdd238
SC
11195{
11196 if (!list_empty_careful(&vcpu->async_pf.done))
11197 return true;
11198
11199 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11200 kvm_apic_init_sipi_allowed(vcpu))
11201 return true;
11202
70cdd238
SC
11203 if (kvm_is_exception_pending(vcpu))
11204 return true;
11205
11206 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11207 (vcpu->arch.nmi_pending &&
11208 kvm_x86_call(nmi_allowed)(vcpu, false)))
11209 return true;
11210
11211#ifdef CONFIG_KVM_SMM
11212 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11213 (vcpu->arch.smi_pending &&
11214 kvm_x86_call(smi_allowed)(vcpu, false)))
11215 return true;
11216#endif
11217
11218 if (kvm_test_request(KVM_REQ_PMI, vcpu))
11219 return true;
11220
11221 if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11222 return true;
11223
11224 if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11225 return true;
11226
11227 if (kvm_hv_has_stimer_pending(vcpu))
11228 return true;
11229
11230 if (is_guest_mode(vcpu) &&
11231 kvm_x86_ops.nested_ops->has_events &&
11232 kvm_x86_ops.nested_ops->has_events(vcpu, false))
11233 return true;
11234
11235 if (kvm_xen_has_pending_events(vcpu))
11236 return true;
11237
11238 return false;
11239}
44428e49 11240EXPORT_SYMBOL_GPL(kvm_vcpu_has_events);
70cdd238
SC
11241
11242int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11243{
44428e49
BW
11244 return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11245 kvm_vcpu_has_events(vcpu);
70cdd238
SC
11246}
11247
8d25b7be 11248/* Called within kvm->srcu read side. */
2031f287 11249static inline int vcpu_block(struct kvm_vcpu *vcpu)
362c698f 11250{
98c25ead
SC
11251 bool hv_timer;
11252
c3e8abf0 11253 if (!kvm_arch_vcpu_runnable(vcpu)) {
98c25ead
SC
11254 /*
11255 * Switch to the software timer before halt-polling/blocking as
11256 * the guest's timer may be a break event for the vCPU, and the
11257 * hypervisor timer runs only when the CPU is in guest mode.
11258 * Switch before halt-polling so that KVM recognizes an expired
11259 * timer before blocking.
11260 */
11261 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11262 if (hv_timer)
11263 kvm_lapic_switch_to_sw_timer(vcpu);
11264
2031f287 11265 kvm_vcpu_srcu_read_unlock(vcpu);
cdafece4
SC
11266 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11267 kvm_vcpu_halt(vcpu);
11268 else
11269 kvm_vcpu_block(vcpu);
2031f287 11270 kvm_vcpu_srcu_read_lock(vcpu);
bf9f6ac8 11271
98c25ead
SC
11272 if (hv_timer)
11273 kvm_lapic_switch_to_hv_timer(vcpu);
11274
599275c0
PB
11275 /*
11276 * If the vCPU is not runnable, a signal or another host event
11277 * of some kind is pending; service it without changing the
11278 * vCPU's activity state.
11279 */
11280 if (!kvm_arch_vcpu_runnable(vcpu))
9c8fd1ba
PB
11281 return 1;
11282 }
362c698f 11283
26844fee
PB
11284 /*
11285 * Evaluate nested events before exiting the halted state. This allows
11286 * the halt state to be recorded properly in the VMCS12's activity
11287 * state field (AMD does not have a similar field and a VM-Exit always
11288 * causes a spurious wakeup from HLT).
11289 */
11290 if (is_guest_mode(vcpu)) {
45405155
SC
11291 int r = kvm_check_nested_events(vcpu);
11292
11293 WARN_ON_ONCE(r == -EBUSY);
11294 if (r < 0)
26844fee
PB
11295 return 0;
11296 }
11297
4fe09bcf
JM
11298 if (kvm_apic_accept_events(vcpu) < 0)
11299 return 0;
362c698f
PB
11300 switch(vcpu->arch.mp_state) {
11301 case KVM_MP_STATE_HALTED:
647daca2 11302 case KVM_MP_STATE_AP_RESET_HOLD:
c9e5f3fa 11303 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
df561f66 11304 fallthrough;
362c698f
PB
11305 case KVM_MP_STATE_RUNNABLE:
11306 vcpu->arch.apf.halted = false;
11307 break;
11308 case KVM_MP_STATE_INIT_RECEIVED:
11309 break;
11310 default:
22c6a0ef
PB
11311 WARN_ON_ONCE(1);
11312 break;
362c698f
PB
11313 }
11314 return 1;
11315}
09cec754 11316
8d25b7be 11317/* Called within kvm->srcu read side. */
362c698f 11318static int vcpu_run(struct kvm_vcpu *vcpu)
d7690175
MT
11319{
11320 int r;
11321
ee605e31 11322 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
d7690175 11323
362c698f 11324 for (;;) {
6cd88243
PB
11325 /*
11326 * If another guest vCPU requests a PV TLB flush in the middle
11327 * of instruction emulation, the rest of the emulation could
11328 * use a stale page translation. Assume that any code after
11329 * this point can start executing an instruction.
11330 */
11331 vcpu->arch.at_instruction_boundary = false;
58f800d5 11332 if (kvm_vcpu_running(vcpu)) {
851ba692 11333 r = vcpu_enter_guest(vcpu);
bf9f6ac8 11334 } else {
2031f287 11335 r = vcpu_block(vcpu);
bf9f6ac8
FW
11336 }
11337
09cec754
GN
11338 if (r <= 0)
11339 break;
11340
084071d5 11341 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
7caf9571
DW
11342 if (kvm_xen_has_pending_events(vcpu))
11343 kvm_xen_inject_pending_events(vcpu);
11344
09cec754
GN
11345 if (kvm_cpu_has_pending_timer(vcpu))
11346 kvm_inject_pending_timer_irqs(vcpu);
11347
782d422b
MG
11348 if (dm_request_for_irq_injection(vcpu) &&
11349 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
4ca7dd8c
PB
11350 r = 0;
11351 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
09cec754 11352 ++vcpu->stat.request_irq_exits;
362c698f 11353 break;
09cec754 11354 }
af585b92 11355
f3020b88 11356 if (__xfer_to_guest_mode_work_pending()) {
2031f287 11357 kvm_vcpu_srcu_read_unlock(vcpu);
72c3c0fe 11358 r = xfer_to_guest_mode_handle_work(vcpu);
2031f287 11359 kvm_vcpu_srcu_read_lock(vcpu);
72c3c0fe
TG
11360 if (r)
11361 return r;
d7690175 11362 }
b6c7a5dc
HB
11363 }
11364
b6c7a5dc
HB
11365 return r;
11366}
11367
70cdd238
SC
11368static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11369{
11370 /*
11371 * The vCPU has halted, e.g. executed HLT. Update the run state if the
11372 * local APIC is in-kernel, the run loop will detect the non-runnable
11373 * state and halt the vCPU. Exit to userspace if the local APIC is
11374 * managed by userspace, in which case userspace is responsible for
11375 * handling wake events.
11376 */
11377 ++vcpu->stat.halt_exits;
11378 if (lapic_in_kernel(vcpu)) {
44428e49 11379 if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
2a289aed
SC
11380 state = KVM_MP_STATE_RUNNABLE;
11381 kvm_set_mp_state(vcpu, state);
70cdd238
SC
11382 return 1;
11383 } else {
11384 vcpu->run->exit_reason = reason;
11385 return 0;
11386 }
11387}
11388
11389int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11390{
11391 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11392}
11393EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
11394
11395int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11396{
11397 int ret = kvm_skip_emulated_instruction(vcpu);
11398 /*
11399 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11400 * KVM_EXIT_DEBUG here.
11401 */
11402 return kvm_emulate_halt_noskip(vcpu) && ret;
11403}
11404EXPORT_SYMBOL_GPL(kvm_emulate_halt);
11405
1876dd69
SC
11406fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11407{
11408 int ret;
11409
11410 kvm_vcpu_srcu_read_lock(vcpu);
11411 ret = kvm_emulate_halt(vcpu);
11412 kvm_vcpu_srcu_read_unlock(vcpu);
11413
11414 if (!ret)
11415 return EXIT_FASTPATH_EXIT_USERSPACE;
11416
11417 if (kvm_vcpu_running(vcpu))
11418 return EXIT_FASTPATH_REENTER_GUEST;
11419
11420 return EXIT_FASTPATH_EXIT_HANDLED;
11421}
11422EXPORT_SYMBOL_GPL(handle_fastpath_hlt);
11423
70cdd238
SC
11424int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11425{
11426 int ret = kvm_skip_emulated_instruction(vcpu);
11427
11428 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11429 KVM_EXIT_AP_RESET_HOLD) && ret;
11430}
11431EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
11432
11433bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11434{
11435 return kvm_vcpu_apicv_active(vcpu) &&
11436 kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11437}
11438
11439bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11440{
11441 return vcpu->arch.preempted_in_kernel;
11442}
11443
11444bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11445{
11446 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11447 return true;
11448
11449 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11450#ifdef CONFIG_KVM_SMM
11451 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11452#endif
11453 kvm_test_request(KVM_REQ_EVENT, vcpu))
11454 return true;
11455
11456 return kvm_arch_dy_has_pending_interrupt(vcpu);
11457}
11458
716d51ab
GN
11459static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11460{
2d089356 11461 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
716d51ab
GN
11462}
11463
11464static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11465{
11466 BUG_ON(!vcpu->arch.pio.count);
11467
11468 return complete_emulated_io(vcpu);
11469}
11470
f78146b0
AK
11471/*
11472 * Implements the following, as a state machine:
11473 *
11474 * read:
11475 * for each fragment
87da7e66
XG
11476 * for each mmio piece in the fragment
11477 * write gpa, len
11478 * exit
11479 * copy data
f78146b0
AK
11480 * execute insn
11481 *
11482 * write:
11483 * for each fragment
87da7e66
XG
11484 * for each mmio piece in the fragment
11485 * write gpa, len
11486 * copy data
11487 * exit
f78146b0 11488 */
716d51ab 11489static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
5287f194
AK
11490{
11491 struct kvm_run *run = vcpu->run;
f78146b0 11492 struct kvm_mmio_fragment *frag;
87da7e66 11493 unsigned len;
5287f194 11494
716d51ab 11495 BUG_ON(!vcpu->mmio_needed);
5287f194 11496
716d51ab 11497 /* Complete previous fragment */
87da7e66
XG
11498 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11499 len = min(8u, frag->len);
716d51ab 11500 if (!vcpu->mmio_is_write)
87da7e66
XG
11501 memcpy(frag->data, run->mmio.data, len);
11502
11503 if (frag->len <= 8) {
11504 /* Switch to the next fragment. */
11505 frag++;
11506 vcpu->mmio_cur_fragment++;
11507 } else {
11508 /* Go forward to the next mmio piece. */
11509 frag->data += len;
11510 frag->gpa += len;
11511 frag->len -= len;
11512 }
11513
a08d3b3b 11514 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
716d51ab 11515 vcpu->mmio_needed = 0;
0912c977
PB
11516
11517 /* FIXME: return into emulator if single-stepping. */
cef4dea0 11518 if (vcpu->mmio_is_write)
716d51ab
GN
11519 return 1;
11520 vcpu->mmio_read_completed = 1;
11521 return complete_emulated_io(vcpu);
11522 }
87da7e66 11523
716d51ab
GN
11524 run->exit_reason = KVM_EXIT_MMIO;
11525 run->mmio.phys_addr = frag->gpa;
11526 if (vcpu->mmio_is_write)
87da7e66
XG
11527 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11528 run->mmio.len = min(8u, frag->len);
716d51ab
GN
11529 run->mmio.is_write = vcpu->mmio_is_write;
11530 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11531 return 0;
5287f194
AK
11532}
11533
822f312d
SAS
11534/* Swap (qemu) user FPU context for the guest FPU context. */
11535static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11536{
e27bc044 11537 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
d69c1382 11538 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
822f312d
SAS
11539 trace_kvm_fpu(1);
11540}
11541
11542/* When vcpu_run ends, restore user space FPU context. */
11543static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11544{
d69c1382 11545 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
822f312d
SAS
11546 ++vcpu->stat.fpu_reload;
11547 trace_kvm_fpu(0);
11548}
11549
1b94f6f8 11550int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
b6c7a5dc 11551{
7709aba8 11552 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1b94f6f8 11553 struct kvm_run *kvm_run = vcpu->run;
a476cadf 11554 u64 sync_valid_fields;
b6c7a5dc 11555 int r;
b6c7a5dc 11556
931656b9
KB
11557 r = kvm_mmu_post_init_vm(vcpu->kvm);
11558 if (r)
11559 return r;
11560
accb757d 11561 vcpu_load(vcpu);
20b7035c 11562 kvm_sigset_activate(vcpu);
15aad3be 11563 kvm_run->flags = 0;
5663d8f9
PX
11564 kvm_load_guest_fpu(vcpu);
11565
2031f287 11566 kvm_vcpu_srcu_read_lock(vcpu);
a4535290 11567 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
a6816314 11568 if (!vcpu->wants_to_run) {
2f173d26
JS
11569 r = -EINTR;
11570 goto out;
11571 }
7b0151ca 11572
98c25ead 11573 /*
7b0151ca
SC
11574 * Don't bother switching APIC timer emulation from the
11575 * hypervisor timer to the software timer, the only way for the
11576 * APIC timer to be active is if userspace stuffed vCPU state,
11577 * i.e. put the vCPU into a nonsensical state. Only an INIT
11578 * will transition the vCPU out of UNINITIALIZED (without more
11579 * state stuffing from userspace), which will reset the local
11580 * APIC and thus cancel the timer or drop the IRQ (if the timer
11581 * already expired).
98c25ead 11582 */
2031f287 11583 kvm_vcpu_srcu_read_unlock(vcpu);
c91d4497 11584 kvm_vcpu_block(vcpu);
2031f287 11585 kvm_vcpu_srcu_read_lock(vcpu);
8d25b7be 11586
4fe09bcf
JM
11587 if (kvm_apic_accept_events(vcpu) < 0) {
11588 r = 0;
11589 goto out;
11590 }
ac9f6dc0 11591 r = -EAGAIN;
a0595000
JS
11592 if (signal_pending(current)) {
11593 r = -EINTR;
1b94f6f8 11594 kvm_run->exit_reason = KVM_EXIT_INTR;
a0595000
JS
11595 ++vcpu->stat.signal_exits;
11596 }
ac9f6dc0 11597 goto out;
b6c7a5dc
HB
11598 }
11599
74c1807f
PB
11600 sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11601 if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11602 (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
01643c51
KH
11603 r = -EINVAL;
11604 goto out;
11605 }
11606
1b94f6f8 11607 if (kvm_run->kvm_dirty_regs) {
01643c51
KH
11608 r = sync_regs(vcpu);
11609 if (r != 0)
11610 goto out;
11611 }
11612
b6c7a5dc 11613 /* re-sync apic's tpr */
35754c98 11614 if (!lapic_in_kernel(vcpu)) {
eea1cff9
AP
11615 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11616 r = -EINVAL;
11617 goto out;
11618 }
11619 }
b6c7a5dc 11620
7709aba8
SC
11621 /*
11622 * If userspace set a pending exception and L2 is active, convert it to
11623 * a pending VM-Exit if L1 wants to intercept the exception.
11624 */
11625 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11626 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11627 ex->error_code)) {
11628 kvm_queue_exception_vmexit(vcpu, ex->vector,
11629 ex->has_error_code, ex->error_code,
11630 ex->has_payload, ex->payload);
11631 ex->injected = false;
11632 ex->pending = false;
11633 }
11634 vcpu->arch.exception_from_userspace = false;
11635
716d51ab
GN
11636 if (unlikely(vcpu->arch.complete_userspace_io)) {
11637 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11638 vcpu->arch.complete_userspace_io = NULL;
11639 r = cui(vcpu);
11640 if (r <= 0)
5663d8f9 11641 goto out;
0bc27326
SC
11642 } else {
11643 WARN_ON_ONCE(vcpu->arch.pio.count);
11644 WARN_ON_ONCE(vcpu->mmio_needed);
11645 }
5287f194 11646
a6816314 11647 if (!vcpu->wants_to_run) {
460df4c1 11648 r = -EINTR;
fc4fad79
SC
11649 goto out;
11650 }
11651
89604647 11652 r = kvm_x86_call(vcpu_pre_run)(vcpu);
fc4fad79
SC
11653 if (r <= 0)
11654 goto out;
11655
11656 r = vcpu_run(vcpu);
b6c7a5dc
HB
11657
11658out:
5663d8f9 11659 kvm_put_guest_fpu(vcpu);
74c1807f 11660 if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
01643c51 11661 store_regs(vcpu);
f1d86e46 11662 post_kvm_run_save(vcpu);
2031f287 11663 kvm_vcpu_srcu_read_unlock(vcpu);
b6c7a5dc 11664
8d25b7be 11665 kvm_sigset_deactivate(vcpu);
accb757d 11666 vcpu_put(vcpu);
b6c7a5dc
HB
11667 return r;
11668}
11669
01643c51 11670static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 11671{
7ae441ea
GN
11672 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11673 /*
11674 * We are here if userspace calls get_regs() in the middle of
11675 * instruction emulation. Registers state needs to be copied
4a969980 11676 * back from emulation context to vcpu. Userspace shouldn't do
7ae441ea
GN
11677 * that usually, but some bad designed PV devices (vmware
11678 * backdoor interface) need this to work
11679 */
c9b8b07c 11680 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
7ae441ea
GN
11681 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11682 }
de3cd117
SC
11683 regs->rax = kvm_rax_read(vcpu);
11684 regs->rbx = kvm_rbx_read(vcpu);
11685 regs->rcx = kvm_rcx_read(vcpu);
11686 regs->rdx = kvm_rdx_read(vcpu);
11687 regs->rsi = kvm_rsi_read(vcpu);
11688 regs->rdi = kvm_rdi_read(vcpu);
e9c16c78 11689 regs->rsp = kvm_rsp_read(vcpu);
de3cd117 11690 regs->rbp = kvm_rbp_read(vcpu);
b6c7a5dc 11691#ifdef CONFIG_X86_64
de3cd117
SC
11692 regs->r8 = kvm_r8_read(vcpu);
11693 regs->r9 = kvm_r9_read(vcpu);
11694 regs->r10 = kvm_r10_read(vcpu);
11695 regs->r11 = kvm_r11_read(vcpu);
11696 regs->r12 = kvm_r12_read(vcpu);
11697 regs->r13 = kvm_r13_read(vcpu);
11698 regs->r14 = kvm_r14_read(vcpu);
11699 regs->r15 = kvm_r15_read(vcpu);
b6c7a5dc
HB
11700#endif
11701
5fdbf976 11702 regs->rip = kvm_rip_read(vcpu);
91586a3b 11703 regs->rflags = kvm_get_rflags(vcpu);
01643c51 11704}
b6c7a5dc 11705
01643c51
KH
11706int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11707{
517987e3
PB
11708 if (vcpu->kvm->arch.has_protected_state &&
11709 vcpu->arch.guest_state_protected)
11710 return -EINVAL;
11711
01643c51
KH
11712 vcpu_load(vcpu);
11713 __get_regs(vcpu, regs);
1fc9b76b 11714 vcpu_put(vcpu);
b6c7a5dc
HB
11715 return 0;
11716}
11717
01643c51 11718static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 11719{
7ae441ea
GN
11720 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11721 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11722
de3cd117
SC
11723 kvm_rax_write(vcpu, regs->rax);
11724 kvm_rbx_write(vcpu, regs->rbx);
11725 kvm_rcx_write(vcpu, regs->rcx);
11726 kvm_rdx_write(vcpu, regs->rdx);
11727 kvm_rsi_write(vcpu, regs->rsi);
11728 kvm_rdi_write(vcpu, regs->rdi);
e9c16c78 11729 kvm_rsp_write(vcpu, regs->rsp);
de3cd117 11730 kvm_rbp_write(vcpu, regs->rbp);
b6c7a5dc 11731#ifdef CONFIG_X86_64
de3cd117
SC
11732 kvm_r8_write(vcpu, regs->r8);
11733 kvm_r9_write(vcpu, regs->r9);
11734 kvm_r10_write(vcpu, regs->r10);
11735 kvm_r11_write(vcpu, regs->r11);
11736 kvm_r12_write(vcpu, regs->r12);
11737 kvm_r13_write(vcpu, regs->r13);
11738 kvm_r14_write(vcpu, regs->r14);
11739 kvm_r15_write(vcpu, regs->r15);
b6c7a5dc
HB
11740#endif
11741
5fdbf976 11742 kvm_rip_write(vcpu, regs->rip);
d73235d1 11743 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
b6c7a5dc 11744
b4f14abd 11745 vcpu->arch.exception.pending = false;
7709aba8 11746 vcpu->arch.exception_vmexit.pending = false;
b4f14abd 11747
3842d135 11748 kvm_make_request(KVM_REQ_EVENT, vcpu);
01643c51 11749}
3842d135 11750
01643c51
KH
11751int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11752{
517987e3
PB
11753 if (vcpu->kvm->arch.has_protected_state &&
11754 vcpu->arch.guest_state_protected)
11755 return -EINVAL;
11756
01643c51
KH
11757 vcpu_load(vcpu);
11758 __set_regs(vcpu, regs);
875656fe 11759 vcpu_put(vcpu);
b6c7a5dc
HB
11760 return 0;
11761}
11762
6dba9403 11763static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
b6c7a5dc 11764{
89a27f4d 11765 struct desc_ptr dt;
b6c7a5dc 11766
5265713a
TL
11767 if (vcpu->arch.guest_state_protected)
11768 goto skip_protected_regs;
11769
3e6e0aab
GT
11770 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11771 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11772 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11773 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11774 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11775 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 11776
3e6e0aab
GT
11777 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11778 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 11779
89604647 11780 kvm_x86_call(get_idt)(vcpu, &dt);
89a27f4d
GN
11781 sregs->idt.limit = dt.size;
11782 sregs->idt.base = dt.address;
89604647 11783 kvm_x86_call(get_gdt)(vcpu, &dt);
89a27f4d
GN
11784 sregs->gdt.limit = dt.size;
11785 sregs->gdt.base = dt.address;
b6c7a5dc 11786
ad312c7c 11787 sregs->cr2 = vcpu->arch.cr2;
9f8fe504 11788 sregs->cr3 = kvm_read_cr3(vcpu);
5265713a
TL
11789
11790skip_protected_regs:
11791 sregs->cr0 = kvm_read_cr0(vcpu);
fc78f519 11792 sregs->cr4 = kvm_read_cr4(vcpu);
2d3ad1f4 11793 sregs->cr8 = kvm_get_cr8(vcpu);
f6801dff 11794 sregs->efer = vcpu->arch.efer;
d91060e3 11795 sregs->apic_base = vcpu->arch.apic_base;
6dba9403 11796}
b6c7a5dc 11797
6dba9403
ML
11798static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11799{
11800 __get_sregs_common(vcpu, sregs);
11801
11802 if (vcpu->arch.guest_state_protected)
11803 return;
b6c7a5dc 11804
04140b41 11805 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
14d0bc1f
GN
11806 set_bit(vcpu->arch.interrupt.nr,
11807 (unsigned long *)sregs->interrupt_bitmap);
01643c51 11808}
16d7a191 11809
6dba9403
ML
11810static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11811{
11812 int i;
11813
11814 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11815
11816 if (vcpu->arch.guest_state_protected)
11817 return;
11818
11819 if (is_pae_paging(vcpu)) {
11820 for (i = 0 ; i < 4 ; i++)
11821 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11822 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11823 }
11824}
11825
01643c51
KH
11826int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11827 struct kvm_sregs *sregs)
11828{
517987e3
PB
11829 if (vcpu->kvm->arch.has_protected_state &&
11830 vcpu->arch.guest_state_protected)
11831 return -EINVAL;
11832
01643c51
KH
11833 vcpu_load(vcpu);
11834 __get_sregs(vcpu, sregs);
bcdec41c 11835 vcpu_put(vcpu);
b6c7a5dc
HB
11836 return 0;
11837}
11838
62d9f0db
MT
11839int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11840 struct kvm_mp_state *mp_state)
11841{
4fe09bcf
JM
11842 int r;
11843
fd232561 11844 vcpu_load(vcpu);
f958bd23
SC
11845 if (kvm_mpx_supported())
11846 kvm_load_guest_fpu(vcpu);
fd232561 11847
ef01cac4
SC
11848 kvm_vcpu_srcu_read_lock(vcpu);
11849
4fe09bcf
JM
11850 r = kvm_apic_accept_events(vcpu);
11851 if (r < 0)
11852 goto out;
11853 r = 0;
11854
647daca2
TL
11855 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11856 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11857 vcpu->arch.pv.pv_unhalted)
6aef266c
SV
11858 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11859 else
11860 mp_state->mp_state = vcpu->arch.mp_state;
11861
4fe09bcf 11862out:
ef01cac4
SC
11863 kvm_vcpu_srcu_read_unlock(vcpu);
11864
f958bd23
SC
11865 if (kvm_mpx_supported())
11866 kvm_put_guest_fpu(vcpu);
fd232561 11867 vcpu_put(vcpu);
4fe09bcf 11868 return r;
62d9f0db
MT
11869}
11870
11871int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11872 struct kvm_mp_state *mp_state)
11873{
e83dff5e
CD
11874 int ret = -EINVAL;
11875
11876 vcpu_load(vcpu);
11877
22c6a0ef
PB
11878 switch (mp_state->mp_state) {
11879 case KVM_MP_STATE_UNINITIALIZED:
11880 case KVM_MP_STATE_HALTED:
11881 case KVM_MP_STATE_AP_RESET_HOLD:
11882 case KVM_MP_STATE_INIT_RECEIVED:
11883 case KVM_MP_STATE_SIPI_RECEIVED:
11884 if (!lapic_in_kernel(vcpu))
11885 goto out;
11886 break;
11887
11888 case KVM_MP_STATE_RUNNABLE:
11889 break;
11890
11891 default:
e83dff5e 11892 goto out;
22c6a0ef 11893 }
66450a21 11894
27cbe7d6 11895 /*
1b7a1b78
SC
11896 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11897 * forcing the guest into INIT/SIPI if those events are supposed to be
11898 * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11899 * if an SMI is pending as well.
27cbe7d6 11900 */
1b7a1b78 11901 if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
28bf2888
DH
11902 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11903 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
e83dff5e 11904 goto out;
28bf2888 11905
66450a21 11906 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
c9e5f3fa 11907 kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
66450a21
JK
11908 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11909 } else
c9e5f3fa 11910 kvm_set_mp_state(vcpu, mp_state->mp_state);
3842d135 11911 kvm_make_request(KVM_REQ_EVENT, vcpu);
e83dff5e
CD
11912
11913 ret = 0;
11914out:
11915 vcpu_put(vcpu);
11916 return ret;
62d9f0db
MT
11917}
11918
7f3d35fd
KW
11919int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11920 int reason, bool has_error_code, u32 error_code)
b6c7a5dc 11921{
c9b8b07c 11922 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d 11923 int ret;
e01c2426 11924
8ec4722d 11925 init_emulate_ctxt(vcpu);
c697518a 11926
7f3d35fd 11927 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9d74191a 11928 has_error_code, error_code);
2a1fc7dc
SC
11929
11930 /*
11931 * Report an error userspace if MMIO is needed, as KVM doesn't support
11932 * MMIO during a task switch (or any other complex operation).
11933 */
11934 if (ret || vcpu->mmio_needed) {
11935 vcpu->mmio_needed = false;
1051778f
SC
11936 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11937 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11938 vcpu->run->internal.ndata = 0;
60fc3d02 11939 return 0;
1051778f 11940 }
37817f29 11941
9d74191a
TY
11942 kvm_rip_write(vcpu, ctxt->eip);
11943 kvm_set_rflags(vcpu, ctxt->eflags);
60fc3d02 11944 return 1;
37817f29
IE
11945}
11946EXPORT_SYMBOL_GPL(kvm_task_switch);
11947
ee69c92b 11948static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
f2981033 11949{
37b95951 11950 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
f2981033
LT
11951 /*
11952 * When EFER.LME and CR0.PG are set, the processor is in
11953 * 64-bit mode (though maybe in a 32-bit code segment).
11954 * CR4.PAE and EFER.LMA must be set.
11955 */
ee69c92b
SC
11956 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11957 return false;
2c49db45 11958 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
c1c35cf7 11959 return false;
f2981033
LT
11960 } else {
11961 /*
11962 * Not in 64-bit mode: EFER.LMA is clear and the code
11963 * segment cannot be 64-bit.
11964 */
11965 if (sregs->efer & EFER_LMA || sregs->cs.l)
ee69c92b 11966 return false;
f2981033
LT
11967 }
11968
26a0652c
SC
11969 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11970 kvm_is_valid_cr0(vcpu, sregs->cr0);
f2981033
LT
11971}
11972
6dba9403
ML
11973static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11974 int *mmu_reset_needed, bool update_pdptrs)
b6c7a5dc 11975{
6dba9403 11976 int idx;
89a27f4d 11977 struct desc_ptr dt;
b4ef9d4e 11978
ee69c92b 11979 if (!kvm_is_valid_sregs(vcpu, sregs))
6dba9403 11980 return -EINVAL;
f2981033 11981
c9155eb0 11982 if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
6dba9403 11983 return -EINVAL;
6d1068b3 11984
5265713a 11985 if (vcpu->arch.guest_state_protected)
6dba9403 11986 return 0;
5265713a 11987
89a27f4d
GN
11988 dt.size = sregs->idt.limit;
11989 dt.address = sregs->idt.base;
89604647 11990 kvm_x86_call(set_idt)(vcpu, &dt);
89a27f4d
GN
11991 dt.size = sregs->gdt.limit;
11992 dt.address = sregs->gdt.base;
89604647 11993 kvm_x86_call(set_gdt)(vcpu, &dt);
b6c7a5dc 11994
ad312c7c 11995 vcpu->arch.cr2 = sregs->cr2;
6dba9403 11996 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
dc7e795e 11997 vcpu->arch.cr3 = sregs->cr3;
3883bc9d 11998 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
89604647 11999 kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
b6c7a5dc 12000
2d3ad1f4 12001 kvm_set_cr8(vcpu, sregs->cr8);
b6c7a5dc 12002
6dba9403 12003 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
89604647 12004 kvm_x86_call(set_efer)(vcpu, sregs->efer);
b6c7a5dc 12005
6dba9403 12006 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
89604647 12007 kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
b6c7a5dc 12008
6dba9403 12009 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
89604647 12010 kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
63f42e02 12011
6dba9403
ML
12012 if (update_pdptrs) {
12013 idx = srcu_read_lock(&vcpu->kvm->srcu);
12014 if (is_pae_paging(vcpu)) {
2df4a5eb 12015 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
6dba9403
ML
12016 *mmu_reset_needed = 1;
12017 }
12018 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7c93be44 12019 }
b6c7a5dc 12020
3e6e0aab
GT
12021 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12022 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12023 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12024 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12025 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12026 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 12027
3e6e0aab
GT
12028 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12029 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 12030
5f0269f5
ME
12031 update_cr8_intercept(vcpu);
12032
9c3e4aab 12033 /* Older userspace won't unhalt the vcpu on reset. */
c5af89b6 12034 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9c3e4aab 12035 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3eeb3288 12036 !is_protmode(vcpu))
c9e5f3fa 12037 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
9c3e4aab 12038
6dba9403
ML
12039 return 0;
12040}
12041
12042static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12043{
12044 int pending_vec, max_bits;
12045 int mmu_reset_needed = 0;
12046 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12047
12048 if (ret)
12049 return ret;
12050
4346db6e 12051 if (mmu_reset_needed) {
6dba9403 12052 kvm_mmu_reset_context(vcpu);
4346db6e
ML
12053 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12054 }
6dba9403 12055
5265713a
TL
12056 max_bits = KVM_NR_INTERRUPTS;
12057 pending_vec = find_first_bit(
12058 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6dba9403 12059
5265713a
TL
12060 if (pending_vec < max_bits) {
12061 kvm_queue_interrupt(vcpu, pending_vec, false);
12062 pr_debug("Set back pending irq %d\n", pending_vec);
6dba9403 12063 kvm_make_request(KVM_REQ_EVENT, vcpu);
5265713a 12064 }
6dba9403
ML
12065 return 0;
12066}
5265713a 12067
6dba9403
ML
12068static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12069{
12070 int mmu_reset_needed = 0;
12071 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12072 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12073 !(sregs2->efer & EFER_LMA);
12074 int i, ret;
3842d135 12075
6dba9403
ML
12076 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12077 return -EINVAL;
12078
12079 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12080 return -EINVAL;
12081
12082 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12083 &mmu_reset_needed, !valid_pdptrs);
12084 if (ret)
12085 return ret;
12086
12087 if (valid_pdptrs) {
12088 for (i = 0; i < 4 ; i++)
12089 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12090
12091 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12092 mmu_reset_needed = 1;
158a48ec 12093 vcpu->arch.pdptrs_from_userspace = true;
6dba9403 12094 }
4346db6e 12095 if (mmu_reset_needed) {
6dba9403 12096 kvm_mmu_reset_context(vcpu);
4346db6e
ML
12097 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12098 }
6dba9403 12099 return 0;
01643c51
KH
12100}
12101
12102int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12103 struct kvm_sregs *sregs)
12104{
12105 int ret;
12106
517987e3
PB
12107 if (vcpu->kvm->arch.has_protected_state &&
12108 vcpu->arch.guest_state_protected)
12109 return -EINVAL;
12110
01643c51
KH
12111 vcpu_load(vcpu);
12112 ret = __set_sregs(vcpu, sregs);
b4ef9d4e
CD
12113 vcpu_put(vcpu);
12114 return ret;
b6c7a5dc
HB
12115}
12116
cae72dcc
ML
12117static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12118{
320af55a 12119 bool set = false;
cae72dcc 12120 struct kvm_vcpu *vcpu;
46808a4c 12121 unsigned long i;
cae72dcc 12122
0047fb33
SC
12123 if (!enable_apicv)
12124 return;
12125
cae72dcc
ML
12126 down_write(&kvm->arch.apicv_update_lock);
12127
12128 kvm_for_each_vcpu(i, vcpu, kvm) {
12129 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
320af55a 12130 set = true;
cae72dcc
ML
12131 break;
12132 }
12133 }
320af55a 12134 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
cae72dcc
ML
12135 up_write(&kvm->arch.apicv_update_lock);
12136}
12137
d0bfb940
JK
12138int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12139 struct kvm_guest_debug *dbg)
b6c7a5dc 12140{
355be0b9 12141 unsigned long rflags;
ae675ef0 12142 int i, r;
b6c7a5dc 12143
8d4846b9
TL
12144 if (vcpu->arch.guest_state_protected)
12145 return -EINVAL;
12146
66b56562
CD
12147 vcpu_load(vcpu);
12148
4f926bf2
JK
12149 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12150 r = -EBUSY;
7709aba8 12151 if (kvm_is_exception_pending(vcpu))
2122ff5e 12152 goto out;
4f926bf2
JK
12153 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12154 kvm_queue_exception(vcpu, DB_VECTOR);
12155 else
12156 kvm_queue_exception(vcpu, BP_VECTOR);
12157 }
12158
91586a3b
JK
12159 /*
12160 * Read rflags as long as potentially injected trace flags are still
12161 * filtered out.
12162 */
12163 rflags = kvm_get_rflags(vcpu);
355be0b9
JK
12164
12165 vcpu->guest_debug = dbg->control;
12166 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12167 vcpu->guest_debug = 0;
12168
12169 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
ae675ef0
JK
12170 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12171 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
c8639010 12172 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
ae675ef0
JK
12173 } else {
12174 for (i = 0; i < KVM_NR_DB_REGS; i++)
12175 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
ae675ef0 12176 }
c8639010 12177 kvm_update_dr7(vcpu);
ae675ef0 12178
f92653ee 12179 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
e87e46d5 12180 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
94fe45da 12181
91586a3b
JK
12182 /*
12183 * Trigger an rflags update that will inject or remove the trace
12184 * flags.
12185 */
12186 kvm_set_rflags(vcpu, rflags);
b6c7a5dc 12187
89604647 12188 kvm_x86_call(update_exception_bitmap)(vcpu);
b6c7a5dc 12189
cae72dcc
ML
12190 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12191
4f926bf2 12192 r = 0;
d0bfb940 12193
2122ff5e 12194out:
66b56562 12195 vcpu_put(vcpu);
b6c7a5dc
HB
12196 return r;
12197}
12198
8b006791
ZX
12199/*
12200 * Translate a guest virtual address to a guest physical address.
12201 */
12202int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12203 struct kvm_translation *tr)
12204{
12205 unsigned long vaddr = tr->linear_address;
12206 gpa_t gpa;
f656ce01 12207 int idx;
8b006791 12208
1da5b61d
CD
12209 vcpu_load(vcpu);
12210
f656ce01 12211 idx = srcu_read_lock(&vcpu->kvm->srcu);
1871c602 12212 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
f656ce01 12213 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8b006791 12214 tr->physical_address = gpa;
6e1d2a3f 12215 tr->valid = gpa != INVALID_GPA;
8b006791
ZX
12216 tr->writeable = 1;
12217 tr->usermode = 0;
8b006791 12218
1da5b61d 12219 vcpu_put(vcpu);
8b006791
ZX
12220 return 0;
12221}
12222
d0752060
HB
12223int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12224{
1393123e 12225 struct fxregs_state *fxsave;
d0752060 12226
d69c1382 12227 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
517987e3 12228 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
ed02b213 12229
1393123e 12230 vcpu_load(vcpu);
d0752060 12231
d69c1382 12232 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
d0752060
HB
12233 memcpy(fpu->fpr, fxsave->st_space, 128);
12234 fpu->fcw = fxsave->cwd;
12235 fpu->fsw = fxsave->swd;
12236 fpu->ftwx = fxsave->twd;
12237 fpu->last_opcode = fxsave->fop;
12238 fpu->last_ip = fxsave->rip;
12239 fpu->last_dp = fxsave->rdp;
0e96f31e 12240 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
d0752060 12241
1393123e 12242 vcpu_put(vcpu);
d0752060
HB
12243 return 0;
12244}
12245
12246int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12247{
6a96bc7f
CD
12248 struct fxregs_state *fxsave;
12249
d69c1382 12250 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
517987e3 12251 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
ed02b213 12252
6a96bc7f
CD
12253 vcpu_load(vcpu);
12254
d69c1382 12255 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
d0752060 12256
d0752060
HB
12257 memcpy(fxsave->st_space, fpu->fpr, 128);
12258 fxsave->cwd = fpu->fcw;
12259 fxsave->swd = fpu->fsw;
12260 fxsave->twd = fpu->ftwx;
12261 fxsave->fop = fpu->last_opcode;
12262 fxsave->rip = fpu->last_ip;
12263 fxsave->rdp = fpu->last_dp;
0e96f31e 12264 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
d0752060 12265
6a96bc7f 12266 vcpu_put(vcpu);
d0752060
HB
12267 return 0;
12268}
12269
01643c51
KH
12270static void store_regs(struct kvm_vcpu *vcpu)
12271{
12272 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12273
12274 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12275 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12276
12277 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12278 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12279
12280 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12281 kvm_vcpu_ioctl_x86_get_vcpu_events(
12282 vcpu, &vcpu->run->s.regs.events);
12283}
12284
12285static int sync_regs(struct kvm_vcpu *vcpu)
12286{
01643c51
KH
12287 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12288 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12289 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12290 }
0d033770 12291
01643c51 12292 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
0d033770
ML
12293 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12294
12295 if (__set_sregs(vcpu, &sregs))
01643c51 12296 return -EINVAL;
0d033770 12297
01643c51
KH
12298 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12299 }
0d033770 12300
01643c51 12301 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
0d033770
ML
12302 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12303
12304 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
01643c51 12305 return -EINVAL;
0d033770 12306
01643c51
KH
12307 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12308 }
12309
12310 return 0;
12311}
12312
897cc38e 12313int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
e9b11c17 12314{
1d5e740d 12315 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
8d20bd63 12316 pr_warn_once("SMP vm created on host with unstable TSC; "
897cc38e 12317 "guest TSC will not be reliable\n");
7f1ea208 12318
35875316
ZG
12319 if (!kvm->arch.max_vcpu_ids)
12320 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12321
12322 if (id >= kvm->arch.max_vcpu_ids)
12323 return -EINVAL;
12324
89604647 12325 return kvm_x86_call(vcpu_precreate)(kvm);
e9b11c17
ZX
12326}
12327
e529ef66 12328int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
e9b11c17 12329{
95a0d01e
SC
12330 struct page *page;
12331 int r;
c447e76b 12332
63f5a190 12333 vcpu->arch.last_vmentry_cpu = -1;
7117003f
SC
12334 vcpu->arch.regs_avail = ~0;
12335 vcpu->arch.regs_dirty = ~0;
63f5a190 12336
a4bff3df 12337 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
52491a38 12338
95a0d01e 12339 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
c9e5f3fa 12340 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
95a0d01e 12341 else
c9e5f3fa 12342 kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
c447e76b 12343
95a0d01e
SC
12344 r = kvm_mmu_create(vcpu);
12345 if (r < 0)
12346 return r;
12347
89a58812 12348 r = kvm_create_lapic(vcpu);
a78d9046
SC
12349 if (r < 0)
12350 goto fail_mmu_destroy;
95a0d01e
SC
12351
12352 r = -ENOMEM;
12353
93bb59ca 12354 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
95a0d01e
SC
12355 if (!page)
12356 goto fail_free_lapic;
12357 vcpu->arch.pio_data = page_address(page);
12358
087acc4e 12359 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
95a0d01e 12360 GFP_KERNEL_ACCOUNT);
281b5278
JW
12361 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12362 GFP_KERNEL_ACCOUNT);
12363 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
3c0ba05c 12364 goto fail_free_mce_banks;
95a0d01e
SC
12365 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12366
12367 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12368 GFP_KERNEL_ACCOUNT))
12369 goto fail_free_mce_banks;
12370
c9b8b07c
SC
12371 if (!alloc_emulate_ctxt(vcpu))
12372 goto free_wbinvd_dirty_mask;
12373
d69c1382 12374 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
8d20bd63 12375 pr_err("failed to allocate vcpu's fpu\n");
c9b8b07c 12376 goto free_emulate_ctxt;
95a0d01e
SC
12377 }
12378
95a0d01e 12379 kvm_async_pf_hash_reset(vcpu);
6c6f82be 12380
dcb988cd
SC
12381 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12382 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12383 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12384 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12385 }
95a0d01e
SC
12386 kvm_pmu_init(vcpu);
12387
12388 vcpu->arch.pending_external_vector = -1;
12389 vcpu->arch.preempted_in_kernel = false;
12390
3c86c0d3
VP
12391#if IS_ENABLED(CONFIG_HYPERV)
12392 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12393#endif
12394
89604647 12395 r = kvm_x86_call(vcpu_create)(vcpu);
95a0d01e
SC
12396 if (r)
12397 goto free_guest_fpu;
e9b11c17 12398
942c2490 12399 kvm_xen_init_vcpu(vcpu);
ec7660cc 12400 vcpu_load(vcpu);
85e5ba83 12401 kvm_vcpu_after_set_cpuid(vcpu);
ffbb61d0 12402 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
d28bc9dd 12403 kvm_vcpu_reset(vcpu, false);
c9060662 12404 kvm_init_mmu(vcpu);
e9b11c17 12405 vcpu_put(vcpu);
ec7660cc 12406 return 0;
95a0d01e
SC
12407
12408free_guest_fpu:
d69c1382 12409 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
c9b8b07c
SC
12410free_emulate_ctxt:
12411 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
95a0d01e
SC
12412free_wbinvd_dirty_mask:
12413 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12414fail_free_mce_banks:
12415 kfree(vcpu->arch.mce_banks);
281b5278 12416 kfree(vcpu->arch.mci_ctl2_banks);
95a0d01e
SC
12417 free_page((unsigned long)vcpu->arch.pio_data);
12418fail_free_lapic:
12419 kvm_free_lapic(vcpu);
12420fail_mmu_destroy:
12421 kvm_mmu_destroy(vcpu);
12422 return r;
e9b11c17
ZX
12423}
12424
31928aa5 12425void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
42897d86 12426{
332967a3 12427 struct kvm *kvm = vcpu->kvm;
42897d86 12428
ec7660cc 12429 if (mutex_lock_killable(&vcpu->mutex))
31928aa5 12430 return;
ec7660cc 12431 vcpu_load(vcpu);
bf328e22 12432 kvm_synchronize_tsc(vcpu, NULL);
42897d86 12433 vcpu_put(vcpu);
2d5ba19b
MT
12434
12435 /* poll control enabled by default */
12436 vcpu->arch.msr_kvm_poll_control = 1;
12437
ec7660cc 12438 mutex_unlock(&vcpu->mutex);
42897d86 12439
b34de572
WL
12440 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12441 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12442 KVMCLOCK_SYNC_PERIOD);
42897d86
MT
12443}
12444
d40ccc62 12445void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
e9b11c17 12446{
54a1a24f 12447 int idx, cpu;
344d9588 12448
e4472125
SC
12449 kvm_clear_async_pf_completion_queue(vcpu);
12450 kvm_mmu_unload(vcpu);
12451
50b143e1 12452 kvmclock_reset(vcpu);
e9b11c17 12453
54a1a24f
SC
12454 for_each_possible_cpu(cpu)
12455 cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12456
89604647 12457 kvm_x86_call(vcpu_free)(vcpu);
50b143e1 12458
c9b8b07c 12459 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
50b143e1 12460 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
d69c1382 12461 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
95a0d01e 12462
a795cd43 12463 kvm_xen_destroy_vcpu(vcpu);
95a0d01e
SC
12464 kvm_hv_vcpu_uninit(vcpu);
12465 kvm_pmu_destroy(vcpu);
12466 kfree(vcpu->arch.mce_banks);
281b5278 12467 kfree(vcpu->arch.mci_ctl2_banks);
95a0d01e
SC
12468 kvm_free_lapic(vcpu);
12469 idx = srcu_read_lock(&vcpu->kvm->srcu);
12470 kvm_mmu_destroy(vcpu);
12471 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12472 free_page((unsigned long)vcpu->arch.pio_data);
255cbecf 12473 kvfree(vcpu->arch.cpuid_entries);
e9b11c17
ZX
12474}
12475
d28bc9dd 12476void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
e9b11c17 12477{
25b97845 12478 struct kvm_cpuid_entry2 *cpuid_0x1;
0aa18375 12479 unsigned long old_cr0 = kvm_read_cr0(vcpu);
4c72ab5a 12480 unsigned long new_cr0;
0aa18375 12481
62dd57dd
SC
12482 /*
12483 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12484 * to handle side effects. RESET emulation hits those flows and relies
12485 * on emulated/virtualized registers, including those that are loaded
12486 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12487 * to detect improper or missing initialization.
12488 */
12489 WARN_ON_ONCE(!init_event &&
12490 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
0aa18375 12491
ed129ec9
ML
12492 /*
12493 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12494 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12495 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12496 * bits), i.e. virtualization is disabled.
12497 */
12498 if (is_guest_mode(vcpu))
12499 kvm_leave_nested(vcpu);
12500
b7e31be3
RK
12501 kvm_lapic_reset(vcpu, init_event);
12502
ed129ec9 12503 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
e69fab5d
PB
12504 vcpu->arch.hflags = 0;
12505
c43203ca 12506 vcpu->arch.smi_pending = 0;
52797bf9 12507 vcpu->arch.smi_count = 0;
7460fb4a
AK
12508 atomic_set(&vcpu->arch.nmi_queued, 0);
12509 vcpu->arch.nmi_pending = 0;
448fa4a9 12510 vcpu->arch.nmi_injected = false;
5f7552d4
NA
12511 kvm_clear_interrupt_queue(vcpu);
12512 kvm_clear_exception_queue(vcpu);
448fa4a9 12513
42dbaa5a 12514 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
ae561ede 12515 kvm_update_dr0123(vcpu);
9a3ecd5e 12516 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
42dbaa5a 12517 vcpu->arch.dr7 = DR7_FIXED_1;
c8639010 12518 kvm_update_dr7(vcpu);
42dbaa5a 12519
1119022c
NA
12520 vcpu->arch.cr2 = 0;
12521
3842d135 12522 kvm_make_request(KVM_REQ_EVENT, vcpu);
2635b5c4
VK
12523 vcpu->arch.apf.msr_en_val = 0;
12524 vcpu->arch.apf.msr_int_val = 0;
c9aaa895 12525 vcpu->arch.st.msr_val = 0;
3842d135 12526
12f9a48f
GC
12527 kvmclock_reset(vcpu);
12528
af585b92
GN
12529 kvm_clear_async_pf_completion_queue(vcpu);
12530 kvm_async_pf_hash_reset(vcpu);
12531 vcpu->arch.apf.halted = false;
3842d135 12532
d69c1382
TG
12533 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12534 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
a554d207
WL
12535
12536 /*
a61353ac
SC
12537 * All paths that lead to INIT are required to load the guest's
12538 * FPU state (because most paths are buried in KVM_RUN).
a554d207 12539 */
f775b13e
RR
12540 if (init_event)
12541 kvm_put_guest_fpu(vcpu);
087df48c
TG
12542
12543 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12544 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12545
f775b13e
RR
12546 if (init_event)
12547 kvm_load_guest_fpu(vcpu);
a554d207
WL
12548 }
12549
64d60670 12550 if (!init_event) {
64d60670 12551 vcpu->arch.smbase = 0x30000;
db2336a8 12552
b6717d35
SC
12553 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12554
db2336a8 12555 vcpu->arch.msr_misc_features_enables = 0;
9fc22296
SC
12556 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12557 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
a554d207 12558
05a9e065
LX
12559 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12560 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
64d60670 12561 }
f5132b01 12562
ff8828c8 12563 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
66f7b72e 12564 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
ff8828c8 12565 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
66f7b72e 12566
49d8665c
SC
12567 /*
12568 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12569 * if no CPUID match is found. Note, it's impossible to get a match at
12570 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
25b97845
SC
12571 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12572 * on RESET. But, go through the motions in case that's ever remedied.
49d8665c 12573 */
277ad7d5 12574 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
25b97845 12575 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
49d8665c 12576
89604647 12577 kvm_x86_call(vcpu_reset)(vcpu, init_event);
0aa18375 12578
f39e805e
SC
12579 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12580 kvm_rip_write(vcpu, 0xfff0);
12581
03a6e840
SC
12582 vcpu->arch.cr3 = 0;
12583 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12584
4c72ab5a
SC
12585 /*
12586 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12587 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12588 * (or qualify) that with a footnote stating that CD/NW are preserved.
12589 */
12590 new_cr0 = X86_CR0_ET;
12591 if (init_event)
12592 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12593 else
12594 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12595
89604647
WW
12596 kvm_x86_call(set_cr0)(vcpu, new_cr0);
12597 kvm_x86_call(set_cr4)(vcpu, 0);
12598 kvm_x86_call(set_efer)(vcpu, 0);
12599 kvm_x86_call(update_exception_bitmap)(vcpu);
f39e805e 12600
0aa18375 12601 /*
b5f61c03
PB
12602 * On the standard CR0/CR4/EFER modification paths, there are several
12603 * complex conditions determining whether the MMU has to be reset and/or
12604 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12605 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12606 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12607 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
0aa18375 12608 */
b5f61c03
PB
12609 if (old_cr0 & X86_CR0_PG) {
12610 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
0aa18375 12611 kvm_mmu_reset_context(vcpu);
b5f61c03 12612 }
df37ed38
SC
12613
12614 /*
12615 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12616 * APM states the TLBs are untouched by INIT, but it also states that
12617 * the TLBs are flushed on "External initialization of the processor."
12618 * Flush the guest TLB regardless of vendor, there is no meaningful
12619 * benefit in relying on the guest to flush the TLB immediately after
12620 * INIT. A spurious TLB flush is benign and likely negligible from a
12621 * performance perspective.
12622 */
12623 if (init_event)
12624 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
e9b11c17 12625}
265e4353 12626EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
e9b11c17 12627
2b4a273b 12628void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
66450a21
JK
12629{
12630 struct kvm_segment cs;
12631
12632 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12633 cs.selector = vector << 8;
12634 cs.base = vector << 12;
12635 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12636 kvm_rip_write(vcpu, 0);
e9b11c17 12637}
647daca2 12638EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
e9b11c17 12639
590b09b1
SC
12640void kvm_arch_enable_virtualization(void)
12641{
12642 cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12643}
12644
12645void kvm_arch_disable_virtualization(void)
12646{
12647 cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12648}
12649
071f24ad 12650int kvm_arch_enable_virtualization_cpu(void)
e9b11c17 12651{
ca84d1a2
ZA
12652 struct kvm *kvm;
12653 struct kvm_vcpu *vcpu;
46808a4c 12654 unsigned long i;
0dd6a6ed
ZA
12655 int ret;
12656 u64 local_tsc;
12657 u64 max_tsc = 0;
12658 bool stable, backwards_tsc = false;
18863bdd 12659
7e34fbd0 12660 kvm_user_return_msr_cpu_online();
c82a5c5c
CG
12661
12662 ret = kvm_x86_check_processor_compatibility();
12663 if (ret)
12664 return ret;
12665
0617a769 12666 ret = kvm_x86_call(enable_virtualization_cpu)();
0dd6a6ed
ZA
12667 if (ret != 0)
12668 return ret;
12669
4ea1636b 12670 local_tsc = rdtsc();
b0c39dc6 12671 stable = !kvm_check_tsc_unstable();
0dd6a6ed
ZA
12672 list_for_each_entry(kvm, &vm_list, vm_list) {
12673 kvm_for_each_vcpu(i, vcpu, kvm) {
12674 if (!stable && vcpu->cpu == smp_processor_id())
105b21bb 12675 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
12676 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12677 backwards_tsc = true;
12678 if (vcpu->arch.last_host_tsc > max_tsc)
12679 max_tsc = vcpu->arch.last_host_tsc;
12680 }
12681 }
12682 }
12683
12684 /*
12685 * Sometimes, even reliable TSCs go backwards. This happens on
12686 * platforms that reset TSC during suspend or hibernate actions, but
12687 * maintain synchronization. We must compensate. Fortunately, we can
12688 * detect that condition here, which happens early in CPU bringup,
12689 * before any KVM threads can be running. Unfortunately, we can't
12690 * bring the TSCs fully up to date with real time, as we aren't yet far
12691 * enough into CPU bringup that we know how much real time has actually
9285ec4c 12692 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
0dd6a6ed
ZA
12693 * variables that haven't been updated yet.
12694 *
12695 * So we simply find the maximum observed TSC above, then record the
12696 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
12697 * the adjustment will be applied. Note that we accumulate
12698 * adjustments, in case multiple suspend cycles happen before some VCPU
12699 * gets a chance to run again. In the event that no KVM threads get a
12700 * chance to run, we will miss the entire elapsed period, as we'll have
12701 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12702 * loose cycle time. This isn't too big a deal, since the loss will be
12703 * uniform across all VCPUs (not to mention the scenario is extremely
12704 * unlikely). It is possible that a second hibernate recovery happens
12705 * much faster than a first, causing the observed TSC here to be
12706 * smaller; this would require additional padding adjustment, which is
12707 * why we set last_host_tsc to the local tsc observed here.
12708 *
12709 * N.B. - this code below runs only on platforms with reliable TSC,
12710 * as that is the only way backwards_tsc is set above. Also note
12711 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12712 * have the same delta_cyc adjustment applied if backwards_tsc
12713 * is detected. Note further, this adjustment is only done once,
12714 * as we reset last_host_tsc on all VCPUs to stop this from being
12715 * called multiple times (one for each physical CPU bringup).
12716 *
4a969980 12717 * Platforms with unreliable TSCs don't have to deal with this, they
0dd6a6ed
ZA
12718 * will be compensated by the logic in vcpu_load, which sets the TSC to
12719 * catchup mode. This will catchup all VCPUs to real time, but cannot
12720 * guarantee that they stay in perfect synchronization.
12721 */
12722 if (backwards_tsc) {
12723 u64 delta_cyc = max_tsc - local_tsc;
12724 list_for_each_entry(kvm, &vm_list, vm_list) {
a826faf1 12725 kvm->arch.backwards_tsc_observed = true;
0dd6a6ed
ZA
12726 kvm_for_each_vcpu(i, vcpu, kvm) {
12727 vcpu->arch.tsc_offset_adjustment += delta_cyc;
12728 vcpu->arch.last_host_tsc = local_tsc;
105b21bb 12729 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
12730 }
12731
12732 /*
12733 * We have to disable TSC offset matching.. if you were
12734 * booting a VM while issuing an S4 host suspend....
12735 * you may have some problem. Solving this issue is
12736 * left as an exercise to the reader.
12737 */
12738 kvm->arch.last_tsc_nsec = 0;
12739 kvm->arch.last_tsc_write = 0;
12740 }
12741
12742 }
12743 return 0;
e9b11c17
ZX
12744}
12745
071f24ad 12746void kvm_arch_disable_virtualization_cpu(void)
e9b11c17 12747{
0617a769 12748 kvm_x86_call(disable_virtualization_cpu)();
13a34e06 12749 drop_user_return_notifiers();
e9b11c17
ZX
12750}
12751
d71ba788
PB
12752bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12753{
12754 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12755}
a50f673f 12756EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
d71ba788
PB
12757
12758bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12759{
12760 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
e9b11c17
ZX
12761}
12762
562b6b08
SC
12763void kvm_arch_free_vm(struct kvm *kvm)
12764{
cfef5af3
VK
12765#if IS_ENABLED(CONFIG_HYPERV)
12766 kfree(kvm->arch.hv_pa_pg);
12767#endif
78b497f2 12768 __kvm_arch_free_vm(kvm);
e790d9ef
RK
12769}
12770
562b6b08 12771
e08b9637 12772int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
d19a9cd2 12773{
eb7511bf 12774 int ret;
869b4421 12775 unsigned long flags;
eb7511bf 12776
89ea60c2 12777 if (!kvm_is_vm_type_supported(type))
e08b9637
CO
12778 return -EINVAL;
12779
89ea60c2 12780 kvm->arch.vm_type = type;
517987e3
PB
12781 kvm->arch.has_private_mem =
12782 (type == KVM_X86_SW_PROTECTED_VM);
5932ca41
PB
12783 /* Decided by the vendor code for other VM types. */
12784 kvm->arch.pre_fault_allowed =
12785 type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
bd7d5362 12786 kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
89ea60c2 12787
eb7511bf
HZ
12788 ret = kvm_page_track_init(kvm);
12789 if (ret)
a1a39128
PB
12790 goto out;
12791
0df9dab8 12792 kvm_mmu_init_vm(kvm);
eb7511bf 12793
89604647 12794 ret = kvm_x86_call(vm_init)(kvm);
b24ede22
JS
12795 if (ret)
12796 goto out_uninit_mmu;
12797
6ef768fa 12798 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
e0f0bbc5 12799 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
d19a9cd2 12800
5550af4d
SY
12801 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12802 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7a84428a
AW
12803 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12804 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12805 &kvm->arch.irq_sources_bitmap);
5550af4d 12806
038f8c11 12807 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
1e08ec4a 12808 mutex_init(&kvm->arch.apic_map_lock);
869b4421 12809 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
8171cd68 12810 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
869b4421
PB
12811
12812 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
d828199e 12813 pvclock_update_vm_gtod_copy(kvm);
869b4421 12814 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
53f658b3 12815
741e511b 12816 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
b460256b 12817 kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
6fbbde9a 12818 kvm->arch.guest_can_read_msr_platform_info = true;
ba7bb663 12819 kvm->arch.enable_pmu = enable_pmu;
6fbbde9a 12820
3c86c0d3
VP
12821#if IS_ENABLED(CONFIG_HYPERV)
12822 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12823 kvm->arch.hv_root_tdp = INVALID_PAGE;
12824#endif
12825
7e44e449 12826 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
332967a3 12827 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7e44e449 12828
4651fc56 12829 kvm_apicv_init(kvm);
cbc0236a 12830 kvm_hv_init_vm(kvm);
319afe68 12831 kvm_xen_init_vm(kvm);
0eb05bf2 12832
398b7b6c
PB
12833 if (ignore_msrs && !report_ignored_msrs) {
12834 pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
12835 "a supported configuration. Lying to the guest about the existence of MSRs\n"
12836 "may cause the guest operating system to hang or produce errors. If a guest\n"
12837 "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
12838 }
12839
6f612694 12840 once_init(&kvm->arch.nx_once);
b24ede22 12841 return 0;
a1a39128 12842
b24ede22
JS
12843out_uninit_mmu:
12844 kvm_mmu_uninit_vm(kvm);
a1a39128
PB
12845 kvm_page_track_cleanup(kvm);
12846out:
12847 return ret;
d19a9cd2
ZX
12848}
12849
ff5a983c
PX
12850/**
12851 * __x86_set_memory_region: Setup KVM internal memory slot
12852 *
12853 * @kvm: the kvm pointer to the VM.
12854 * @id: the slot ID to setup.
12855 * @gpa: the GPA to install the slot (unused when @size == 0).
12856 * @size: the size of the slot. Set to zero to uninstall a slot.
12857 *
12858 * This function helps to setup a KVM internal memory slot. Specify
12859 * @size > 0 to install a new slot, while @size == 0 to uninstall a
12860 * slot. The return code can be one of the following:
12861 *
12862 * HVA: on success (uninstall will return a bogus HVA)
12863 * -errno: on error
12864 *
12865 * The caller should always use IS_ERR() to check the return value
12866 * before use. Note, the KVM internal memory slots are guaranteed to
12867 * remain valid and unchanged until the VM is destroyed, i.e., the
12868 * GPA->HVA translation will not change. However, the HVA is a user
12869 * address, i.e. its accessibility is not guaranteed, and must be
12870 * accessed via __copy_{to,from}_user().
12871 */
12872void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12873 u32 size)
9da0e4d5
PB
12874{
12875 int i, r;
3f649ab7 12876 unsigned long hva, old_npages;
f0d648bd 12877 struct kvm_memslots *slots = kvm_memslots(kvm);
0577d1ab 12878 struct kvm_memory_slot *slot;
9da0e4d5 12879
d131f004
SC
12880 lockdep_assert_held(&kvm->slots_lock);
12881
1d8007bd 12882 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
ff5a983c 12883 return ERR_PTR_USR(-EINVAL);
9da0e4d5 12884
f0d648bd
PB
12885 slot = id_to_memslot(slots, id);
12886 if (size) {
0577d1ab 12887 if (slot && slot->npages)
ff5a983c 12888 return ERR_PTR_USR(-EEXIST);
f0d648bd
PB
12889
12890 /*
12891 * MAP_SHARED to prevent internal slot pages from being moved
12892 * by fork()/COW.
12893 */
12894 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12895 MAP_SHARED | MAP_ANONYMOUS, 0);
2eb398df 12896 if (IS_ERR_VALUE(hva))
ff5a983c 12897 return (void __user *)hva;
f0d648bd 12898 } else {
0577d1ab 12899 if (!slot || !slot->npages)
46914534 12900 return NULL;
f0d648bd 12901
0577d1ab 12902 old_npages = slot->npages;
b66f9bab 12903 hva = slot->userspace_addr;
f0d648bd
PB
12904 }
12905
eed52e43 12906 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
bb58b90b 12907 struct kvm_userspace_memory_region2 m;
9da0e4d5 12908
1d8007bd
PB
12909 m.slot = id | (i << 16);
12910 m.flags = 0;
12911 m.guest_phys_addr = gpa;
f0d648bd 12912 m.userspace_addr = hva;
1d8007bd 12913 m.memory_size = size;
156bffdb 12914 r = kvm_set_internal_memslot(kvm, &m);
9da0e4d5 12915 if (r < 0)
ff5a983c 12916 return ERR_PTR_USR(r);
9da0e4d5
PB
12917 }
12918
103c763c 12919 if (!size)
0577d1ab 12920 vm_munmap(hva, old_npages * PAGE_SIZE);
f0d648bd 12921
ff5a983c 12922 return (void __user *)hva;
9da0e4d5
PB
12923}
12924EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12925
1aa9b957
JS
12926void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12927{
fd217326
SC
12928 /*
12929 * Stop all background workers and kthreads before destroying vCPUs, as
12930 * iterating over vCPUs in a different task while vCPUs are being freed
12931 * is unsafe, i.e. will lead to use-after-free. The PIT also needs to
12932 * be stopped before IRQ routing is freed.
12933 */
12934 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12935 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12936
12937 kvm_free_pit(kvm);
12938
1aa9b957 12939 kvm_mmu_pre_destroy_vm(kvm);
8d032b68 12940 static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
1aa9b957
JS
12941}
12942
d19a9cd2
ZX
12943void kvm_arch_destroy_vm(struct kvm *kvm)
12944{
27469d29
AH
12945 if (current->mm == kvm->mm) {
12946 /*
12947 * Free memory regions allocated on behalf of userspace,
f7081834 12948 * unless the memory map has changed due to process exit
27469d29
AH
12949 * or fd copying.
12950 */
6a3c623b
PX
12951 mutex_lock(&kvm->slots_lock);
12952 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12953 0, 0);
12954 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12955 0, 0);
12956 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12957 mutex_unlock(&kvm->slots_lock);
27469d29 12958 }
17bcd714 12959 kvm_destroy_vcpus(kvm);
b318e8de 12960 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
c761159c
PX
12961 kvm_pic_destroy(kvm);
12962 kvm_ioapic_destroy(kvm);
af1bae54 12963 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
66bb8a06 12964 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13d268ca 12965 kvm_mmu_uninit_vm(kvm);
2beb6dad 12966 kvm_page_track_cleanup(kvm);
7d6bbebb 12967 kvm_xen_destroy_vm(kvm);
cbc0236a 12968 kvm_hv_destroy_vm(kvm);
46c49372 12969 kvm_x86_call(vm_destroy)(kvm);
d19a9cd2 12970}
0de10343 12971
c9b929b3 12972static void memslot_rmap_free(struct kvm_memory_slot *slot)
db3fe4eb
TY
12973{
12974 int i;
12975
d89cc617 12976 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
a952d608 12977 vfree(slot->arch.rmap[i]);
e96c81ee 12978 slot->arch.rmap[i] = NULL;
c9b929b3
BG
12979 }
12980}
e96c81ee 12981
c9b929b3
BG
12982void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12983{
12984 int i;
12985
12986 memslot_rmap_free(slot);
d89cc617 12987
c9b929b3 12988 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
a952d608 12989 vfree(slot->arch.lpage_info[i - 1]);
e96c81ee 12990 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb 12991 }
21ebbeda 12992
e96c81ee 12993 kvm_page_track_free_memslot(slot);
db3fe4eb
TY
12994}
12995
1e76a3ce 12996int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
56dd1019
BG
12997{
12998 const int sz = sizeof(*slot->arch.rmap[0]);
12999 int i;
13000
13001 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13002 int level = i + 1;
4139b197 13003 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
56dd1019 13004
fa13843d
PB
13005 if (slot->arch.rmap[i])
13006 continue;
d501f747 13007
37b2a651 13008 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
56dd1019
BG
13009 if (!slot->arch.rmap[i]) {
13010 memslot_rmap_free(slot);
13011 return -ENOMEM;
13012 }
13013 }
13014
13015 return 0;
13016}
13017
a2557408 13018static int kvm_alloc_memslot_metadata(struct kvm *kvm,
9d7d18ee 13019 struct kvm_memory_slot *slot)
db3fe4eb 13020{
9d7d18ee 13021 unsigned long npages = slot->npages;
56dd1019 13022 int i, r;
db3fe4eb 13023
edd4fa37
SC
13024 /*
13025 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
344315e9 13026 * old arrays will be freed by kvm_set_memory_region() if installing
edd4fa37
SC
13027 * the new memslot is successful.
13028 */
13029 memset(&slot->arch, 0, sizeof(slot->arch));
13030
e2209710 13031 if (kvm_memslots_have_rmaps(kvm)) {
a2557408
BG
13032 r = memslot_rmap_alloc(slot, npages);
13033 if (r)
13034 return r;
13035 }
56dd1019
BG
13036
13037 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
92f94f1e 13038 struct kvm_lpage_info *linfo;
db3fe4eb
TY
13039 unsigned long ugfn;
13040 int lpages;
d89cc617 13041 int level = i + 1;
db3fe4eb 13042
4139b197 13043 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
db3fe4eb 13044
37b2a651 13045 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
92f94f1e 13046 if (!linfo)
db3fe4eb
TY
13047 goto out_free;
13048
92f94f1e
XG
13049 slot->arch.lpage_info[i - 1] = linfo;
13050
db3fe4eb 13051 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 13052 linfo[0].disallow_lpage = 1;
db3fe4eb 13053 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 13054 linfo[lpages - 1].disallow_lpage = 1;
db3fe4eb
TY
13055 ugfn = slot->userspace_addr >> PAGE_SHIFT;
13056 /*
13057 * If the gfn and userspace address are not aligned wrt each
600087b6 13058 * other, disable large page support for this slot.
db3fe4eb 13059 */
600087b6 13060 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
db3fe4eb
TY
13061 unsigned long j;
13062
13063 for (j = 0; j < lpages; ++j)
92f94f1e 13064 linfo[j].disallow_lpage = 1;
db3fe4eb
TY
13065 }
13066 }
13067
90b4fe17
CP
13068#ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13069 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13070#endif
13071
deae4a10 13072 if (kvm_page_track_create_memslot(kvm, slot, npages))
21ebbeda
XG
13073 goto out_free;
13074
db3fe4eb
TY
13075 return 0;
13076
13077out_free:
c9b929b3 13078 memslot_rmap_free(slot);
d89cc617 13079
c9b929b3 13080 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
a952d608 13081 vfree(slot->arch.lpage_info[i - 1]);
d89cc617 13082 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb
TY
13083 }
13084 return -ENOMEM;
13085}
13086
15248258 13087void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
e59dbe09 13088{
91724814 13089 struct kvm_vcpu *vcpu;
46808a4c 13090 unsigned long i;
91724814 13091
e6dff7d1
TY
13092 /*
13093 * memslots->generation has been incremented.
13094 * mmio generation may have reached its maximum value.
13095 */
15248258 13096 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
91724814
BO
13097
13098 /* Force re-initialization of steal_time cache */
13099 kvm_for_each_vcpu(i, vcpu, kvm)
13100 kvm_vcpu_kick(vcpu);
e59dbe09
TY
13101}
13102
f7784b8e 13103int kvm_arch_prepare_memory_region(struct kvm *kvm,
537a17b3
SC
13104 const struct kvm_memory_slot *old,
13105 struct kvm_memory_slot *new,
13106 enum kvm_mr_change change)
0de10343 13107{
c70934e0
SC
13108 /*
13109 * KVM doesn't support moving memslots when there are external page
13110 * trackers attached to the VM, i.e. if KVMGT is in use.
13111 */
13112 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13113 return -EINVAL;
13114
86931ff7
SC
13115 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13116 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13117 return -EINVAL;
13118
2c3412e9
RE
13119 if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13120 return -EINVAL;
13121
9d7d18ee 13122 return kvm_alloc_memslot_metadata(kvm, new);
86931ff7 13123 }
537a17b3
SC
13124
13125 if (change == KVM_MR_FLAGS_ONLY)
13126 memcpy(&new->arch, &old->arch, sizeof(old->arch));
13127 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13128 return -EIO;
13129
f7784b8e
MT
13130 return 0;
13131}
13132
a85863c2
MS
13133
13134static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13135{
ee661d8e 13136 int nr_slots;
a85863c2 13137
fbb4adad 13138 if (!kvm->arch.cpu_dirty_log_size)
a85863c2
MS
13139 return;
13140
ee661d8e
DM
13141 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13142 if ((enable && nr_slots == 1) || !nr_slots)
a85863c2 13143 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
a85863c2
MS
13144}
13145
88178fd4 13146static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
3741679b 13147 struct kvm_memory_slot *old,
269e9552 13148 const struct kvm_memory_slot *new,
3741679b 13149 enum kvm_mr_change change)
88178fd4 13150{
77aedf26
SC
13151 u32 old_flags = old ? old->flags : 0;
13152 u32 new_flags = new ? new->flags : 0;
13153 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
a85863c2 13154
3741679b 13155 /*
a85863c2
MS
13156 * Update CPU dirty logging if dirty logging is being toggled. This
13157 * applies to all operations.
3741679b 13158 */
77aedf26 13159 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
a85863c2 13160 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
88178fd4
KH
13161
13162 /*
a85863c2 13163 * Nothing more to do for RO slots (which can't be dirtied and can't be
b6e16ae5 13164 * made writable) or CREATE/MOVE/DELETE of a slot.
88178fd4 13165 *
b6e16ae5 13166 * For a memslot with dirty logging disabled:
3741679b
AY
13167 * CREATE: No dirty mappings will already exist.
13168 * MOVE/DELETE: The old mappings will already have been cleaned up by
13169 * kvm_arch_flush_shadow_memslot()
b6e16ae5
SC
13170 *
13171 * For a memslot with dirty logging enabled:
13172 * CREATE: No shadow pages exist, thus nothing to write-protect
13173 * and no dirty bits to clear.
13174 * MOVE/DELETE: The old mappings will already have been cleaned up by
13175 * kvm_arch_flush_shadow_memslot().
3741679b 13176 */
77aedf26 13177 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
88178fd4 13178 return;
3741679b
AY
13179
13180 /*
52f46079
SC
13181 * READONLY and non-flags changes were filtered out above, and the only
13182 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13183 * logging isn't being toggled on or off.
88178fd4 13184 */
77aedf26 13185 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
52f46079
SC
13186 return;
13187
b6e16ae5
SC
13188 if (!log_dirty_pages) {
13189 /*
13e2e4f6
DM
13190 * Recover huge page mappings in the slot now that dirty logging
13191 * is disabled, i.e. now that KVM does not have to track guest
13192 * writes at 4KiB granularity.
b6e16ae5 13193 *
13e2e4f6
DM
13194 * Dirty logging might be disabled by userspace if an ongoing VM
13195 * live migration is cancelled and the VM must continue running
13196 * on the source.
b6e16ae5 13197 */
13e2e4f6 13198 kvm_mmu_recover_huge_pages(kvm, new);
b6e16ae5 13199 } else {
89212919
KZ
13200 /*
13201 * Initially-all-set does not require write protecting any page,
13202 * because they're all assumed to be dirty.
13203 */
13204 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13205 return;
a1419f8b 13206
a3fe5dbd
DM
13207 if (READ_ONCE(eager_page_split))
13208 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13209
fbb4adad 13210 if (kvm->arch.cpu_dirty_log_size) {
89212919
KZ
13211 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13212 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13213 } else {
13214 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
3c9bd400 13215 }
b64d740e
JS
13216
13217 /*
13218 * Unconditionally flush the TLBs after enabling dirty logging.
13219 * A flush is almost always going to be necessary (see below),
13220 * and unconditionally flushing allows the helpers to omit
13221 * the subtly complex checks when removing write access.
13222 *
13223 * Do the flush outside of mmu_lock to reduce the amount of
13224 * time mmu_lock is held. Flushing after dropping mmu_lock is
13225 * safe as KVM only needs to guarantee the slot is fully
13226 * write-protected before returning to userspace, i.e. before
13227 * userspace can consume the dirty status.
13228 *
13229 * Flushing outside of mmu_lock requires KVM to be careful when
13230 * making decisions based on writable status of an SPTE, e.g. a
13231 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13232 *
13233 * Specifically, KVM also write-protects guest page tables to
13234 * monitor changes when using shadow paging, and must guarantee
13235 * no CPUs can write to those page before mmu_lock is dropped.
13236 * Because CPUs may have stale TLB entries at this point, a
13237 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13238 *
13239 * KVM also allows making SPTES writable outside of mmu_lock,
13240 * e.g. to allow dirty logging without taking mmu_lock.
13241 *
13242 * To handle these scenarios, KVM uses a separate software-only
13243 * bit (MMU-writable) to track if a SPTE is !writable due to
13244 * a guest page table being write-protected (KVM clears the
13245 * MMU-writable flag when write-protecting for shadow paging).
13246 *
13247 * The use of MMU-writable is also the primary motivation for
13248 * the unconditional flush. Because KVM must guarantee that a
13249 * CPU doesn't contain stale, writable TLB entries for a
13250 * !MMU-writable SPTE, KVM must flush if it encounters any
13251 * MMU-writable SPTE regardless of whether the actual hardware
13252 * writable bit was set. I.e. KVM is almost guaranteed to need
13253 * to flush, while unconditionally flushing allows the "remove
13254 * write access" helpers to ignore MMU-writable entirely.
13255 *
13256 * See is_writable_pte() for more details (the case involving
13257 * access-tracked SPTEs is particularly relevant).
13258 */
619b5072 13259 kvm_flush_remote_tlbs_memslot(kvm, new);
88178fd4
KH
13260 }
13261}
13262
f7784b8e 13263void kvm_arch_commit_memory_region(struct kvm *kvm,
9d4c197c 13264 struct kvm_memory_slot *old,
f36f3f28 13265 const struct kvm_memory_slot *new,
8482644a 13266 enum kvm_mr_change change)
f7784b8e 13267{
b83ab124
YZ
13268 if (change == KVM_MR_DELETE)
13269 kvm_page_track_delete_slot(kvm, old);
13270
e0c2b633 13271 if (!kvm->arch.n_requested_mmu_pages &&
f5756029
MS
13272 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13273 unsigned long nr_mmu_pages;
13274
13275 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13276 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13277 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13278 }
1c91cad4 13279
269e9552 13280 kvm_mmu_slot_apply_flags(kvm, old, new, change);
21198846
SC
13281
13282 /* Free the arrays associated with the old memslot. */
13283 if (change == KVM_MR_MOVE)
e96c81ee 13284 kvm_arch_free_memslot(kvm, old);
0de10343 13285}
1d737c8a 13286
199b5763
LM
13287bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13288{
eecf3985
SC
13289 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13290
b86bb11e
WL
13291 if (vcpu->arch.guest_state_protected)
13292 return true;
13293
89604647 13294 return kvm_x86_call(get_cpl)(vcpu) == 0;
199b5763
LM
13295}
13296
e1bfc245
SC
13297unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13298{
eecf3985
SC
13299 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13300
13301 if (vcpu->arch.guest_state_protected)
13302 return 0;
13303
e1bfc245
SC
13304 return kvm_rip_read(vcpu);
13305}
13306
b6d33834 13307int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
5736199a 13308{
b6d33834 13309 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
5736199a 13310}
78646121
GN
13311
13312int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13313{
89604647 13314 return kvm_x86_call(interrupt_allowed)(vcpu, false);
78646121 13315}
229456fc 13316
82b32774 13317unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
f92653ee 13318{
7ed9abfe
TL
13319 /* Can't read the RIP when guest state is protected, just return 0 */
13320 if (vcpu->arch.guest_state_protected)
13321 return 0;
13322
82b32774
NA
13323 if (is_64_bit_mode(vcpu))
13324 return kvm_rip_read(vcpu);
13325 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13326 kvm_rip_read(vcpu));
13327}
13328EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
f92653ee 13329
82b32774
NA
13330bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13331{
13332 return kvm_get_linear_rip(vcpu) == linear_rip;
f92653ee
JK
13333}
13334EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13335
94fe45da
JK
13336unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13337{
13338 unsigned long rflags;
13339
89604647 13340 rflags = kvm_x86_call(get_rflags)(vcpu);
94fe45da 13341 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
c310bac5 13342 rflags &= ~X86_EFLAGS_TF;
94fe45da
JK
13343 return rflags;
13344}
13345EXPORT_SYMBOL_GPL(kvm_get_rflags);
13346
6addfc42 13347static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
94fe45da
JK
13348{
13349 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
f92653ee 13350 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
c310bac5 13351 rflags |= X86_EFLAGS_TF;
89604647 13352 kvm_x86_call(set_rflags)(vcpu, rflags);
6addfc42
PB
13353}
13354
13355void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13356{
13357 __kvm_set_rflags(vcpu, rflags);
3842d135 13358 kvm_make_request(KVM_REQ_EVENT, vcpu);
94fe45da
JK
13359}
13360EXPORT_SYMBOL_GPL(kvm_set_rflags);
13361
af585b92
GN
13362static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13363{
dd03bcaa
PX
13364 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13365
af585b92
GN
13366 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13367}
13368
13369static inline u32 kvm_async_pf_next_probe(u32 key)
13370{
dd03bcaa 13371 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
af585b92
GN
13372}
13373
13374static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13375{
13376 u32 key = kvm_async_pf_hash_fn(gfn);
13377
13378 while (vcpu->arch.apf.gfns[key] != ~0)
13379 key = kvm_async_pf_next_probe(key);
13380
13381 vcpu->arch.apf.gfns[key] = gfn;
13382}
13383
13384static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13385{
13386 int i;
13387 u32 key = kvm_async_pf_hash_fn(gfn);
13388
dd03bcaa 13389 for (i = 0; i < ASYNC_PF_PER_VCPU &&
c7d28c24
XG
13390 (vcpu->arch.apf.gfns[key] != gfn &&
13391 vcpu->arch.apf.gfns[key] != ~0); i++)
af585b92
GN
13392 key = kvm_async_pf_next_probe(key);
13393
13394 return key;
13395}
13396
13397bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13398{
13399 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13400}
13401
13402static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13403{
13404 u32 i, j, k;
13405
13406 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
0fd46044
PX
13407
13408 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13409 return;
13410
af585b92
GN
13411 while (true) {
13412 vcpu->arch.apf.gfns[i] = ~0;
13413 do {
13414 j = kvm_async_pf_next_probe(j);
13415 if (vcpu->arch.apf.gfns[j] == ~0)
13416 return;
13417 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13418 /*
13419 * k lies cyclically in ]i,j]
13420 * | i.k.j |
13421 * |....j i.k.| or |.k..j i...|
13422 */
13423 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13424 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13425 i = j;
13426 }
13427}
13428
68fd66f1 13429static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
7c90705b 13430{
68fd66f1
VK
13431 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13432
13433 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13434 sizeof(reason));
13435}
13436
13437static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13438{
2635b5c4 13439 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
4e335d9e 13440
2635b5c4
VK
13441 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13442 &token, offset, sizeof(token));
13443}
13444
13445static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13446{
13447 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13448 u32 val;
13449
13450 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13451 &val, offset, sizeof(val)))
13452 return false;
13453
13454 return !val;
7c90705b
GN
13455}
13456
1dfdb45e
PB
13457static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13458{
57cb3bb0
PB
13459
13460 if (!kvm_pv_async_pf_enabled(vcpu))
1dfdb45e
PB
13461 return false;
13462
4fa0efb4 13463 if (!vcpu->arch.apf.send_always &&
b9595d1d 13464 (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
1dfdb45e
PB
13465 return false;
13466
57cb3bb0
PB
13467 if (is_guest_mode(vcpu)) {
13468 /*
13469 * L1 needs to opt into the special #PF vmexits that are
13470 * used to deliver async page faults.
13471 */
13472 return vcpu->arch.apf.delivery_as_pf_vmexit;
13473 } else {
13474 /*
13475 * Play it safe in case the guest temporarily disables paging.
13476 * The real mode IDT in particular is unlikely to have a #PF
13477 * exception setup.
13478 */
13479 return is_paging(vcpu);
13480 }
1dfdb45e
PB
13481}
13482
13483bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13484{
13485 if (unlikely(!lapic_in_kernel(vcpu) ||
13486 kvm_event_needs_reinjection(vcpu) ||
7709aba8 13487 kvm_is_exception_pending(vcpu)))
1dfdb45e
PB
13488 return false;
13489
13490 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13491 return false;
13492
13493 /*
13494 * If interrupts are off we cannot even use an artificial
13495 * halt state.
13496 */
c300ab9f 13497 return kvm_arch_interrupt_allowed(vcpu);
1dfdb45e
PB
13498}
13499
2a18b7e7 13500bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
af585b92
GN
13501 struct kvm_async_pf *work)
13502{
6389ee94
AK
13503 struct x86_exception fault;
13504
736c291c 13505 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
af585b92 13506 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7c90705b 13507
1dfdb45e 13508 if (kvm_can_deliver_async_pf(vcpu) &&
68fd66f1 13509 !apf_put_user_notpresent(vcpu)) {
6389ee94
AK
13510 fault.vector = PF_VECTOR;
13511 fault.error_code_valid = true;
13512 fault.error_code = 0;
13513 fault.nested_page_fault = false;
13514 fault.address = work->arch.token;
adfe20fb 13515 fault.async_page_fault = true;
6389ee94 13516 kvm_inject_page_fault(vcpu, &fault);
2a18b7e7 13517 return true;
1dfdb45e
PB
13518 } else {
13519 /*
13520 * It is not possible to deliver a paravirtualized asynchronous
13521 * page fault, but putting the guest in an artificial halt state
13522 * can be beneficial nevertheless: if an interrupt arrives, we
13523 * can deliver it timely and perhaps the guest will schedule
13524 * another process. When the instruction that triggered a page
13525 * fault is retried, hopefully the page will be ready in the host.
13526 */
13527 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
2a18b7e7 13528 return false;
7c90705b 13529 }
af585b92
GN
13530}
13531
13532void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13533 struct kvm_async_pf *work)
13534{
2635b5c4
VK
13535 struct kvm_lapic_irq irq = {
13536 .delivery_mode = APIC_DM_FIXED,
13537 .vector = vcpu->arch.apf.vec
13538 };
6389ee94 13539
f2e10669 13540 if (work->wakeup_all)
7c90705b
GN
13541 work->arch.token = ~0; /* broadcast wakeup */
13542 else
13543 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
736c291c 13544 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
7c90705b 13545
2a18b7e7
VK
13546 if ((work->wakeup_all || work->notpresent_injected) &&
13547 kvm_pv_async_pf_enabled(vcpu) &&
557a961a
VK
13548 !apf_put_user_ready(vcpu, work->arch.token)) {
13549 vcpu->arch.apf.pageready_pending = true;
2635b5c4 13550 kvm_apic_set_irq(vcpu, &irq, NULL);
557a961a 13551 }
2635b5c4 13552
e6d53e3b 13553 vcpu->arch.apf.halted = false;
c9e5f3fa 13554 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
7c90705b
GN
13555}
13556
557a961a
VK
13557void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13558{
13559 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13560 if (!vcpu->arch.apf.pageready_pending)
13561 kvm_vcpu_kick(vcpu);
13562}
13563
7c0ade6c 13564bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
7c90705b 13565{
2635b5c4 13566 if (!kvm_pv_async_pf_enabled(vcpu))
7c90705b
GN
13567 return true;
13568 else
2f15d027 13569 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
af585b92
GN
13570}
13571
5544eb9b
PB
13572void kvm_arch_start_assignment(struct kvm *kvm)
13573{
57ab8794 13574 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
89604647 13575 kvm_x86_call(pi_start_assignment)(kvm);
5544eb9b
PB
13576}
13577EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13578
13579void kvm_arch_end_assignment(struct kvm *kvm)
13580{
13581 atomic_dec(&kvm->arch.assigned_device_count);
13582}
13583EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13584
742ab6df 13585bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
5544eb9b 13586{
0f613bfa 13587 return raw_atomic_read(&kvm->arch.assigned_device_count);
5544eb9b
PB
13588}
13589EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13590
362ff6dc
YZ
13591static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13592{
13593 /*
0a7b7355
SC
13594 * Non-coherent DMA assignment and de-assignment may affect whether or
13595 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13596 * due to toggling the "ignore PAT" bit. Zap all SPTEs when the first
13597 * (or last) non-coherent device is (un)registered to so that new SPTEs
13598 * with the correct "ignore guest PAT" setting are created.
3fee4837
PB
13599 *
13600 * If KVM always honors guest PAT, however, there is nothing to do.
362ff6dc 13601 */
3fee4837 13602 if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
362ff6dc
YZ
13603 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13604}
13605
e0f0bbc5
AW
13606void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13607{
362ff6dc
YZ
13608 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13609 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
e0f0bbc5
AW
13610}
13611EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13612
13613void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13614{
362ff6dc
YZ
13615 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13616 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
e0f0bbc5
AW
13617}
13618EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13619
13620bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13621{
13622 return atomic_read(&kvm->arch.noncoherent_dma_count);
13623}
13624EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13625
87276880
FW
13626int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13627 struct irq_bypass_producer *prod)
13628{
13629 struct kvm_kernel_irqfd *irqfd =
13630 container_of(cons, struct kvm_kernel_irqfd, consumer);
f1fb088d 13631 struct kvm *kvm = irqfd->kvm;
2edd9cb7 13632 int ret;
87276880 13633
2edd9cb7 13634 kvm_arch_start_assignment(irqfd->kvm);
f1fb088d
SC
13635
13636 spin_lock_irq(&kvm->irqfds.lock);
13637 irqfd->producer = prod;
13638
89604647
WW
13639 ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13640 prod->irq, irqfd->gsi, 1);
2edd9cb7
ZL
13641 if (ret)
13642 kvm_arch_end_assignment(irqfd->kvm);
87276880 13643
f1fb088d
SC
13644 spin_unlock_irq(&kvm->irqfds.lock);
13645
13646
2edd9cb7 13647 return ret;
87276880
FW
13648}
13649
13650void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13651 struct irq_bypass_producer *prod)
13652{
13653 int ret;
13654 struct kvm_kernel_irqfd *irqfd =
13655 container_of(cons, struct kvm_kernel_irqfd, consumer);
f1fb088d 13656 struct kvm *kvm = irqfd->kvm;
87276880 13657
87276880 13658 WARN_ON(irqfd->producer != prod);
87276880
FW
13659
13660 /*
13661 * When producer of consumer is unregistered, we change back to
13662 * remapped mode, so we can re-use the current implementation
bb3541f1 13663 * when the irq is masked/disabled or the consumer side (KVM
87276880
FW
13664 * int this case doesn't want to receive the interrupts.
13665 */
f1fb088d
SC
13666 spin_lock_irq(&kvm->irqfds.lock);
13667 irqfd->producer = NULL;
13668
89604647
WW
13669 ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13670 prod->irq, irqfd->gsi, 0);
87276880
FW
13671 if (ret)
13672 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13673 " fails: %d\n", irqfd->consumer.token, ret);
2edd9cb7 13674
f1fb088d
SC
13675 spin_unlock_irq(&kvm->irqfds.lock);
13676
13677
2edd9cb7 13678 kvm_arch_end_assignment(irqfd->kvm);
87276880
FW
13679}
13680
13681int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13682 uint32_t guest_irq, bool set)
13683{
89604647 13684 return kvm_x86_call(pi_update_irte)(kvm, host_irq, guest_irq, set);
87276880
FW
13685}
13686
515a0c79
LM
13687bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13688 struct kvm_kernel_irq_routing_entry *new)
13689{
bcda70c5
SC
13690 if (old->type != KVM_IRQ_ROUTING_MSI ||
13691 new->type != KVM_IRQ_ROUTING_MSI)
515a0c79
LM
13692 return true;
13693
13694 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13695}
13696
52004014
FW
13697bool kvm_vector_hashing_enabled(void)
13698{
13699 return vector_hashing;
13700}
52004014 13701
2d5ba19b
MT
13702bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13703{
13704 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13705}
13706EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13707
564429a6 13708#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
3bb2531e
PB
13709int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13710{
89604647 13711 return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
3bb2531e
PB
13712}
13713#endif
841c2be0 13714
564429a6 13715#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
a90764f0
MR
13716void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13717{
89604647 13718 kvm_x86_call(gmem_invalidate)(start, end);
a90764f0
MR
13719}
13720#endif
841c2be0
ML
13721
13722int kvm_spec_ctrl_test_value(u64 value)
6441fa61 13723{
841c2be0
ML
13724 /*
13725 * test that setting IA32_SPEC_CTRL to given value
13726 * is allowed by the host processor
13727 */
6441fa61 13728
841c2be0
ML
13729 u64 saved_value;
13730 unsigned long flags;
13731 int ret = 0;
6441fa61 13732
841c2be0 13733 local_irq_save(flags);
6441fa61 13734
6fe22aba 13735 if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
841c2be0 13736 ret = 1;
6fa17efe 13737 else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
841c2be0
ML
13738 ret = 1;
13739 else
78255eb2 13740 wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
6441fa61 13741
841c2be0 13742 local_irq_restore(flags);
6441fa61 13743
841c2be0 13744 return ret;
6441fa61 13745}
841c2be0 13746EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
2d5ba19b 13747
89786147
MG
13748void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13749{
1f5a21ee 13750 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
89786147 13751 struct x86_exception fault;
5b22bbe7 13752 u64 access = error_code &
19cf4b7e 13753 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
89786147
MG
13754
13755 if (!(error_code & PFERR_PRESENT_MASK) ||
6e1d2a3f 13756 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
89786147
MG
13757 /*
13758 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13759 * tables probably do not match the TLB. Just proceed
13760 * with the error code that the processor gave.
13761 */
13762 fault.vector = PF_VECTOR;
13763 fault.error_code_valid = true;
13764 fault.error_code = error_code;
13765 fault.nested_page_fault = false;
13766 fault.address = gva;
2bc685e6 13767 fault.async_page_fault = false;
89786147
MG
13768 }
13769 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
6441fa61 13770}
89786147 13771EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
2d5ba19b 13772
3f3393b3
BM
13773/*
13774 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13775 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13776 * indicates whether exit to userspace is needed.
13777 */
13778int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13779 struct x86_exception *e)
13780{
13781 if (r == X86EMUL_PROPAGATE_FAULT) {
77b1908e
SC
13782 if (KVM_BUG_ON(!e, vcpu->kvm))
13783 return -EIO;
13784
3f3393b3
BM
13785 kvm_inject_emulated_page_fault(vcpu, e);
13786 return 1;
13787 }
13788
13789 /*
13790 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13791 * while handling a VMX instruction KVM could've handled the request
13792 * correctly by exiting to userspace and performing I/O but there
13793 * doesn't seem to be a real use-case behind such requests, just return
13794 * KVM_EXIT_INTERNAL_ERROR for now.
13795 */
e615e355 13796 kvm_prepare_emulation_failure_exit(vcpu);
3f3393b3
BM
13797
13798 return 0;
13799}
13800EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13801
9715092f
BM
13802int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13803{
13804 bool pcid_enabled;
13805 struct x86_exception e;
9715092f
BM
13806 struct {
13807 u64 pcid;
13808 u64 gla;
13809 } operand;
13810 int r;
13811
13812 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13813 if (r != X86EMUL_CONTINUE)
13814 return kvm_handle_memory_failure(vcpu, r, &e);
13815
13816 if (operand.pcid >> 12 != 0) {
13817 kvm_inject_gp(vcpu, 0);
13818 return 1;
13819 }
13820
607475cf 13821 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
9715092f
BM
13822
13823 switch (type) {
13824 case INVPCID_TYPE_INDIV_ADDR:
b39bd520
BW
13825 /*
13826 * LAM doesn't apply to addresses that are inputs to TLB
13827 * invalidation.
13828 */
9715092f 13829 if ((!pcid_enabled && (operand.pcid != 0)) ||
9245fd6b 13830 is_noncanonical_invlpg_address(operand.gla, vcpu)) {
9715092f
BM
13831 kvm_inject_gp(vcpu, 0);
13832 return 1;
13833 }
13834 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13835 return kvm_skip_emulated_instruction(vcpu);
13836
13837 case INVPCID_TYPE_SINGLE_CTXT:
13838 if (!pcid_enabled && (operand.pcid != 0)) {
13839 kvm_inject_gp(vcpu, 0);
13840 return 1;
13841 }
13842
21823fbd 13843 kvm_invalidate_pcid(vcpu, operand.pcid);
9715092f
BM
13844 return kvm_skip_emulated_instruction(vcpu);
13845
13846 case INVPCID_TYPE_ALL_NON_GLOBAL:
13847 /*
13848 * Currently, KVM doesn't mark global entries in the shadow
13849 * page tables, so a non-global flush just degenerates to a
13850 * global flush. If needed, we could optimize this later by
13851 * keeping track of global entries in shadow page tables.
13852 */
13853
13854 fallthrough;
13855 case INVPCID_TYPE_ALL_INCL_GLOBAL:
28f28d45 13856 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
9715092f
BM
13857 return kvm_skip_emulated_instruction(vcpu);
13858
13859 default:
796c83c5
VS
13860 kvm_inject_gp(vcpu, 0);
13861 return 1;
9715092f
BM
13862 }
13863}
13864EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13865
8f423a80
TL
13866static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13867{
13868 struct kvm_run *run = vcpu->run;
13869 struct kvm_mmio_fragment *frag;
13870 unsigned int len;
13871
13872 BUG_ON(!vcpu->mmio_needed);
13873
13874 /* Complete previous fragment */
13875 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13876 len = min(8u, frag->len);
13877 if (!vcpu->mmio_is_write)
13878 memcpy(frag->data, run->mmio.data, len);
13879
13880 if (frag->len <= 8) {
13881 /* Switch to the next fragment. */
13882 frag++;
13883 vcpu->mmio_cur_fragment++;
13884 } else {
13885 /* Go forward to the next mmio piece. */
13886 frag->data += len;
13887 frag->gpa += len;
13888 frag->len -= len;
13889 }
13890
13891 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13892 vcpu->mmio_needed = 0;
13893
13894 // VMG change, at this point, we're always done
13895 // RIP has already been advanced
13896 return 1;
13897 }
13898
13899 // More MMIO is needed
13900 run->mmio.phys_addr = frag->gpa;
13901 run->mmio.len = min(8u, frag->len);
13902 run->mmio.is_write = vcpu->mmio_is_write;
13903 if (run->mmio.is_write)
13904 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13905 run->exit_reason = KVM_EXIT_MMIO;
13906
13907 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13908
13909 return 0;
13910}
13911
13912int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13913 void *data)
13914{
13915 int handled;
13916 struct kvm_mmio_fragment *frag;
13917
13918 if (!data)
13919 return -EINVAL;
13920
13921 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13922 if (handled == bytes)
13923 return 1;
13924
13925 bytes -= handled;
13926 gpa += handled;
13927 data += handled;
13928
13929 /*TODO: Check if need to increment number of frags */
13930 frag = vcpu->mmio_fragments;
13931 vcpu->mmio_nr_fragments = 1;
13932 frag->len = bytes;
13933 frag->gpa = gpa;
13934 frag->data = data;
13935
13936 vcpu->mmio_needed = 1;
13937 vcpu->mmio_cur_fragment = 0;
13938
13939 vcpu->run->mmio.phys_addr = gpa;
13940 vcpu->run->mmio.len = min(8u, frag->len);
13941 vcpu->run->mmio.is_write = 1;
13942 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13943 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13944
13945 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13946
13947 return 0;
13948}
13949EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13950
13951int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13952 void *data)
13953{
13954 int handled;
13955 struct kvm_mmio_fragment *frag;
13956
13957 if (!data)
13958 return -EINVAL;
13959
13960 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13961 if (handled == bytes)
13962 return 1;
13963
13964 bytes -= handled;
13965 gpa += handled;
13966 data += handled;
13967
13968 /*TODO: Check if need to increment number of frags */
13969 frag = vcpu->mmio_fragments;
13970 vcpu->mmio_nr_fragments = 1;
13971 frag->len = bytes;
13972 frag->gpa = gpa;
13973 frag->data = data;
13974
13975 vcpu->mmio_needed = 1;
13976 vcpu->mmio_cur_fragment = 0;
13977
13978 vcpu->run->mmio.phys_addr = gpa;
13979 vcpu->run->mmio.len = min(8u, frag->len);
13980 vcpu->run->mmio.is_write = 0;
13981 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13982
13983 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13984
13985 return 0;
13986}
13987EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13988
db209369
PB
13989static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13990{
13991 vcpu->arch.sev_pio_count -= count;
13992 vcpu->arch.sev_pio_data += count * size;
13993}
13994
7ed9abfe 13995static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
95e16b47
PB
13996 unsigned int port);
13997
13998static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
7ed9abfe 13999{
95e16b47
PB
14000 int size = vcpu->arch.pio.size;
14001 int port = vcpu->arch.pio.port;
14002
14003 vcpu->arch.pio.count = 0;
14004 if (vcpu->arch.sev_pio_count)
14005 return kvm_sev_es_outs(vcpu, size, port);
14006 return 1;
14007}
14008
14009static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14010 unsigned int port)
14011{
14012 for (;;) {
14013 unsigned int count =
14014 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14015 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14016
14017 /* memcpy done already by emulator_pio_out. */
db209369 14018 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
14019 if (!ret)
14020 break;
7ed9abfe 14021
ea724ea4 14022 /* Emulation done by the kernel. */
95e16b47
PB
14023 if (!vcpu->arch.sev_pio_count)
14024 return 1;
ea724ea4 14025 }
7ed9abfe 14026
95e16b47 14027 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
7ed9abfe
TL
14028 return 0;
14029}
14030
95e16b47
PB
14031static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14032 unsigned int port);
14033
4fa4b38d
PB
14034static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14035{
0c05e10b 14036 unsigned count = vcpu->arch.pio.count;
95e16b47
PB
14037 int size = vcpu->arch.pio.size;
14038 int port = vcpu->arch.pio.port;
4fa4b38d 14039
0c05e10b 14040 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
db209369 14041 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
14042 if (vcpu->arch.sev_pio_count)
14043 return kvm_sev_es_ins(vcpu, size, port);
4fa4b38d
PB
14044 return 1;
14045}
14046
7ed9abfe 14047static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
95e16b47 14048 unsigned int port)
7ed9abfe 14049{
95e16b47
PB
14050 for (;;) {
14051 unsigned int count =
14052 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
f35cee4a 14053 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
95e16b47 14054 break;
7ed9abfe 14055
ea724ea4 14056 /* Emulation done by the kernel. */
db209369 14057 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
14058 if (!vcpu->arch.sev_pio_count)
14059 return 1;
7ed9abfe
TL
14060 }
14061
ea724ea4 14062 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
7ed9abfe
TL
14063 return 0;
14064}
14065
14066int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14067 unsigned int port, void *data, unsigned int count,
14068 int in)
14069{
ea724ea4 14070 vcpu->arch.sev_pio_data = data;
95e16b47
PB
14071 vcpu->arch.sev_pio_count = count;
14072 return in ? kvm_sev_es_ins(vcpu, size, port)
14073 : kvm_sev_es_outs(vcpu, size, port);
7ed9abfe
TL
14074}
14075EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
14076
d95df951 14077EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
229456fc 14078EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
bb723beb 14079EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
931c33b1 14080EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
229456fc
MT
14081EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14082EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14083EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14084EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
89e54ec5 14085EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
d8cabddf 14086EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
17897f36 14087EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
236649de 14088EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5497b955 14089EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
ec1ff790 14090EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
532a46b9 14091EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
2e554e8d 14092EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
489223ed 14093EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
4f75bcc3 14094EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
843e4330 14095EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
efc64404 14096EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
18f40c53
SS
14097EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14098EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
ab56f8e6 14099EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
9f084f7c 14100EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
39b6b8c3 14101EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
8e819d75 14102EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
d523ab6b
TL
14103EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14104EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
59e38b58
TL
14105EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14106EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
c63cf135 14107EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
1d0e8480
SC
14108
14109static int __init kvm_x86_init(void)
14110{
1201f226
SC
14111 kvm_init_xstate_sizes();
14112
1d0e8480 14113 kvm_mmu_x86_module_init();
6f0f2d5e 14114 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
1d0e8480
SC
14115 return 0;
14116}
14117module_init(kvm_x86_init);
14118
14119static void __exit kvm_x86_exit(void)
14120{
fc3c9414 14121 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
1d0e8480
SC
14122}
14123module_exit(kvm_x86_exit);