KVM: x86/xen: add support for 32-bit guests in SCHEDOP_poll
[linux-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
CO
17 */
18
edf88417 19#include <linux/kvm_host.h>
313a3dc7 20#include "irq.h"
88197e6a 21#include "ioapic.h"
1d737c8a 22#include "mmu.h"
7837699f 23#include "i8254.h"
37817f29 24#include "tss.h"
5fdbf976 25#include "kvm_cache_regs.h"
2f728d66 26#include "kvm_emulate.h"
26eef70c 27#include "x86.h"
00b27a3e 28#include "cpuid.h"
474a5bb9 29#include "pmu.h"
e83d5887 30#include "hyperv.h"
8df14af4 31#include "lapic.h"
23200b7a 32#include "xen.h"
b0b42197 33#include "smm.h"
313a3dc7 34
18068523 35#include <linux/clocksource.h>
4d5c5d0f 36#include <linux/interrupt.h>
313a3dc7
CO
37#include <linux/kvm.h>
38#include <linux/fs.h>
39#include <linux/vmalloc.h>
1767e931
PG
40#include <linux/export.h>
41#include <linux/moduleparam.h>
0de10343 42#include <linux/mman.h>
2bacc55c 43#include <linux/highmem.h>
19de40a8 44#include <linux/iommu.h>
c8076604 45#include <linux/cpufreq.h>
18863bdd 46#include <linux/user-return-notifier.h>
a983fb23 47#include <linux/srcu.h>
5a0e3ad6 48#include <linux/slab.h>
ff9d07a0 49#include <linux/perf_event.h>
7bee342a 50#include <linux/uaccess.h>
af585b92 51#include <linux/hash.h>
a1b60c1c 52#include <linux/pci.h>
16e8d74d
MT
53#include <linux/timekeeper_internal.h>
54#include <linux/pvclock_gtod.h>
87276880
FW
55#include <linux/kvm_irqfd.h>
56#include <linux/irqbypass.h>
3905f9ad 57#include <linux/sched/stat.h>
0c5f81da 58#include <linux/sched/isolation.h>
d0ec49d4 59#include <linux/mem_encrypt.h>
72c3c0fe 60#include <linux/entry-kvm.h>
7d62874f 61#include <linux/suspend.h>
3905f9ad 62
aec51dc4 63#include <trace/events/kvm.h>
2ed152af 64
24f1e32c 65#include <asm/debugreg.h>
d825ed0a 66#include <asm/msr.h>
a5f61300 67#include <asm/desc.h>
890ca9ae 68#include <asm/mce.h>
784a4661 69#include <asm/pkru.h>
f89e32e0 70#include <linux/kernel_stat.h>
a0ff0611
TG
71#include <asm/fpu/api.h>
72#include <asm/fpu/xcr.h>
73#include <asm/fpu/xstate.h>
1d5f066e 74#include <asm/pvclock.h>
217fc9cf 75#include <asm/div64.h>
efc64404 76#include <asm/irq_remapping.h>
b0c39dc6 77#include <asm/mshyperv.h>
0092e434 78#include <asm/hypervisor.h>
9715092f 79#include <asm/tlbflush.h>
bf8c55d8 80#include <asm/intel_pt.h>
b3dc0695 81#include <asm/emulate_prefix.h>
fe7e9488 82#include <asm/sgx.h>
dd2cb348 83#include <clocksource/hyperv_timer.h>
043405e1 84
d1898b73
DH
85#define CREATE_TRACE_POINTS
86#include "trace.h"
87
313a3dc7 88#define MAX_IO_MSRS 256
890ca9ae 89#define KVM_MAX_MCE_BANKS 32
938c8745
SC
90
91struct kvm_caps kvm_caps __read_mostly = {
92 .supported_mce_cap = MCG_CTL_P | MCG_SER_P,
93};
94EXPORT_SYMBOL_GPL(kvm_caps);
890ca9ae 95
6e37ec88
SC
96#define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
97
0f65dd70 98#define emul_to_vcpu(ctxt) \
c9b8b07c 99 ((struct kvm_vcpu *)(ctxt)->vcpu)
0f65dd70 100
50a37eb4
JR
101/* EFER defaults:
102 * - enable syscall per default because its emulated by KVM
103 * - enable LME and LMA per default on 64 bit KVM
104 */
105#ifdef CONFIG_X86_64
1260edbe
LJ
106static
107u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
50a37eb4 108#else
1260edbe 109static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
50a37eb4 110#endif
313a3dc7 111
b11306b5
SC
112static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
113
0dbb1123
AK
114#define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
115
ba7bb663
DD
116#define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
117
c519265f
RK
118#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
119 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
37131313 120
cb142eb7 121static void update_cr8_intercept(struct kvm_vcpu *vcpu);
7460fb4a 122static void process_nmi(struct kvm_vcpu *vcpu);
6addfc42 123static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
01643c51
KH
124static void store_regs(struct kvm_vcpu *vcpu);
125static int sync_regs(struct kvm_vcpu *vcpu);
d2f7d498 126static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
674eea0f 127
6dba9403
ML
128static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
129static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
130
afaf0b2f 131struct kvm_x86_ops kvm_x86_ops __read_mostly;
97896d04 132
9af5471b
JB
133#define KVM_X86_OP(func) \
134 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
135 *(((struct kvm_x86_ops *)0)->func));
e4fc23ba 136#define KVM_X86_OP_OPTIONAL KVM_X86_OP
5be2226f 137#define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
9af5471b
JB
138#include <asm/kvm-x86-ops.h>
139EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
140EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
9af5471b 141
893590c7 142static bool __read_mostly ignore_msrs = 0;
476bc001 143module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
ed85c068 144
d855066f 145bool __read_mostly report_ignored_msrs = true;
fab0aa3b 146module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
d855066f 147EXPORT_SYMBOL_GPL(report_ignored_msrs);
fab0aa3b 148
4c27625b 149unsigned int min_timer_period_us = 200;
9ed96e87
MT
150module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
151
630994b3
MT
152static bool __read_mostly kvmclock_periodic_sync = true;
153module_param(kvmclock_periodic_sync, bool, S_IRUGO);
154
cc578287 155/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
893590c7 156static u32 __read_mostly tsc_tolerance_ppm = 250;
cc578287
ZA
157module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
158
c3941d9e
SC
159/*
160 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
d9f6e12f 161 * adaptive tuning starting from default advancement of 1000ns. '0' disables
c3941d9e 162 * advancement entirely. Any other value is used as-is and disables adaptive
d9f6e12f 163 * tuning, i.e. allows privileged userspace to set an exact advancement time.
c3941d9e
SC
164 */
165static int __read_mostly lapic_timer_advance_ns = -1;
0e6edceb 166module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
d0659d94 167
52004014
FW
168static bool __read_mostly vector_hashing = true;
169module_param(vector_hashing, bool, S_IRUGO);
170
c4ae60e4
LA
171bool __read_mostly enable_vmware_backdoor = false;
172module_param(enable_vmware_backdoor, bool, S_IRUGO);
173EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
174
d500e1ed
SC
175/*
176 * Flags to manipulate forced emulation behavior (any non-zero value will
177 * enable forced emulation).
178 */
179#define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
180static int __read_mostly force_emulation_prefix;
40aaa5b6 181module_param(force_emulation_prefix, int, 0644);
6c86eedc 182
0c5f81da
WL
183int __read_mostly pi_inject_timer = -1;
184module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
185
4732f244
LX
186/* Enable/disable PMU virtualization */
187bool __read_mostly enable_pmu = true;
188EXPORT_SYMBOL_GPL(enable_pmu);
189module_param(enable_pmu, bool, 0444);
190
cb00a70b 191bool __read_mostly eager_page_split = true;
a3fe5dbd
DM
192module_param(eager_page_split, bool, 0644);
193
7e34fbd0
SC
194/*
195 * Restoring the host value for MSRs that are only consumed when running in
196 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
197 * returns to userspace, i.e. the kernel can run with the guest's value.
198 */
199#define KVM_MAX_NR_USER_RETURN_MSRS 16
18863bdd 200
7e34fbd0 201struct kvm_user_return_msrs {
18863bdd
AK
202 struct user_return_notifier urn;
203 bool registered;
7e34fbd0 204 struct kvm_user_return_msr_values {
2bf78fa7
SY
205 u64 host;
206 u64 curr;
7e34fbd0 207 } values[KVM_MAX_NR_USER_RETURN_MSRS];
18863bdd
AK
208};
209
9cc39a5a
SC
210u32 __read_mostly kvm_nr_uret_msrs;
211EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
212static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
7e34fbd0 213static struct kvm_user_return_msrs __percpu *user_return_msrs;
18863bdd 214
cfc48181
SC
215#define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
216 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
217 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
86aff7a4 218 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
cfc48181 219
91661989
SC
220u64 __read_mostly host_efer;
221EXPORT_SYMBOL_GPL(host_efer);
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
86137773
TL
229u64 __read_mostly host_xss;
230EXPORT_SYMBOL_GPL(host_xss);
139a12cf 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
2acf923e
DC
305u64 __read_mostly host_xcr0;
306
c9b8b07c
SC
307static struct kmem_cache *x86_emulator_cache;
308
6abe9c13
PX
309/*
310 * When called, it means the previous get/set msr reached an invalid msr.
cc4cb017 311 * Return true if we want to ignore/silent this failed msr access.
6abe9c13 312 */
d632826f 313static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
6abe9c13
PX
314{
315 const char *op = write ? "wrmsr" : "rdmsr";
316
317 if (ignore_msrs) {
318 if (report_ignored_msrs)
d383b314
TI
319 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
320 op, msr, data);
6abe9c13 321 /* Mask the error */
cc4cb017 322 return true;
6abe9c13 323 } else {
d383b314
TI
324 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
325 op, msr, data);
cc4cb017 326 return false;
6abe9c13
PX
327 }
328}
329
c9b8b07c
SC
330static struct kmem_cache *kvm_alloc_emulator_cache(void)
331{
06add254
SC
332 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
333 unsigned int size = sizeof(struct x86_emulate_ctxt);
334
335 return kmem_cache_create_usercopy("x86_emulator", size,
c9b8b07c 336 __alignof__(struct x86_emulate_ctxt),
06add254
SC
337 SLAB_ACCOUNT, useroffset,
338 size - useroffset, NULL);
c9b8b07c
SC
339}
340
b6785def 341static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
d6aa1000 342
af585b92
GN
343static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
344{
345 int i;
dd03bcaa 346 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
af585b92
GN
347 vcpu->arch.apf.gfns[i] = ~0;
348}
349
18863bdd
AK
350static void kvm_on_user_return(struct user_return_notifier *urn)
351{
352 unsigned slot;
7e34fbd0
SC
353 struct kvm_user_return_msrs *msrs
354 = container_of(urn, struct kvm_user_return_msrs, urn);
355 struct kvm_user_return_msr_values *values;
1650b4eb
IA
356 unsigned long flags;
357
358 /*
359 * Disabling irqs at this point since the following code could be
360 * interrupted and executed through kvm_arch_hardware_disable()
361 */
362 local_irq_save(flags);
7e34fbd0
SC
363 if (msrs->registered) {
364 msrs->registered = false;
1650b4eb
IA
365 user_return_notifier_unregister(urn);
366 }
367 local_irq_restore(flags);
9cc39a5a 368 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
7e34fbd0 369 values = &msrs->values[slot];
2bf78fa7 370 if (values->host != values->curr) {
9cc39a5a 371 wrmsrl(kvm_uret_msrs_list[slot], values->host);
2bf78fa7 372 values->curr = values->host;
18863bdd
AK
373 }
374 }
18863bdd
AK
375}
376
e5fda4bb 377static int kvm_probe_user_return_msr(u32 msr)
5104d7ff
SC
378{
379 u64 val;
380 int ret;
381
382 preempt_disable();
383 ret = rdmsrl_safe(msr, &val);
384 if (ret)
385 goto out;
386 ret = wrmsrl_safe(msr, val);
387out:
388 preempt_enable();
389 return ret;
390}
5104d7ff 391
e5fda4bb 392int kvm_add_user_return_msr(u32 msr)
2bf78fa7 393{
e5fda4bb
SC
394 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
395
396 if (kvm_probe_user_return_msr(msr))
397 return -1;
398
399 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
400 return kvm_nr_uret_msrs++;
18863bdd 401}
e5fda4bb 402EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
18863bdd 403
8ea8b8d6
SC
404int kvm_find_user_return_msr(u32 msr)
405{
406 int i;
407
9cc39a5a
SC
408 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
409 if (kvm_uret_msrs_list[i] == msr)
8ea8b8d6
SC
410 return i;
411 }
412 return -1;
413}
414EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
415
7e34fbd0 416static void kvm_user_return_msr_cpu_online(void)
18863bdd 417{
05c19c2f 418 unsigned int cpu = smp_processor_id();
7e34fbd0 419 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
05c19c2f
SC
420 u64 value;
421 int i;
18863bdd 422
9cc39a5a
SC
423 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
424 rdmsrl_safe(kvm_uret_msrs_list[i], &value);
7e34fbd0
SC
425 msrs->values[i].host = value;
426 msrs->values[i].curr = value;
05c19c2f 427 }
18863bdd
AK
428}
429
7e34fbd0 430int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
18863bdd 431{
013f6a5d 432 unsigned int cpu = smp_processor_id();
7e34fbd0 433 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
8b3c3104 434 int err;
18863bdd 435
7e34fbd0
SC
436 value = (value & mask) | (msrs->values[slot].host & ~mask);
437 if (value == msrs->values[slot].curr)
8b3c3104 438 return 0;
9cc39a5a 439 err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
8b3c3104
AH
440 if (err)
441 return 1;
442
7e34fbd0
SC
443 msrs->values[slot].curr = value;
444 if (!msrs->registered) {
445 msrs->urn.on_user_return = kvm_on_user_return;
446 user_return_notifier_register(&msrs->urn);
447 msrs->registered = true;
18863bdd 448 }
8b3c3104 449 return 0;
18863bdd 450}
7e34fbd0 451EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
18863bdd 452
13a34e06 453static void drop_user_return_notifiers(void)
3548bab5 454{
013f6a5d 455 unsigned int cpu = smp_processor_id();
7e34fbd0 456 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
3548bab5 457
7e34fbd0
SC
458 if (msrs->registered)
459 kvm_on_user_return(&msrs->urn);
3548bab5
AK
460}
461
6866b83e
CO
462u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
463{
8a5a87d9 464 return vcpu->arch.apic_base;
6866b83e
CO
465}
466EXPORT_SYMBOL_GPL(kvm_get_apic_base);
467
58871649
JM
468enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
469{
470 return kvm_apic_mode(kvm_get_apic_base(vcpu));
471}
472EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
473
58cb628d
JK
474int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
475{
58871649
JM
476 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
477 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
a8ac864a 478 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
d6321d49 479 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
58cb628d 480
58871649 481 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
58cb628d 482 return 1;
58871649
JM
483 if (!msr_info->host_initiated) {
484 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
485 return 1;
486 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
487 return 1;
488 }
58cb628d
JK
489
490 kvm_lapic_set_base(vcpu, msr_info->data);
4abaffce 491 kvm_recalculate_apic_map(vcpu->kvm);
58cb628d 492 return 0;
6866b83e
CO
493}
494EXPORT_SYMBOL_GPL(kvm_set_apic_base);
495
ad0577c3
SC
496/*
497 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
498 *
499 * Hardware virtualization extension instructions may fault if a reboot turns
500 * off virtualization while processes are running. Usually after catching the
501 * fault we just panic; during reboot instead the instruction is ignored.
502 */
503noinstr void kvm_spurious_fault(void)
e3ba45b8
GL
504{
505 /* Fault while not rebooting. We want the trace. */
b4fdcf60 506 BUG_ON(!kvm_rebooting);
e3ba45b8
GL
507}
508EXPORT_SYMBOL_GPL(kvm_spurious_fault);
509
3fd28fce
ED
510#define EXCPT_BENIGN 0
511#define EXCPT_CONTRIBUTORY 1
512#define EXCPT_PF 2
513
514static int exception_class(int vector)
515{
516 switch (vector) {
517 case PF_VECTOR:
518 return EXCPT_PF;
519 case DE_VECTOR:
520 case TS_VECTOR:
521 case NP_VECTOR:
522 case SS_VECTOR:
523 case GP_VECTOR:
524 return EXCPT_CONTRIBUTORY;
525 default:
526 break;
527 }
528 return EXCPT_BENIGN;
529}
530
d6e8c854
NA
531#define EXCPT_FAULT 0
532#define EXCPT_TRAP 1
533#define EXCPT_ABORT 2
534#define EXCPT_INTERRUPT 3
5623f751 535#define EXCPT_DB 4
d6e8c854
NA
536
537static int exception_type(int vector)
538{
539 unsigned int mask;
540
541 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
542 return EXCPT_INTERRUPT;
543
544 mask = 1 << vector;
545
5623f751
SC
546 /*
547 * #DBs can be trap-like or fault-like, the caller must check other CPU
548 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
549 */
550 if (mask & (1 << DB_VECTOR))
551 return EXCPT_DB;
552
553 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
d6e8c854
NA
554 return EXCPT_TRAP;
555
556 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
557 return EXCPT_ABORT;
558
559 /* Reserved exceptions will result in fault */
560 return EXCPT_FAULT;
561}
562
d4963e31
SC
563void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
564 struct kvm_queued_exception *ex)
da998b46 565{
d4963e31 566 if (!ex->has_payload)
da998b46
JM
567 return;
568
d4963e31 569 switch (ex->vector) {
f10c729f
JM
570 case DB_VECTOR:
571 /*
572 * "Certain debug exceptions may clear bit 0-3. The
573 * remaining contents of the DR6 register are never
574 * cleared by the processor".
575 */
576 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
577 /*
9a3ecd5e
CQ
578 * In order to reflect the #DB exception payload in guest
579 * dr6, three components need to be considered: active low
580 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
581 * DR6_BS and DR6_BT)
582 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
583 * In the target guest dr6:
584 * FIXED_1 bits should always be set.
585 * Active low bits should be cleared if 1-setting in payload.
586 * Active high bits should be set if 1-setting in payload.
587 *
588 * Note, the payload is compatible with the pending debug
589 * exceptions/exit qualification under VMX, that active_low bits
590 * are active high in payload.
591 * So they need to be flipped for DR6.
f10c729f 592 */
9a3ecd5e 593 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
d4963e31
SC
594 vcpu->arch.dr6 |= ex->payload;
595 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
307f1cfa
OU
596
597 /*
598 * The #DB payload is defined as compatible with the 'pending
599 * debug exceptions' field under VMX, not DR6. While bit 12 is
600 * defined in the 'pending debug exceptions' field (enabled
601 * breakpoint), it is reserved and must be zero in DR6.
602 */
603 vcpu->arch.dr6 &= ~BIT(12);
f10c729f 604 break;
da998b46 605 case PF_VECTOR:
d4963e31 606 vcpu->arch.cr2 = ex->payload;
da998b46
JM
607 break;
608 }
609
d4963e31
SC
610 ex->has_payload = false;
611 ex->payload = 0;
da998b46
JM
612}
613EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
614
7709aba8
SC
615static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
616 bool has_error_code, u32 error_code,
617 bool has_payload, unsigned long payload)
618{
619 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
620
621 ex->vector = vector;
622 ex->injected = false;
623 ex->pending = true;
624 ex->has_error_code = has_error_code;
625 ex->error_code = error_code;
626 ex->has_payload = has_payload;
627 ex->payload = payload;
628}
629
f9697df2
ML
630/* Forcibly leave the nested mode in cases like a vCPU reset */
631static void kvm_leave_nested(struct kvm_vcpu *vcpu)
632{
633 kvm_x86_ops.nested_ops->leave_nested(vcpu);
634}
635
3fd28fce 636static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
ce7ddec4 637 unsigned nr, bool has_error, u32 error_code,
91e86d22 638 bool has_payload, unsigned long payload, bool reinject)
3fd28fce
ED
639{
640 u32 prev_nr;
641 int class1, class2;
642
3842d135
AK
643 kvm_make_request(KVM_REQ_EVENT, vcpu);
644
7709aba8
SC
645 /*
646 * If the exception is destined for L2 and isn't being reinjected,
647 * morph it to a VM-Exit if L1 wants to intercept the exception. A
648 * previously injected exception is not checked because it was checked
649 * when it was original queued, and re-checking is incorrect if _L1_
650 * injected the exception, in which case it's exempt from interception.
651 */
652 if (!reinject && is_guest_mode(vcpu) &&
653 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
654 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
655 has_payload, payload);
656 return;
657 }
658
664f8e26 659 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
3fd28fce 660 queue:
664f8e26
WL
661 if (reinject) {
662 /*
7709aba8
SC
663 * On VM-Entry, an exception can be pending if and only
664 * if event injection was blocked by nested_run_pending.
665 * In that case, however, vcpu_enter_guest() requests an
666 * immediate exit, and the guest shouldn't proceed far
667 * enough to need reinjection.
664f8e26 668 */
7709aba8 669 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
664f8e26 670 vcpu->arch.exception.injected = true;
91e86d22
JM
671 if (WARN_ON_ONCE(has_payload)) {
672 /*
673 * A reinjected event has already
674 * delivered its payload.
675 */
676 has_payload = false;
677 payload = 0;
678 }
664f8e26
WL
679 } else {
680 vcpu->arch.exception.pending = true;
681 vcpu->arch.exception.injected = false;
682 }
3fd28fce 683 vcpu->arch.exception.has_error_code = has_error;
d4963e31 684 vcpu->arch.exception.vector = nr;
3fd28fce 685 vcpu->arch.exception.error_code = error_code;
91e86d22
JM
686 vcpu->arch.exception.has_payload = has_payload;
687 vcpu->arch.exception.payload = payload;
a06230b6 688 if (!is_guest_mode(vcpu))
d4963e31
SC
689 kvm_deliver_exception_payload(vcpu,
690 &vcpu->arch.exception);
3fd28fce
ED
691 return;
692 }
693
694 /* to check exception */
d4963e31 695 prev_nr = vcpu->arch.exception.vector;
3fd28fce
ED
696 if (prev_nr == DF_VECTOR) {
697 /* triple fault -> shutdown */
a8eeb04a 698 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3fd28fce
ED
699 return;
700 }
701 class1 = exception_class(prev_nr);
702 class2 = exception_class(nr);
81601495
SC
703 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
704 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
664f8e26 705 /*
81601495
SC
706 * Synthesize #DF. Clear the previously injected or pending
707 * exception so as not to incorrectly trigger shutdown.
664f8e26 708 */
664f8e26 709 vcpu->arch.exception.injected = false;
81601495
SC
710 vcpu->arch.exception.pending = false;
711
712 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
713 } else {
3fd28fce
ED
714 /* replace previous exception with a new one in a hope
715 that instruction re-execution will regenerate lost
716 exception */
717 goto queue;
81601495 718 }
3fd28fce
ED
719}
720
298101da
AK
721void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
722{
91e86d22 723 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
298101da
AK
724}
725EXPORT_SYMBOL_GPL(kvm_queue_exception);
726
ce7ddec4
JR
727void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
728{
91e86d22 729 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
ce7ddec4
JR
730}
731EXPORT_SYMBOL_GPL(kvm_requeue_exception);
732
4d5523cf
PB
733void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
734 unsigned long payload)
f10c729f
JM
735{
736 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
737}
4d5523cf 738EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
f10c729f 739
da998b46
JM
740static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
741 u32 error_code, unsigned long payload)
742{
743 kvm_multiple_exception(vcpu, nr, true, error_code,
744 true, payload, false);
745}
746
6affcbed 747int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
c3c91fee 748{
db8fcefa
AP
749 if (err)
750 kvm_inject_gp(vcpu, 0);
751 else
6affcbed
KH
752 return kvm_skip_emulated_instruction(vcpu);
753
754 return 1;
db8fcefa
AP
755}
756EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
8df25a32 757
d2f7d498
HW
758static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
759{
760 if (err) {
761 kvm_inject_gp(vcpu, 0);
762 return 1;
763 }
764
765 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
766 EMULTYPE_COMPLETE_USER_EXIT);
767}
768
6389ee94 769void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
c3c91fee
AK
770{
771 ++vcpu->stat.pf_guest;
7709aba8
SC
772
773 /*
774 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
775 * whether or not L1 wants to intercept "regular" #PF.
776 */
777 if (is_guest_mode(vcpu) && fault->async_page_fault)
778 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
779 true, fault->error_code,
780 true, fault->address);
781 else
da998b46
JM
782 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
783 fault->address);
c3c91fee 784}
27d6c865 785EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
c3c91fee 786
7709aba8 787void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
53b3d8e9 788 struct x86_exception *fault)
d4f8cf66 789{
0cd665bd 790 struct kvm_mmu *fault_mmu;
53b3d8e9
SC
791 WARN_ON_ONCE(fault->vector != PF_VECTOR);
792
0cd665bd
PB
793 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
794 vcpu->arch.walk_mmu;
ef54bcfe 795
ee1fa209
JS
796 /*
797 * Invalidate the TLB entry for the faulting address, if it exists,
798 * else the access will fault indefinitely (and to emulate hardware).
799 */
800 if ((fault->error_code & PFERR_PRESENT_MASK) &&
801 !(fault->error_code & PFERR_RSVD_MASK))
802 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
b9e5603c 803 fault_mmu->root.hpa);
ee1fa209
JS
804
805 fault_mmu->inject_page_fault(vcpu, fault);
d4f8cf66 806}
53b3d8e9 807EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
d4f8cf66 808
3419ffc8
SY
809void kvm_inject_nmi(struct kvm_vcpu *vcpu)
810{
7460fb4a
AK
811 atomic_inc(&vcpu->arch.nmi_queued);
812 kvm_make_request(KVM_REQ_NMI, vcpu);
3419ffc8
SY
813}
814EXPORT_SYMBOL_GPL(kvm_inject_nmi);
815
298101da
AK
816void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
817{
91e86d22 818 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
298101da
AK
819}
820EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
821
ce7ddec4
JR
822void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
823{
91e86d22 824 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
ce7ddec4
JR
825}
826EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
827
0a79b009
AK
828/*
829 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
830 * a #GP and return false.
831 */
832bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
298101da 833{
b3646477 834 if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
0a79b009
AK
835 return true;
836 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
837 return false;
298101da 838}
0a79b009 839EXPORT_SYMBOL_GPL(kvm_require_cpl);
298101da 840
16f8a6f9
NA
841bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
842{
843 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
844 return true;
845
846 kvm_queue_exception(vcpu, UD_VECTOR);
847 return false;
848}
849EXPORT_SYMBOL_GPL(kvm_require_dr);
850
16cfacc8
SC
851static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
852{
5b7f575c 853 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
16cfacc8
SC
854}
855
a03490ed 856/*
16cfacc8 857 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
a03490ed 858 */
2df4a5eb 859int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 860{
2df4a5eb 861 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
a03490ed 862 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
15cabbc2 863 gpa_t real_gpa;
a03490ed
CO
864 int i;
865 int ret;
ff03a073 866 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
a03490ed 867
15cabbc2
SC
868 /*
869 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
870 * to an L1 GPA.
871 */
c59a0f57
LJ
872 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
873 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
6e1d2a3f 874 if (real_gpa == INVALID_GPA)
15cabbc2
SC
875 return 0;
876
94c641ba 877 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
15cabbc2 878 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
94c641ba 879 cr3 & GENMASK(11, 5), sizeof(pdpte));
15cabbc2
SC
880 if (ret < 0)
881 return 0;
882
a03490ed 883 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
812f30b2 884 if ((pdpte[i] & PT_PRESENT_MASK) &&
16cfacc8 885 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
15cabbc2 886 return 0;
a03490ed
CO
887 }
888 }
a03490ed 889
6b123c3a
LJ
890 /*
891 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
892 * Shadow page roots need to be reconstructed instead.
893 */
894 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
0c1c92f1 895 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
6b123c3a 896
46cbc040
PB
897 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
898 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
899 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
158a48ec
ML
900 vcpu->arch.pdptrs_from_userspace = false;
901
15cabbc2 902 return 1;
a03490ed 903}
cc4b6871 904EXPORT_SYMBOL_GPL(load_pdptrs);
a03490ed 905
f27ad38a
TL
906void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
907{
f27ad38a
TL
908 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
909 kvm_clear_async_pf_completion_queue(vcpu);
910 kvm_async_pf_hash_reset(vcpu);
b5f61c03
PB
911
912 /*
913 * Clearing CR0.PG is defined to flush the TLB from the guest's
914 * perspective.
915 */
916 if (!(cr0 & X86_CR0_PG))
917 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
f27ad38a
TL
918 }
919
20f632bd 920 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
f27ad38a
TL
921 kvm_mmu_reset_context(vcpu);
922
923 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
924 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
925 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
926 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
927}
928EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
929
49a9b07e 930int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
a03490ed 931{
aad82703 932 unsigned long old_cr0 = kvm_read_cr0(vcpu);
aad82703 933
f9a48e6a
AK
934 cr0 |= X86_CR0_ET;
935
ab344828 936#ifdef CONFIG_X86_64
0f12244f
GN
937 if (cr0 & 0xffffffff00000000UL)
938 return 1;
ab344828
GN
939#endif
940
941 cr0 &= ~CR0_RESERVED_BITS;
a03490ed 942
0f12244f
GN
943 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
944 return 1;
a03490ed 945
0f12244f
GN
946 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
947 return 1;
a03490ed 948
a03490ed 949#ifdef CONFIG_X86_64
05487215
SC
950 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
951 (cr0 & X86_CR0_PG)) {
952 int cs_db, cs_l;
953
954 if (!is_pae(vcpu))
955 return 1;
b3646477 956 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
05487215 957 if (cs_l)
0f12244f 958 return 1;
a03490ed 959 }
05487215
SC
960#endif
961 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
e63f315d 962 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
2df4a5eb 963 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
05487215 964 return 1;
a03490ed 965
777ab82d
LJ
966 if (!(cr0 & X86_CR0_PG) &&
967 (is_64_bit_mode(vcpu) || kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)))
ad756a16
MJ
968 return 1;
969
b3646477 970 static_call(kvm_x86_set_cr0)(vcpu, cr0);
a03490ed 971
f27ad38a 972 kvm_post_set_cr0(vcpu, old_cr0, cr0);
b18d5431 973
0f12244f
GN
974 return 0;
975}
2d3ad1f4 976EXPORT_SYMBOL_GPL(kvm_set_cr0);
a03490ed 977
2d3ad1f4 978void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
a03490ed 979{
49a9b07e 980 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
a03490ed 981}
2d3ad1f4 982EXPORT_SYMBOL_GPL(kvm_lmsw);
a03490ed 983
139a12cf 984void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 985{
16809ecd
TL
986 if (vcpu->arch.guest_state_protected)
987 return;
988
139a12cf
AL
989 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
990
991 if (vcpu->arch.xcr0 != host_xcr0)
992 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
993
994 if (vcpu->arch.xsaves_enabled &&
995 vcpu->arch.ia32_xss != host_xss)
996 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
997 }
37486135 998
945024d7 999#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
37486135 1000 if (static_cpu_has(X86_FEATURE_PKU) &&
945024d7
JK
1001 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1002 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1003 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)))
72a6c08c 1004 write_pkru(vcpu->arch.pkru);
945024d7 1005#endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
42bdf991 1006}
139a12cf 1007EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
42bdf991 1008
139a12cf 1009void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
42bdf991 1010{
16809ecd
TL
1011 if (vcpu->arch.guest_state_protected)
1012 return;
1013
945024d7 1014#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
37486135 1015 if (static_cpu_has(X86_FEATURE_PKU) &&
945024d7
JK
1016 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1017 kvm_read_cr4_bits(vcpu, X86_CR4_PKE))) {
37486135
BM
1018 vcpu->arch.pkru = rdpkru();
1019 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
72a6c08c 1020 write_pkru(vcpu->arch.host_pkru);
37486135 1021 }
945024d7 1022#endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
37486135 1023
139a12cf
AL
1024 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
1025
1026 if (vcpu->arch.xcr0 != host_xcr0)
1027 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
1028
1029 if (vcpu->arch.xsaves_enabled &&
1030 vcpu->arch.ia32_xss != host_xss)
1031 wrmsrl(MSR_IA32_XSS, host_xss);
1032 }
1033
42bdf991 1034}
139a12cf 1035EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
42bdf991 1036
ba1f77c5 1037#ifdef CONFIG_X86_64
988896bb
LB
1038static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1039{
ee519b3a 1040 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
988896bb 1041}
ba1f77c5 1042#endif
988896bb 1043
69b0049a 1044static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
2acf923e 1045{
56c103ec
LJ
1046 u64 xcr0 = xcr;
1047 u64 old_xcr0 = vcpu->arch.xcr0;
46c34cb0 1048 u64 valid_bits;
2acf923e
DC
1049
1050 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1051 if (index != XCR_XFEATURE_ENABLED_MASK)
1052 return 1;
d91cab78 1053 if (!(xcr0 & XFEATURE_MASK_FP))
2acf923e 1054 return 1;
d91cab78 1055 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
2acf923e 1056 return 1;
46c34cb0
PB
1057
1058 /*
1059 * Do not allow the guest to set bits that we do not support
1060 * saving. However, xcr0 bit 0 is always set, even if the
e8f65b9b 1061 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
46c34cb0 1062 */
ee519b3a 1063 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
46c34cb0 1064 if (xcr0 & ~valid_bits)
2acf923e 1065 return 1;
46c34cb0 1066
d91cab78
DH
1067 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1068 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
390bd528
LJ
1069 return 1;
1070
d91cab78
DH
1071 if (xcr0 & XFEATURE_MASK_AVX512) {
1072 if (!(xcr0 & XFEATURE_MASK_YMM))
612263b3 1073 return 1;
d91cab78 1074 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
612263b3
CP
1075 return 1;
1076 }
86aff7a4
JL
1077
1078 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1079 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1080 return 1;
1081
2acf923e 1082 vcpu->arch.xcr0 = xcr0;
56c103ec 1083
d91cab78 1084 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
aedbaf4f 1085 kvm_update_cpuid_runtime(vcpu);
2acf923e
DC
1086 return 0;
1087}
1088
92f9895c 1089int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
2acf923e 1090{
50b2d49b 1091 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
92f9895c
SC
1092 if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
1093 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1094 kvm_inject_gp(vcpu, 0);
1095 return 1;
1096 }
bbefd4fc 1097
92f9895c 1098 return kvm_skip_emulated_instruction(vcpu);
2acf923e 1099}
92f9895c 1100EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
2acf923e 1101
c33f6f22 1102bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
a03490ed 1103{
b11306b5 1104 if (cr4 & cr4_reserved_bits)
ee69c92b 1105 return false;
b9baba86 1106
b899c132 1107 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
ee69c92b 1108 return false;
3ca94192 1109
c33f6f22
SC
1110 return true;
1111}
1112EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
1113
1114static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1115{
1116 return __kvm_is_valid_cr4(vcpu, cr4) &&
1117 static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
3ca94192
WL
1118}
1119
5b51cb13
TL
1120void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1121{
b5f61c03
PB
1122 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1123 kvm_mmu_reset_context(vcpu);
1124
509bfe3d 1125 /*
509bfe3d
LJ
1126 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1127 * according to the SDM; however, stale prev_roots could be reused
1128 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
b5f61c03
PB
1129 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1130 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1131 * so fall through.
509bfe3d 1132 */
b5f61c03
PB
1133 if (!tdp_enabled &&
1134 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
f6d0a252 1135 kvm_mmu_unload(vcpu);
b5f61c03
PB
1136
1137 /*
1138 * The TLB has to be flushed for all PCIDs if any of the following
1139 * (architecturally required) changes happen:
1140 * - CR4.PCIDE is changed from 1 to 0
1141 * - CR4.PGE is toggled
509bfe3d 1142 *
b5f61c03 1143 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
509bfe3d 1144 */
b5f61c03
PB
1145 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1146 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
55261738 1147 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
b5f61c03
PB
1148
1149 /*
1150 * The TLB has to be flushed for the current PCID if any of the
1151 * following (architecturally required) changes happen:
1152 * - CR4.SMEP is changed from 0 to 1
1153 * - CR4.PAE is toggled
1154 */
1155 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1156 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1157 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1158
3ca94192 1159}
5b51cb13 1160EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
3ca94192
WL
1161
1162int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1163{
1164 unsigned long old_cr4 = kvm_read_cr4(vcpu);
3ca94192 1165
ee69c92b 1166 if (!kvm_is_valid_cr4(vcpu, cr4))
ae3e61e1
PB
1167 return 1;
1168
a03490ed 1169 if (is_long_mode(vcpu)) {
0f12244f
GN
1170 if (!(cr4 & X86_CR4_PAE))
1171 return 1;
d74fcfc1
SC
1172 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1173 return 1;
a2edf57f 1174 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
a37ebdce 1175 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
2df4a5eb 1176 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
0f12244f
GN
1177 return 1;
1178
ad756a16 1179 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
d6321d49 1180 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
ad756a16
MJ
1181 return 1;
1182
1183 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1184 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1185 return 1;
1186 }
1187
b3646477 1188 static_call(kvm_x86_set_cr4)(vcpu, cr4);
a03490ed 1189
5b51cb13 1190 kvm_post_set_cr4(vcpu, old_cr4, cr4);
2acf923e 1191
0f12244f
GN
1192 return 0;
1193}
2d3ad1f4 1194EXPORT_SYMBOL_GPL(kvm_set_cr4);
a03490ed 1195
21823fbd
SC
1196static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1197{
1198 struct kvm_mmu *mmu = vcpu->arch.mmu;
1199 unsigned long roots_to_free = 0;
1200 int i;
1201
e45e9e39
LJ
1202 /*
1203 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1204 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1205 * also via the emulator. KVM's TDP page tables are not in the scope of
1206 * the invalidation, but the guest's TLB entries need to be flushed as
1207 * the CPU may have cached entries in its TLB for the target PCID.
1208 */
1209 if (unlikely(tdp_enabled)) {
1210 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1211 return;
1212 }
1213
21823fbd
SC
1214 /*
1215 * If neither the current CR3 nor any of the prev_roots use the given
1216 * PCID, then nothing needs to be done here because a resync will
1217 * happen anyway before switching to any other CR3.
1218 */
1219 if (kvm_get_active_pcid(vcpu) == pcid) {
e62f1aa8 1220 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
21823fbd
SC
1221 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1222 }
1223
509bfe3d
LJ
1224 /*
1225 * If PCID is disabled, there is no need to free prev_roots even if the
1226 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1227 * with PCIDE=0.
1228 */
1229 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
1230 return;
1231
21823fbd
SC
1232 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1233 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1234 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1235
0c1c92f1 1236 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
21823fbd
SC
1237}
1238
2390218b 1239int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed 1240{
ade61e28 1241 bool skip_tlb_flush = false;
21823fbd 1242 unsigned long pcid = 0;
ac146235 1243#ifdef CONFIG_X86_64
c19986fe
JS
1244 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1245
ade61e28 1246 if (pcid_enabled) {
208320ba
JS
1247 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1248 cr3 &= ~X86_CR3_PCID_NOFLUSH;
21823fbd 1249 pcid = cr3 & X86_CR3_PCID_MASK;
ade61e28 1250 }
ac146235 1251#endif
9d88fca7 1252
c7313155 1253 /* PDPTRs are always reloaded for PAE paging. */
21823fbd
SC
1254 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1255 goto handle_tlb_flush;
d835dfec 1256
886bbcc7
SC
1257 /*
1258 * Do not condition the GPA check on long mode, this helper is used to
1259 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1260 * the current vCPU mode is accurate.
1261 */
1262 if (kvm_vcpu_is_illegal_gpa(vcpu, cr3))
d1cd3ce9 1263 return 1;
886bbcc7 1264
2df4a5eb 1265 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
346874c9 1266 return 1;
a03490ed 1267
21823fbd 1268 if (cr3 != kvm_read_cr3(vcpu))
b5129100 1269 kvm_mmu_new_pgd(vcpu, cr3);
21823fbd 1270
0f12244f 1271 vcpu->arch.cr3 = cr3;
3883bc9d 1272 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
405329fc 1273 /* Do not call post_set_cr3, we do not get here for confidential guests. */
7c390d35 1274
21823fbd
SC
1275handle_tlb_flush:
1276 /*
1277 * A load of CR3 that flushes the TLB flushes only the current PCID,
1278 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1279 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1280 * and it's impossible to use a non-zero PCID when PCID is disabled,
1281 * i.e. only PCID=0 can be relevant.
1282 */
1283 if (!skip_tlb_flush)
1284 kvm_invalidate_pcid(vcpu, pcid);
1285
0f12244f
GN
1286 return 0;
1287}
2d3ad1f4 1288EXPORT_SYMBOL_GPL(kvm_set_cr3);
a03490ed 1289
eea1cff9 1290int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
a03490ed 1291{
0f12244f
GN
1292 if (cr8 & CR8_RESERVED_BITS)
1293 return 1;
35754c98 1294 if (lapic_in_kernel(vcpu))
a03490ed
CO
1295 kvm_lapic_set_tpr(vcpu, cr8);
1296 else
ad312c7c 1297 vcpu->arch.cr8 = cr8;
0f12244f
GN
1298 return 0;
1299}
2d3ad1f4 1300EXPORT_SYMBOL_GPL(kvm_set_cr8);
a03490ed 1301
2d3ad1f4 1302unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
a03490ed 1303{
35754c98 1304 if (lapic_in_kernel(vcpu))
a03490ed
CO
1305 return kvm_lapic_get_cr8(vcpu);
1306 else
ad312c7c 1307 return vcpu->arch.cr8;
a03490ed 1308}
2d3ad1f4 1309EXPORT_SYMBOL_GPL(kvm_get_cr8);
a03490ed 1310
ae561ede
NA
1311static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1312{
1313 int i;
1314
1315 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1316 for (i = 0; i < KVM_NR_DB_REGS; i++)
1317 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
ae561ede
NA
1318 }
1319}
1320
7c86663b 1321void kvm_update_dr7(struct kvm_vcpu *vcpu)
c8639010
JK
1322{
1323 unsigned long dr7;
1324
1325 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1326 dr7 = vcpu->arch.guest_debug_dr7;
1327 else
1328 dr7 = vcpu->arch.dr7;
b3646477 1329 static_call(kvm_x86_set_dr7)(vcpu, dr7);
360b948d
PB
1330 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1331 if (dr7 & DR7_BP_EN_MASK)
1332 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
c8639010 1333}
7c86663b 1334EXPORT_SYMBOL_GPL(kvm_update_dr7);
c8639010 1335
6f43ed01
NA
1336static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1337{
1338 u64 fixed = DR6_FIXED_1;
1339
d6321d49 1340 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
6f43ed01 1341 fixed |= DR6_RTM;
e8ea85fb
CQ
1342
1343 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1344 fixed |= DR6_BUS_LOCK;
6f43ed01
NA
1345 return fixed;
1346}
1347
996ff542 1348int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
020df079 1349{
ea740059
MP
1350 size_t size = ARRAY_SIZE(vcpu->arch.db);
1351
020df079
GN
1352 switch (dr) {
1353 case 0 ... 3:
ea740059 1354 vcpu->arch.db[array_index_nospec(dr, size)] = val;
020df079
GN
1355 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1356 vcpu->arch.eff_db[dr] = val;
1357 break;
1358 case 4:
020df079 1359 case 6:
f5f6145e 1360 if (!kvm_dr6_valid(val))
996ff542 1361 return 1; /* #GP */
6f43ed01 1362 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
020df079
GN
1363 break;
1364 case 5:
020df079 1365 default: /* 7 */
b91991bf 1366 if (!kvm_dr7_valid(val))
996ff542 1367 return 1; /* #GP */
020df079 1368 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
c8639010 1369 kvm_update_dr7(vcpu);
020df079
GN
1370 break;
1371 }
1372
1373 return 0;
1374}
1375EXPORT_SYMBOL_GPL(kvm_set_dr);
1376
29d6ca41 1377void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
020df079 1378{
ea740059
MP
1379 size_t size = ARRAY_SIZE(vcpu->arch.db);
1380
020df079
GN
1381 switch (dr) {
1382 case 0 ... 3:
ea740059 1383 *val = vcpu->arch.db[array_index_nospec(dr, size)];
020df079
GN
1384 break;
1385 case 4:
020df079 1386 case 6:
5679b803 1387 *val = vcpu->arch.dr6;
020df079
GN
1388 break;
1389 case 5:
020df079
GN
1390 default: /* 7 */
1391 *val = vcpu->arch.dr7;
1392 break;
1393 }
338dbc97 1394}
020df079
GN
1395EXPORT_SYMBOL_GPL(kvm_get_dr);
1396
c483c454 1397int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
022cd0e8 1398{
de3cd117 1399 u32 ecx = kvm_rcx_read(vcpu);
022cd0e8 1400 u64 data;
022cd0e8 1401
c483c454
SC
1402 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1403 kvm_inject_gp(vcpu, 0);
1404 return 1;
1405 }
1406
de3cd117
SC
1407 kvm_rax_write(vcpu, (u32)data);
1408 kvm_rdx_write(vcpu, data >> 32);
c483c454 1409 return kvm_skip_emulated_instruction(vcpu);
022cd0e8 1410}
c483c454 1411EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
022cd0e8 1412
043405e1
CO
1413/*
1414 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1415 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1416 *
7a5ee6ed
CQ
1417 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1418 * extract the supported MSRs from the related const lists.
1419 * msrs_to_save is selected from the msrs_to_save_all to reflect the
e3267cbb 1420 * capabilities of the host cpu. This capabilities test skips MSRs that are
7a5ee6ed 1421 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
62ef68bb 1422 * may depend on host virtualization features rather than host cpu features.
043405e1 1423 */
e3267cbb 1424
7a5ee6ed 1425static const u32 msrs_to_save_all[] = {
043405e1 1426 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
8c06585d 1427 MSR_STAR,
043405e1
CO
1428#ifdef CONFIG_X86_64
1429 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1430#endif
b3897a49 1431 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
32ad73db 1432 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
2bdb76c0 1433 MSR_IA32_SPEC_CTRL,
bf8c55d8
CP
1434 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1435 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1436 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1437 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1438 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1439 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
6e3ba4ab
TX
1440 MSR_IA32_UMWAIT_CONTROL,
1441
e2ada66e 1442 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
9fb12fe5 1443 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
e2ada66e
JM
1444 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1445 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
4f1fa2a1
LX
1446 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
1447
1448 /* This part of MSRs should match KVM_INTEL_PMC_MAX_GENERIC. */
e2ada66e
JM
1449 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1450 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1451 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1452 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
e2ada66e
JM
1453 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1454 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1455 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1456 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
e1fc1553
FM
1457
1458 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1459 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
556f3c9a
LX
1460
1461 /* This part of MSRs should match KVM_AMD_PMC_MAX_GENERIC. */
e1fc1553
FM
1462 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1463 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1464 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1465 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
556f3c9a 1466
548e8365 1467 MSR_IA32_XFD, MSR_IA32_XFD_ERR,
043405e1
CO
1468};
1469
7a5ee6ed 1470static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
043405e1
CO
1471static unsigned num_msrs_to_save;
1472
7a5ee6ed 1473static const u32 emulated_msrs_all[] = {
62ef68bb
PB
1474 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1475 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1476 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1477 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
72c139ba 1478 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
e7d9513b
AS
1479 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1480 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
e516cebb 1481 HV_X64_MSR_RESET,
11c4b1ca 1482 HV_X64_MSR_VP_INDEX,
9eec50b8 1483 HV_X64_MSR_VP_RUNTIME,
5c919412 1484 HV_X64_MSR_SCONTROL,
1f4b34f8 1485 HV_X64_MSR_STIMER0_CONFIG,
d4abc577 1486 HV_X64_MSR_VP_ASSIST_PAGE,
a2e164e7
VK
1487 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1488 HV_X64_MSR_TSC_EMULATION_STATUS,
f97f5a56
JD
1489 HV_X64_MSR_SYNDBG_OPTIONS,
1490 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1491 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1492 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
a2e164e7
VK
1493
1494 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
557a961a 1495 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
62ef68bb 1496
ba904635 1497 MSR_IA32_TSC_ADJUST,
09141ec0 1498 MSR_IA32_TSC_DEADLINE,
2bdb76c0 1499 MSR_IA32_ARCH_CAPABILITIES,
27461da3 1500 MSR_IA32_PERF_CAPABILITIES,
043405e1 1501 MSR_IA32_MISC_ENABLE,
908e75f3
AK
1502 MSR_IA32_MCG_STATUS,
1503 MSR_IA32_MCG_CTL,
c45dcc71 1504 MSR_IA32_MCG_EXT_CTL,
64d60670 1505 MSR_IA32_SMBASE,
52797bf9 1506 MSR_SMI_COUNT,
db2336a8
KH
1507 MSR_PLATFORM_INFO,
1508 MSR_MISC_FEATURES_ENABLES,
bc226f07 1509 MSR_AMD64_VIRT_SPEC_CTRL,
5228eb96 1510 MSR_AMD64_TSC_RATIO,
6c6a2ab9 1511 MSR_IA32_POWER_CTL,
99634e3e 1512 MSR_IA32_UCODE_REV,
191c8137 1513
95c5c7c7
PB
1514 /*
1515 * The following list leaves out MSRs whose values are determined
1516 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1517 * We always support the "true" VMX control MSRs, even if the host
1518 * processor does not, so I am putting these registers here rather
7a5ee6ed 1519 * than in msrs_to_save_all.
95c5c7c7
PB
1520 */
1521 MSR_IA32_VMX_BASIC,
1522 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1523 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1524 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1525 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1526 MSR_IA32_VMX_MISC,
1527 MSR_IA32_VMX_CR0_FIXED0,
1528 MSR_IA32_VMX_CR4_FIXED0,
1529 MSR_IA32_VMX_VMCS_ENUM,
1530 MSR_IA32_VMX_PROCBASED_CTLS2,
1531 MSR_IA32_VMX_EPT_VPID_CAP,
1532 MSR_IA32_VMX_VMFUNC,
1533
191c8137 1534 MSR_K7_HWCR,
2d5ba19b 1535 MSR_KVM_POLL_CONTROL,
043405e1
CO
1536};
1537
7a5ee6ed 1538static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
62ef68bb
PB
1539static unsigned num_emulated_msrs;
1540
801e459a
TL
1541/*
1542 * List of msr numbers which are used to expose MSR-based features that
1543 * can be used by a hypervisor to validate requested CPU features.
1544 */
7a5ee6ed 1545static const u32 msr_based_features_all[] = {
1389309c
PB
1546 MSR_IA32_VMX_BASIC,
1547 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1548 MSR_IA32_VMX_PINBASED_CTLS,
1549 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1550 MSR_IA32_VMX_PROCBASED_CTLS,
1551 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1552 MSR_IA32_VMX_EXIT_CTLS,
1553 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1554 MSR_IA32_VMX_ENTRY_CTLS,
1555 MSR_IA32_VMX_MISC,
1556 MSR_IA32_VMX_CR0_FIXED0,
1557 MSR_IA32_VMX_CR0_FIXED1,
1558 MSR_IA32_VMX_CR4_FIXED0,
1559 MSR_IA32_VMX_CR4_FIXED1,
1560 MSR_IA32_VMX_VMCS_ENUM,
1561 MSR_IA32_VMX_PROCBASED_CTLS2,
1562 MSR_IA32_VMX_EPT_VPID_CAP,
1563 MSR_IA32_VMX_VMFUNC,
1564
d1d93fa9 1565 MSR_F10H_DECFG,
518e7b94 1566 MSR_IA32_UCODE_REV,
cd283252 1567 MSR_IA32_ARCH_CAPABILITIES,
27461da3 1568 MSR_IA32_PERF_CAPABILITIES,
801e459a
TL
1569};
1570
7a5ee6ed 1571static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
801e459a
TL
1572static unsigned int num_msr_based_features;
1573
0204750b
JM
1574/*
1575 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1576 * does not yet virtualize. These include:
1577 * 10 - MISC_PACKAGE_CTRLS
1578 * 11 - ENERGY_FILTERING_CTL
1579 * 12 - DOITM
1580 * 18 - FB_CLEAR_CTRL
1581 * 21 - XAPIC_DISABLE_STATUS
1582 * 23 - OVERCLOCKING_STATUS
1583 */
1584
1585#define KVM_SUPPORTED_ARCH_CAP \
1586 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1587 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1588 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1589 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1590 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO)
1591
4d22c17c 1592static u64 kvm_get_arch_capabilities(void)
5b76a3cf 1593{
4d22c17c 1594 u64 data = 0;
5b76a3cf 1595
0204750b 1596 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
4d22c17c 1597 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
0204750b
JM
1598 data &= KVM_SUPPORTED_ARCH_CAP;
1599 }
5b76a3cf 1600
b8e8c830
PB
1601 /*
1602 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1603 * the nested hypervisor runs with NX huge pages. If it is not,
d9f6e12f 1604 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
b8e8c830
PB
1605 * L1 guests, so it need not worry about its own (L2) guests.
1606 */
1607 data |= ARCH_CAP_PSCHANGE_MC_NO;
1608
5b76a3cf
PB
1609 /*
1610 * If we're doing cache flushes (either "always" or "cond")
1611 * we will do one whenever the guest does a vmlaunch/vmresume.
1612 * If an outer hypervisor is doing the cache flush for us
1613 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1614 * capability to the guest too, and if EPT is disabled we're not
1615 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1616 * require a nested hypervisor to do a flush of its own.
1617 */
1618 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1619 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1620
0c54914d
PB
1621 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1622 data |= ARCH_CAP_RDCL_NO;
1623 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1624 data |= ARCH_CAP_SSB_NO;
1625 if (!boot_cpu_has_bug(X86_BUG_MDS))
1626 data |= ARCH_CAP_MDS_NO;
1627
7131636e
PB
1628 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1629 /*
1630 * If RTM=0 because the kernel has disabled TSX, the host might
1631 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1632 * and therefore knows that there cannot be TAA) but keep
1633 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1634 * and we want to allow migrating those guests to tsx=off hosts.
1635 */
1636 data &= ~ARCH_CAP_TAA_NO;
1637 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
cbbaa272 1638 data |= ARCH_CAP_TAA_NO;
7131636e
PB
1639 } else {
1640 /*
1641 * Nothing to do here; we emulate TSX_CTRL if present on the
1642 * host so the guest can choose between disabling TSX or
1643 * using VERW to clear CPU buffers.
1644 */
1645 }
e1d38b63 1646
5b76a3cf
PB
1647 return data;
1648}
5b76a3cf 1649
66421c1e
WL
1650static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1651{
1652 switch (msr->index) {
cd283252 1653 case MSR_IA32_ARCH_CAPABILITIES:
5b76a3cf
PB
1654 msr->data = kvm_get_arch_capabilities();
1655 break;
5fe9805d
SC
1656 case MSR_IA32_PERF_CAPABILITIES:
1657 msr->data = kvm_caps.supported_perf_cap;
1658 break;
5b76a3cf 1659 case MSR_IA32_UCODE_REV:
cd283252 1660 rdmsrl_safe(msr->index, &msr->data);
518e7b94 1661 break;
66421c1e 1662 default:
b3646477 1663 return static_call(kvm_x86_get_msr_feature)(msr);
66421c1e
WL
1664 }
1665 return 0;
1666}
1667
801e459a
TL
1668static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1669{
1670 struct kvm_msr_entry msr;
66421c1e 1671 int r;
801e459a
TL
1672
1673 msr.index = index;
66421c1e 1674 r = kvm_get_msr_feature(&msr);
12bc2132
PX
1675
1676 if (r == KVM_MSR_RET_INVALID) {
1677 /* Unconditionally clear the output for simplicity */
1678 *data = 0;
d632826f 1679 if (kvm_msr_ignored_check(index, 0, false))
cc4cb017 1680 r = 0;
12bc2132
PX
1681 }
1682
66421c1e
WL
1683 if (r)
1684 return r;
801e459a
TL
1685
1686 *data = msr.data;
1687
1688 return 0;
1689}
1690
11988499 1691static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
15c4a640 1692{
1b4d56b8 1693 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
11988499 1694 return false;
1b2fd70c 1695
1b4d56b8 1696 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
11988499 1697 return false;
d8017474 1698
0a629563
SC
1699 if (efer & (EFER_LME | EFER_LMA) &&
1700 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1701 return false;
1702
1703 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1704 return false;
d8017474 1705
384bb783 1706 return true;
11988499
SC
1707
1708}
1709bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1710{
1711 if (efer & efer_reserved_bits)
1712 return false;
1713
1714 return __kvm_valid_efer(vcpu, efer);
384bb783
JK
1715}
1716EXPORT_SYMBOL_GPL(kvm_valid_efer);
1717
11988499 1718static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
384bb783
JK
1719{
1720 u64 old_efer = vcpu->arch.efer;
11988499 1721 u64 efer = msr_info->data;
72f211ec 1722 int r;
384bb783 1723
11988499 1724 if (efer & efer_reserved_bits)
66f61c92 1725 return 1;
384bb783 1726
11988499
SC
1727 if (!msr_info->host_initiated) {
1728 if (!__kvm_valid_efer(vcpu, efer))
1729 return 1;
1730
1731 if (is_paging(vcpu) &&
1732 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1733 return 1;
1734 }
384bb783 1735
15c4a640 1736 efer &= ~EFER_LMA;
f6801dff 1737 efer |= vcpu->arch.efer & EFER_LMA;
15c4a640 1738
b3646477 1739 r = static_call(kvm_x86_set_efer)(vcpu, efer);
72f211ec
ML
1740 if (r) {
1741 WARN_ON(r > 0);
1742 return r;
1743 }
a3d204e2 1744
d6174299 1745 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
aad82703
SY
1746 kvm_mmu_reset_context(vcpu);
1747
b69e8cae 1748 return 0;
15c4a640
CO
1749}
1750
f2b4b7dd
JR
1751void kvm_enable_efer_bits(u64 mask)
1752{
1753 efer_reserved_bits &= ~mask;
1754}
1755EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1756
51de8151
AG
1757bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1758{
b318e8de
SC
1759 struct kvm_x86_msr_filter *msr_filter;
1760 struct msr_bitmap_range *ranges;
1a155254 1761 struct kvm *kvm = vcpu->kvm;
b318e8de 1762 bool allowed;
1a155254 1763 int idx;
b318e8de 1764 u32 i;
1a155254 1765
b318e8de
SC
1766 /* x2APIC MSRs do not support filtering. */
1767 if (index >= 0x800 && index <= 0x8ff)
1a155254
AG
1768 return true;
1769
1a155254
AG
1770 idx = srcu_read_lock(&kvm->srcu);
1771
b318e8de
SC
1772 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1773 if (!msr_filter) {
1774 allowed = true;
1775 goto out;
1776 }
1777
1778 allowed = msr_filter->default_allow;
1779 ranges = msr_filter->ranges;
1780
1781 for (i = 0; i < msr_filter->count; i++) {
1a155254
AG
1782 u32 start = ranges[i].base;
1783 u32 end = start + ranges[i].nmsrs;
1784 u32 flags = ranges[i].flags;
1785 unsigned long *bitmap = ranges[i].bitmap;
1786
1787 if ((index >= start) && (index < end) && (flags & type)) {
b318e8de 1788 allowed = !!test_bit(index - start, bitmap);
1a155254
AG
1789 break;
1790 }
1791 }
1792
b318e8de 1793out:
1a155254
AG
1794 srcu_read_unlock(&kvm->srcu, idx);
1795
b318e8de 1796 return allowed;
51de8151
AG
1797}
1798EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1799
15c4a640 1800/*
f20935d8
SC
1801 * Write @data into the MSR specified by @index. Select MSR specific fault
1802 * checks are bypassed if @host_initiated is %true.
15c4a640
CO
1803 * Returns 0 on success, non-0 otherwise.
1804 * Assumes vcpu_load() was already called.
1805 */
f20935d8
SC
1806static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1807 bool host_initiated)
15c4a640 1808{
f20935d8
SC
1809 struct msr_data msr;
1810
1811 switch (index) {
854e8bb1
NA
1812 case MSR_FS_BASE:
1813 case MSR_GS_BASE:
1814 case MSR_KERNEL_GS_BASE:
1815 case MSR_CSTAR:
1816 case MSR_LSTAR:
f20935d8 1817 if (is_noncanonical_address(data, vcpu))
854e8bb1
NA
1818 return 1;
1819 break;
1820 case MSR_IA32_SYSENTER_EIP:
1821 case MSR_IA32_SYSENTER_ESP:
1822 /*
1823 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1824 * non-canonical address is written on Intel but not on
1825 * AMD (which ignores the top 32-bits, because it does
1826 * not implement 64-bit SYSENTER).
1827 *
1828 * 64-bit code should hence be able to write a non-canonical
1829 * value on AMD. Making the address canonical ensures that
1830 * vmentry does not fail on Intel after writing a non-canonical
1831 * value, and that something deterministic happens if the guest
1832 * invokes 64-bit SYSENTER.
1833 */
1fb85d06 1834 data = __canonical_address(data, vcpu_virt_addr_bits(vcpu));
61a05d44
SC
1835 break;
1836 case MSR_TSC_AUX:
1837 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1838 return 1;
1839
1840 if (!host_initiated &&
1841 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1842 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1843 return 1;
1844
1845 /*
1846 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1847 * incomplete and conflicting architectural behavior. Current
1848 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1849 * reserved and always read as zeros. Enforce Intel's reserved
1850 * bits check if and only if the guest CPU is Intel, and clear
1851 * the bits in all other cases. This ensures cross-vendor
1852 * migration will provide consistent behavior for the guest.
1853 */
1854 if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
1855 return 1;
1856
1857 data = (u32)data;
1858 break;
854e8bb1 1859 }
f20935d8
SC
1860
1861 msr.data = data;
1862 msr.index = index;
1863 msr.host_initiated = host_initiated;
1864
b3646477 1865 return static_call(kvm_x86_set_msr)(vcpu, &msr);
15c4a640
CO
1866}
1867
6abe9c13
PX
1868static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1869 u32 index, u64 data, bool host_initiated)
1870{
1871 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1872
1873 if (ret == KVM_MSR_RET_INVALID)
d632826f 1874 if (kvm_msr_ignored_check(index, data, true))
cc4cb017 1875 ret = 0;
6abe9c13
PX
1876
1877 return ret;
1878}
1879
313a3dc7 1880/*
f20935d8
SC
1881 * Read the MSR specified by @index into @data. Select MSR specific fault
1882 * checks are bypassed if @host_initiated is %true.
1883 * Returns 0 on success, non-0 otherwise.
1884 * Assumes vcpu_load() was already called.
313a3dc7 1885 */
edef5c36
PB
1886int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1887 bool host_initiated)
609e36d3
PB
1888{
1889 struct msr_data msr;
f20935d8 1890 int ret;
609e36d3 1891
61a05d44
SC
1892 switch (index) {
1893 case MSR_TSC_AUX:
1894 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1895 return 1;
1896
1897 if (!host_initiated &&
1898 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1899 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1900 return 1;
1901 break;
1902 }
1903
609e36d3 1904 msr.index = index;
f20935d8 1905 msr.host_initiated = host_initiated;
609e36d3 1906
b3646477 1907 ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
f20935d8
SC
1908 if (!ret)
1909 *data = msr.data;
1910 return ret;
609e36d3
PB
1911}
1912
6abe9c13
PX
1913static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1914 u32 index, u64 *data, bool host_initiated)
1915{
1916 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1917
1918 if (ret == KVM_MSR_RET_INVALID) {
1919 /* Unconditionally clear *data for simplicity */
1920 *data = 0;
d632826f 1921 if (kvm_msr_ignored_check(index, 0, false))
cc4cb017 1922 ret = 0;
6abe9c13
PX
1923 }
1924
1925 return ret;
1926}
1927
ac8d6cad
HW
1928static int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1929{
1930 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1931 return KVM_MSR_RET_FILTERED;
1932 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1933}
1934
1935static int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1936{
1937 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1938 return KVM_MSR_RET_FILTERED;
1939 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1940}
1941
f20935d8 1942int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
313a3dc7 1943{
6abe9c13 1944 return kvm_get_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1945}
1946EXPORT_SYMBOL_GPL(kvm_get_msr);
8fe8ab46 1947
f20935d8
SC
1948int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1949{
6abe9c13 1950 return kvm_set_msr_ignored_check(vcpu, index, data, false);
f20935d8
SC
1951}
1952EXPORT_SYMBOL_GPL(kvm_set_msr);
1953
d2f7d498 1954static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1ae09954 1955{
d2f7d498 1956 if (!vcpu->run->msr.error) {
1ae09954
AG
1957 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1958 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1959 }
d2f7d498 1960}
1ae09954 1961
d2f7d498
HW
1962static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1963{
1964 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1ae09954
AG
1965}
1966
d2f7d498
HW
1967static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1968{
1969 complete_userspace_rdmsr(vcpu);
1970 return complete_emulated_msr_access(vcpu);
1971}
1972
1973static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1ae09954 1974{
b3646477 1975 return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1ae09954
AG
1976}
1977
d2f7d498
HW
1978static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1979{
1980 complete_userspace_rdmsr(vcpu);
1981 return complete_fast_msr_access(vcpu);
1982}
1983
1ae09954
AG
1984static u64 kvm_msr_reason(int r)
1985{
1986 switch (r) {
cc4cb017 1987 case KVM_MSR_RET_INVALID:
1ae09954 1988 return KVM_MSR_EXIT_REASON_UNKNOWN;
cc4cb017 1989 case KVM_MSR_RET_FILTERED:
1a155254 1990 return KVM_MSR_EXIT_REASON_FILTER;
1ae09954
AG
1991 default:
1992 return KVM_MSR_EXIT_REASON_INVAL;
1993 }
1994}
1995
1996static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1997 u32 exit_reason, u64 data,
1998 int (*completion)(struct kvm_vcpu *vcpu),
1999 int r)
2000{
2001 u64 msr_reason = kvm_msr_reason(r);
2002
2003 /* Check if the user wanted to know about this MSR fault */
2004 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2005 return 0;
2006
2007 vcpu->run->exit_reason = exit_reason;
2008 vcpu->run->msr.error = 0;
2009 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2010 vcpu->run->msr.reason = msr_reason;
2011 vcpu->run->msr.index = index;
2012 vcpu->run->msr.data = data;
2013 vcpu->arch.complete_userspace_io = completion;
2014
2015 return 1;
2016}
2017
1edce0a9
SC
2018int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2019{
2020 u32 ecx = kvm_rcx_read(vcpu);
2021 u64 data;
1ae09954
AG
2022 int r;
2023
ac8d6cad 2024 r = kvm_get_msr_with_filter(vcpu, ecx, &data);
1edce0a9 2025
8b474427
PB
2026 if (!r) {
2027 trace_kvm_msr_read(ecx, data);
2028
2029 kvm_rax_write(vcpu, data & -1u);
2030 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2031 } else {
d2f7d498
HW
2032 /* MSR read failed? See if we should ask user space */
2033 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2034 complete_fast_rdmsr, r))
2035 return 0;
1edce0a9 2036 trace_kvm_msr_read_ex(ecx);
1edce0a9
SC
2037 }
2038
b3646477 2039 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1edce0a9
SC
2040}
2041EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2042
2043int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2044{
2045 u32 ecx = kvm_rcx_read(vcpu);
2046 u64 data = kvm_read_edx_eax(vcpu);
1ae09954 2047 int r;
1edce0a9 2048
ac8d6cad 2049 r = kvm_set_msr_with_filter(vcpu, ecx, data);
1ae09954 2050
d2f7d498 2051 if (!r) {
8b474427 2052 trace_kvm_msr_write(ecx, data);
d2f7d498
HW
2053 } else {
2054 /* MSR write failed? See if we should ask user space */
2055 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2056 complete_fast_msr_access, r))
2057 return 0;
2058 /* Signal all other negative errors to userspace */
2059 if (r < 0)
2060 return r;
1edce0a9 2061 trace_kvm_msr_write_ex(ecx, data);
d2f7d498 2062 }
1edce0a9 2063
b3646477 2064 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
1edce0a9
SC
2065}
2066EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2067
5ff3a351
SC
2068int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2069{
2070 return kvm_skip_emulated_instruction(vcpu);
2071}
2072EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
2073
2074int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2075{
2076 /* Treat an INVD instruction as a NOP and just skip it. */
2077 return kvm_emulate_as_nop(vcpu);
2078}
2079EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2080
5ff3a351
SC
2081int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2082{
2083 kvm_queue_exception(vcpu, UD_VECTOR);
2084 return 1;
2085}
2086EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2087
bfbcc81b
SC
2088
2089static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
5ff3a351 2090{
43bb9e00 2091 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS) &&
bfbcc81b
SC
2092 !guest_cpuid_has(vcpu, X86_FEATURE_MWAIT))
2093 return kvm_handle_invalid_op(vcpu);
2094
2095 pr_warn_once("kvm: %s instruction emulated as NOP!\n", insn);
5ff3a351
SC
2096 return kvm_emulate_as_nop(vcpu);
2097}
bfbcc81b
SC
2098int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2099{
2100 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2101}
2102EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2103
2104int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2105{
2106 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2107}
5ff3a351
SC
2108EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2109
d89d04ab 2110static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
5a9f5443 2111{
4ae7dc97 2112 xfer_to_guest_mode_prepare();
5a9f5443 2113 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
72c3c0fe 2114 xfer_to_guest_mode_work_pending();
5a9f5443 2115}
5a9f5443 2116
1e9e2622
WL
2117/*
2118 * The fast path for frequent and performance sensitive wrmsr emulation,
2119 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2120 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2121 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2122 * other cases which must be called after interrupts are enabled on the host.
2123 */
2124static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2125{
e1be9ac8
WL
2126 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2127 return 1;
2128
2129 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
bd17f417
SC
2130 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2131 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
b9964ee3
SC
2132 ((u32)(data >> 32) != X2APIC_BROADCAST))
2133 return kvm_x2apic_icr_write(vcpu->arch.apic, data);
1e9e2622
WL
2134
2135 return 1;
2136}
2137
ae95f566
WL
2138static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2139{
2140 if (!kvm_can_use_hv_timer(vcpu))
2141 return 1;
2142
2143 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2144 return 0;
2145}
2146
404d5d7b 2147fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1e9e2622
WL
2148{
2149 u32 msr = kvm_rcx_read(vcpu);
8a1038de 2150 u64 data;
404d5d7b 2151 fastpath_t ret = EXIT_FASTPATH_NONE;
1e9e2622
WL
2152
2153 switch (msr) {
2154 case APIC_BASE_MSR + (APIC_ICR >> 4):
8a1038de 2155 data = kvm_read_edx_eax(vcpu);
404d5d7b
WL
2156 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
2157 kvm_skip_emulated_instruction(vcpu);
2158 ret = EXIT_FASTPATH_EXIT_HANDLED;
80bc97f2 2159 }
1e9e2622 2160 break;
09141ec0 2161 case MSR_IA32_TSC_DEADLINE:
ae95f566
WL
2162 data = kvm_read_edx_eax(vcpu);
2163 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
2164 kvm_skip_emulated_instruction(vcpu);
2165 ret = EXIT_FASTPATH_REENTER_GUEST;
2166 }
2167 break;
1e9e2622 2168 default:
404d5d7b 2169 break;
1e9e2622
WL
2170 }
2171
404d5d7b 2172 if (ret != EXIT_FASTPATH_NONE)
1e9e2622 2173 trace_kvm_msr_write(msr, data);
1e9e2622 2174
404d5d7b 2175 return ret;
1e9e2622
WL
2176}
2177EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2178
f20935d8
SC
2179/*
2180 * Adapt set_msr() to msr_io()'s calling convention
2181 */
2182static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2183{
6abe9c13 2184 return kvm_get_msr_ignored_check(vcpu, index, data, true);
f20935d8
SC
2185}
2186
2187static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2188{
6abe9c13 2189 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
313a3dc7
CO
2190}
2191
16e8d74d 2192#ifdef CONFIG_X86_64
53fafdbb
MT
2193struct pvclock_clock {
2194 int vclock_mode;
2195 u64 cycle_last;
2196 u64 mask;
2197 u32 mult;
2198 u32 shift;
917f9475
PB
2199 u64 base_cycles;
2200 u64 offset;
53fafdbb
MT
2201};
2202
16e8d74d
MT
2203struct pvclock_gtod_data {
2204 seqcount_t seq;
2205
53fafdbb
MT
2206 struct pvclock_clock clock; /* extract of a clocksource struct */
2207 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
16e8d74d 2208
917f9475 2209 ktime_t offs_boot;
55dd00a7 2210 u64 wall_time_sec;
16e8d74d
MT
2211};
2212
2213static struct pvclock_gtod_data pvclock_gtod_data;
2214
2215static void update_pvclock_gtod(struct timekeeper *tk)
2216{
2217 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2218
2219 write_seqcount_begin(&vdata->seq);
2220
2221 /* copy pvclock gtod data */
b95a8a27 2222 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
876e7881
PZ
2223 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2224 vdata->clock.mask = tk->tkr_mono.mask;
2225 vdata->clock.mult = tk->tkr_mono.mult;
2226 vdata->clock.shift = tk->tkr_mono.shift;
917f9475
PB
2227 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2228 vdata->clock.offset = tk->tkr_mono.base;
16e8d74d 2229
b95a8a27 2230 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
53fafdbb
MT
2231 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2232 vdata->raw_clock.mask = tk->tkr_raw.mask;
2233 vdata->raw_clock.mult = tk->tkr_raw.mult;
2234 vdata->raw_clock.shift = tk->tkr_raw.shift;
917f9475
PB
2235 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2236 vdata->raw_clock.offset = tk->tkr_raw.base;
16e8d74d 2237
55dd00a7
MT
2238 vdata->wall_time_sec = tk->xtime_sec;
2239
917f9475 2240 vdata->offs_boot = tk->offs_boot;
53fafdbb 2241
16e8d74d
MT
2242 write_seqcount_end(&vdata->seq);
2243}
8171cd68
PB
2244
2245static s64 get_kvmclock_base_ns(void)
2246{
2247 /* Count up from boot time, but with the frequency of the raw clock. */
2248 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2249}
2250#else
2251static s64 get_kvmclock_base_ns(void)
2252{
2253 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2254 return ktime_get_boottime_ns();
2255}
16e8d74d
MT
2256#endif
2257
55749769 2258static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
18068523 2259{
9ed3c444
AK
2260 int version;
2261 int r;
50d0a0f9 2262 struct pvclock_wall_clock wc;
629b5348 2263 u32 wc_sec_hi;
8171cd68 2264 u64 wall_nsec;
18068523
GOC
2265
2266 if (!wall_clock)
2267 return;
2268
9ed3c444
AK
2269 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2270 if (r)
2271 return;
2272
2273 if (version & 1)
2274 ++version; /* first time write, random junk */
2275
2276 ++version;
18068523 2277
1dab1345
NK
2278 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2279 return;
18068523 2280
50d0a0f9
GH
2281 /*
2282 * The guest calculates current wall clock time by adding
34c238a1 2283 * system time (updated by kvm_guest_time_update below) to the
8171cd68 2284 * wall clock specified here. We do the reverse here.
50d0a0f9 2285 */
8171cd68 2286 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
50d0a0f9 2287
8171cd68
PB
2288 wc.nsec = do_div(wall_nsec, 1000000000);
2289 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
50d0a0f9 2290 wc.version = version;
18068523
GOC
2291
2292 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2293
629b5348
JM
2294 if (sec_hi_ofs) {
2295 wc_sec_hi = wall_nsec >> 32;
2296 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2297 &wc_sec_hi, sizeof(wc_sec_hi));
2298 }
2299
18068523
GOC
2300 version++;
2301 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
18068523
GOC
2302}
2303
5b9bb0eb
OU
2304static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2305 bool old_msr, bool host_initiated)
2306{
2307 struct kvm_arch *ka = &vcpu->kvm->arch;
2308
2309 if (vcpu->vcpu_id == 0 && !host_initiated) {
1e293d1a 2310 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
5b9bb0eb
OU
2311 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2312
2313 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2314 }
2315
2316 vcpu->arch.time = system_time;
2317 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2318
2319 /* we verify if the enable bit is set... */
916d3608 2320 if (system_time & 1) {
52491a38
ML
2321 kvm_gpc_activate(vcpu->kvm, &vcpu->arch.pv_time, vcpu,
2322 KVM_HOST_USES_PFN, system_time & ~1ULL,
2323 sizeof(struct pvclock_vcpu_time_info));
916d3608 2324 } else {
52491a38 2325 kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
916d3608 2326 }
5b9bb0eb
OU
2327
2328 return;
2329}
2330
50d0a0f9
GH
2331static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2332{
b51012de
PB
2333 do_shl32_div32(dividend, divisor);
2334 return dividend;
50d0a0f9
GH
2335}
2336
3ae13faa 2337static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
5f4e3f88 2338 s8 *pshift, u32 *pmultiplier)
50d0a0f9 2339{
5f4e3f88 2340 uint64_t scaled64;
50d0a0f9
GH
2341 int32_t shift = 0;
2342 uint64_t tps64;
2343 uint32_t tps32;
2344
3ae13faa
PB
2345 tps64 = base_hz;
2346 scaled64 = scaled_hz;
50933623 2347 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
50d0a0f9
GH
2348 tps64 >>= 1;
2349 shift--;
2350 }
2351
2352 tps32 = (uint32_t)tps64;
50933623
JK
2353 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2354 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
5f4e3f88
ZA
2355 scaled64 >>= 1;
2356 else
2357 tps32 <<= 1;
50d0a0f9
GH
2358 shift++;
2359 }
2360
5f4e3f88
ZA
2361 *pshift = shift;
2362 *pmultiplier = div_frac(scaled64, tps32);
50d0a0f9
GH
2363}
2364
d828199e 2365#ifdef CONFIG_X86_64
16e8d74d 2366static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
d828199e 2367#endif
16e8d74d 2368
c8076604 2369static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
69b0049a 2370static unsigned long max_tsc_khz;
c8076604 2371
cc578287 2372static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1e993611 2373{
cc578287
ZA
2374 u64 v = (u64)khz * (1000000 + ppm);
2375 do_div(v, 1000000);
2376 return v;
1e993611
JR
2377}
2378
1ab9287a
IS
2379static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2380
381d585c
HZ
2381static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2382{
2383 u64 ratio;
2384
2385 /* Guest TSC same frequency as host TSC? */
2386 if (!scale) {
938c8745 2387 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
381d585c
HZ
2388 return 0;
2389 }
2390
2391 /* TSC scaling supported? */
938c8745 2392 if (!kvm_caps.has_tsc_control) {
381d585c
HZ
2393 if (user_tsc_khz > tsc_khz) {
2394 vcpu->arch.tsc_catchup = 1;
2395 vcpu->arch.tsc_always_catchup = 1;
2396 return 0;
2397 } else {
3f16a5c3 2398 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
381d585c
HZ
2399 return -1;
2400 }
2401 }
2402
2403 /* TSC scaling required - calculate ratio */
938c8745 2404 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
381d585c
HZ
2405 user_tsc_khz, tsc_khz);
2406
938c8745 2407 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
3f16a5c3
PB
2408 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2409 user_tsc_khz);
381d585c
HZ
2410 return -1;
2411 }
2412
1ab9287a 2413 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
381d585c
HZ
2414 return 0;
2415}
2416
4941b8cb 2417static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
759379dd 2418{
cc578287
ZA
2419 u32 thresh_lo, thresh_hi;
2420 int use_scaling = 0;
217fc9cf 2421
03ba32ca 2422 /* tsc_khz can be zero if TSC calibration fails */
4941b8cb 2423 if (user_tsc_khz == 0) {
ad721883 2424 /* set tsc_scaling_ratio to a safe value */
938c8745 2425 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
381d585c 2426 return -1;
ad721883 2427 }
03ba32ca 2428
c285545f 2429 /* Compute a scale to convert nanoseconds in TSC cycles */
3ae13faa 2430 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
cc578287
ZA
2431 &vcpu->arch.virtual_tsc_shift,
2432 &vcpu->arch.virtual_tsc_mult);
4941b8cb 2433 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
cc578287
ZA
2434
2435 /*
2436 * Compute the variation in TSC rate which is acceptable
2437 * within the range of tolerance and decide if the
2438 * rate being applied is within that bounds of the hardware
2439 * rate. If so, no scaling or compensation need be done.
2440 */
2441 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2442 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
4941b8cb
PB
2443 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2444 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
cc578287
ZA
2445 use_scaling = 1;
2446 }
4941b8cb 2447 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
c285545f
ZA
2448}
2449
2450static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2451{
e26101b1 2452 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
cc578287
ZA
2453 vcpu->arch.virtual_tsc_mult,
2454 vcpu->arch.virtual_tsc_shift);
e26101b1 2455 tsc += vcpu->arch.this_tsc_write;
c285545f
ZA
2456 return tsc;
2457}
2458
ba1f77c5 2459#ifdef CONFIG_X86_64
b0c39dc6
VK
2460static inline int gtod_is_based_on_tsc(int mode)
2461{
b95a8a27 2462 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
b0c39dc6 2463}
ba1f77c5 2464#endif
b0c39dc6 2465
69b0049a 2466static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
b48aa97e
MT
2467{
2468#ifdef CONFIG_X86_64
2469 bool vcpus_matched;
b48aa97e
MT
2470 struct kvm_arch *ka = &vcpu->kvm->arch;
2471 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2472
2473 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2474 atomic_read(&vcpu->kvm->online_vcpus));
2475
7f187922
MT
2476 /*
2477 * Once the masterclock is enabled, always perform request in
2478 * order to update it.
2479 *
2480 * In order to enable masterclock, the host clocksource must be TSC
2481 * and the vcpus need to have matched TSCs. When that happens,
2482 * perform request to enable masterclock.
2483 */
2484 if (ka->use_master_clock ||
b0c39dc6 2485 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
b48aa97e
MT
2486 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2487
2488 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2489 atomic_read(&vcpu->kvm->online_vcpus),
2490 ka->use_master_clock, gtod->clock.vclock_mode);
2491#endif
2492}
2493
35181e86
HZ
2494/*
2495 * Multiply tsc by a fixed point number represented by ratio.
2496 *
2497 * The most significant 64-N bits (mult) of ratio represent the
2498 * integral part of the fixed point number; the remaining N bits
2499 * (frac) represent the fractional part, ie. ratio represents a fixed
2500 * point number (mult + frac * 2^(-N)).
2501 *
938c8745 2502 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
35181e86
HZ
2503 */
2504static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2505{
938c8745 2506 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
35181e86
HZ
2507}
2508
62711e5a 2509u64 kvm_scale_tsc(u64 tsc, u64 ratio)
35181e86
HZ
2510{
2511 u64 _tsc = tsc;
35181e86 2512
938c8745 2513 if (ratio != kvm_caps.default_tsc_scaling_ratio)
35181e86
HZ
2514 _tsc = __scale_tsc(ratio, tsc);
2515
2516 return _tsc;
2517}
2518EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2519
9b399dfd 2520static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
07c1419a
HZ
2521{
2522 u64 tsc;
2523
62711e5a 2524 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
07c1419a
HZ
2525
2526 return target_tsc - tsc;
2527}
2528
4ba76538
HZ
2529u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2530{
fe3eb504 2531 return vcpu->arch.l1_tsc_offset +
62711e5a 2532 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
4ba76538
HZ
2533}
2534EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2535
83150f29
IS
2536u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2537{
2538 u64 nested_offset;
2539
938c8745 2540 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
83150f29
IS
2541 nested_offset = l1_offset;
2542 else
2543 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
938c8745 2544 kvm_caps.tsc_scaling_ratio_frac_bits);
83150f29
IS
2545
2546 nested_offset += l2_offset;
2547 return nested_offset;
2548}
2549EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2550
2551u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2552{
938c8745 2553 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
83150f29 2554 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
938c8745 2555 kvm_caps.tsc_scaling_ratio_frac_bits);
83150f29
IS
2556
2557 return l1_multiplier;
2558}
2559EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2560
edcfe540 2561static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
a545ab6a 2562{
edcfe540
IS
2563 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2564 vcpu->arch.l1_tsc_offset,
2565 l1_offset);
2566
2567 vcpu->arch.l1_tsc_offset = l1_offset;
2568
2569 /*
2570 * If we are here because L1 chose not to trap WRMSR to TSC then
2571 * according to the spec this should set L1's TSC (as opposed to
2572 * setting L1's offset for L2).
2573 */
2574 if (is_guest_mode(vcpu))
2575 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2576 l1_offset,
2577 static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
2578 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2579 else
2580 vcpu->arch.tsc_offset = l1_offset;
2581
2582 static_call(kvm_x86_write_tsc_offset)(vcpu, vcpu->arch.tsc_offset);
a545ab6a
LC
2583}
2584
1ab9287a
IS
2585static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2586{
2587 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2588
2589 /* Userspace is changing the multiplier while L2 is active */
2590 if (is_guest_mode(vcpu))
2591 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2592 l1_multiplier,
2593 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2594 else
2595 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2596
938c8745 2597 if (kvm_caps.has_tsc_control)
1ab9287a
IS
2598 static_call(kvm_x86_write_tsc_multiplier)(
2599 vcpu, vcpu->arch.tsc_scaling_ratio);
2600}
2601
b0c39dc6
VK
2602static inline bool kvm_check_tsc_unstable(void)
2603{
2604#ifdef CONFIG_X86_64
2605 /*
2606 * TSC is marked unstable when we're running on Hyper-V,
2607 * 'TSC page' clocksource is good.
2608 */
b95a8a27 2609 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
b0c39dc6
VK
2610 return false;
2611#endif
2612 return check_tsc_unstable();
2613}
2614
58d4277b
OU
2615/*
2616 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2617 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2618 * participates in.
2619 */
2620static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2621 u64 ns, bool matched)
2622{
2623 struct kvm *kvm = vcpu->kvm;
2624
2625 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2626
2627 /*
2628 * We also track th most recent recorded KHZ, write and time to
2629 * allow the matching interval to be extended at each write.
2630 */
2631 kvm->arch.last_tsc_nsec = ns;
2632 kvm->arch.last_tsc_write = tsc;
2633 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
828ca896 2634 kvm->arch.last_tsc_offset = offset;
58d4277b
OU
2635
2636 vcpu->arch.last_guest_tsc = tsc;
2637
2638 kvm_vcpu_write_tsc_offset(vcpu, offset);
2639
2640 if (!matched) {
2641 /*
2642 * We split periods of matched TSC writes into generations.
2643 * For each generation, we track the original measured
2644 * nanosecond time, offset, and write, so if TSCs are in
2645 * sync, we can match exact offset, and if not, we can match
2646 * exact software computation in compute_guest_tsc()
2647 *
2648 * These values are tracked in kvm->arch.cur_xxx variables.
2649 */
2650 kvm->arch.cur_tsc_generation++;
2651 kvm->arch.cur_tsc_nsec = ns;
2652 kvm->arch.cur_tsc_write = tsc;
2653 kvm->arch.cur_tsc_offset = offset;
2654 kvm->arch.nr_vcpus_matched_tsc = 0;
2655 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2656 kvm->arch.nr_vcpus_matched_tsc++;
2657 }
2658
2659 /* Keep track of which generation this VCPU has synchronized to */
2660 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2661 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2662 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2663
2664 kvm_track_tsc_matching(vcpu);
2665}
2666
0c899c25 2667static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
99e3e30a
ZA
2668{
2669 struct kvm *kvm = vcpu->kvm;
f38e098f 2670 u64 offset, ns, elapsed;
99e3e30a 2671 unsigned long flags;
58d4277b 2672 bool matched = false;
c5e8ec8e 2673 bool synchronizing = false;
99e3e30a 2674
038f8c11 2675 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
9b399dfd 2676 offset = kvm_compute_l1_tsc_offset(vcpu, data);
8171cd68 2677 ns = get_kvmclock_base_ns();
f38e098f 2678 elapsed = ns - kvm->arch.last_tsc_nsec;
5d3cb0f6 2679
03ba32ca 2680 if (vcpu->arch.virtual_tsc_khz) {
0c899c25 2681 if (data == 0) {
bd8fab39
DP
2682 /*
2683 * detection of vcpu initialization -- need to sync
2684 * with other vCPUs. This particularly helps to keep
2685 * kvm_clock stable after CPU hotplug
2686 */
2687 synchronizing = true;
2688 } else {
2689 u64 tsc_exp = kvm->arch.last_tsc_write +
2690 nsec_to_cycles(vcpu, elapsed);
2691 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2692 /*
2693 * Special case: TSC write with a small delta (1 second)
2694 * of virtual cycle time against real time is
2695 * interpreted as an attempt to synchronize the CPU.
2696 */
2697 synchronizing = data < tsc_exp + tsc_hz &&
2698 data + tsc_hz > tsc_exp;
2699 }
c5e8ec8e 2700 }
f38e098f
ZA
2701
2702 /*
5d3cb0f6
ZA
2703 * For a reliable TSC, we can match TSC offsets, and for an unstable
2704 * TSC, we add elapsed time in this computation. We could let the
2705 * compensation code attempt to catch up if we fall behind, but
2706 * it's better to try to match offsets from the beginning.
2707 */
c5e8ec8e 2708 if (synchronizing &&
5d3cb0f6 2709 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
b0c39dc6 2710 if (!kvm_check_tsc_unstable()) {
e26101b1 2711 offset = kvm->arch.cur_tsc_offset;
f38e098f 2712 } else {
857e4099 2713 u64 delta = nsec_to_cycles(vcpu, elapsed);
5d3cb0f6 2714 data += delta;
9b399dfd 2715 offset = kvm_compute_l1_tsc_offset(vcpu, data);
f38e098f 2716 }
b48aa97e 2717 matched = true;
f38e098f 2718 }
e26101b1 2719
58d4277b 2720 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
e26101b1 2721 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
99e3e30a 2722}
e26101b1 2723
58ea6767
HZ
2724static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2725 s64 adjustment)
2726{
56ba77a4 2727 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
326e7425 2728 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
58ea6767
HZ
2729}
2730
2731static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2732{
938c8745 2733 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
58ea6767 2734 WARN_ON(adjustment < 0);
62711e5a 2735 adjustment = kvm_scale_tsc((u64) adjustment,
fe3eb504 2736 vcpu->arch.l1_tsc_scaling_ratio);
ea26e4ec 2737 adjust_tsc_offset_guest(vcpu, adjustment);
58ea6767
HZ
2738}
2739
d828199e
MT
2740#ifdef CONFIG_X86_64
2741
a5a1d1c2 2742static u64 read_tsc(void)
d828199e 2743{
a5a1d1c2 2744 u64 ret = (u64)rdtsc_ordered();
03b9730b 2745 u64 last = pvclock_gtod_data.clock.cycle_last;
d828199e
MT
2746
2747 if (likely(ret >= last))
2748 return ret;
2749
2750 /*
2751 * GCC likes to generate cmov here, but this branch is extremely
6a6256f9 2752 * predictable (it's just a function of time and the likely is
d828199e
MT
2753 * very likely) and there's a data dependence, so force GCC
2754 * to generate a branch instead. I don't barrier() because
2755 * we don't actually need a barrier, and if this function
2756 * ever gets inlined it will generate worse code.
2757 */
2758 asm volatile ("");
2759 return last;
2760}
2761
53fafdbb
MT
2762static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2763 int *mode)
d828199e
MT
2764{
2765 long v;
b0c39dc6
VK
2766 u64 tsc_pg_val;
2767
53fafdbb 2768 switch (clock->vclock_mode) {
b95a8a27 2769 case VDSO_CLOCKMODE_HVCLOCK:
b0c39dc6
VK
2770 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2771 tsc_timestamp);
2772 if (tsc_pg_val != U64_MAX) {
2773 /* TSC page valid */
b95a8a27 2774 *mode = VDSO_CLOCKMODE_HVCLOCK;
53fafdbb
MT
2775 v = (tsc_pg_val - clock->cycle_last) &
2776 clock->mask;
b0c39dc6
VK
2777 } else {
2778 /* TSC page invalid */
b95a8a27 2779 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6
VK
2780 }
2781 break;
b95a8a27
TG
2782 case VDSO_CLOCKMODE_TSC:
2783 *mode = VDSO_CLOCKMODE_TSC;
b0c39dc6 2784 *tsc_timestamp = read_tsc();
53fafdbb
MT
2785 v = (*tsc_timestamp - clock->cycle_last) &
2786 clock->mask;
b0c39dc6
VK
2787 break;
2788 default:
b95a8a27 2789 *mode = VDSO_CLOCKMODE_NONE;
b0c39dc6 2790 }
d828199e 2791
b95a8a27 2792 if (*mode == VDSO_CLOCKMODE_NONE)
b0c39dc6 2793 *tsc_timestamp = v = 0;
d828199e 2794
53fafdbb 2795 return v * clock->mult;
d828199e
MT
2796}
2797
53fafdbb 2798static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
d828199e 2799{
cbcf2dd3 2800 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
d828199e 2801 unsigned long seq;
d828199e 2802 int mode;
cbcf2dd3 2803 u64 ns;
d828199e 2804
d828199e
MT
2805 do {
2806 seq = read_seqcount_begin(&gtod->seq);
917f9475 2807 ns = gtod->raw_clock.base_cycles;
53fafdbb 2808 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
917f9475
PB
2809 ns >>= gtod->raw_clock.shift;
2810 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
d828199e 2811 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
cbcf2dd3 2812 *t = ns;
d828199e
MT
2813
2814 return mode;
2815}
2816
899a31f5 2817static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
55dd00a7
MT
2818{
2819 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2820 unsigned long seq;
2821 int mode;
2822 u64 ns;
2823
2824 do {
2825 seq = read_seqcount_begin(&gtod->seq);
55dd00a7 2826 ts->tv_sec = gtod->wall_time_sec;
917f9475 2827 ns = gtod->clock.base_cycles;
53fafdbb 2828 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
55dd00a7
MT
2829 ns >>= gtod->clock.shift;
2830 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2831
2832 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2833 ts->tv_nsec = ns;
2834
2835 return mode;
2836}
2837
b0c39dc6
VK
2838/* returns true if host is using TSC based clocksource */
2839static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
d828199e 2840{
d828199e 2841 /* checked again under seqlock below */
b0c39dc6 2842 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
d828199e
MT
2843 return false;
2844
53fafdbb 2845 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
b0c39dc6 2846 tsc_timestamp));
d828199e 2847}
55dd00a7 2848
b0c39dc6 2849/* returns true if host is using TSC based clocksource */
899a31f5 2850static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
b0c39dc6 2851 u64 *tsc_timestamp)
55dd00a7
MT
2852{
2853 /* checked again under seqlock below */
b0c39dc6 2854 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
55dd00a7
MT
2855 return false;
2856
b0c39dc6 2857 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
55dd00a7 2858}
d828199e
MT
2859#endif
2860
2861/*
2862 *
b48aa97e
MT
2863 * Assuming a stable TSC across physical CPUS, and a stable TSC
2864 * across virtual CPUs, the following condition is possible.
2865 * Each numbered line represents an event visible to both
d828199e
MT
2866 * CPUs at the next numbered event.
2867 *
2868 * "timespecX" represents host monotonic time. "tscX" represents
2869 * RDTSC value.
2870 *
2871 * VCPU0 on CPU0 | VCPU1 on CPU1
2872 *
2873 * 1. read timespec0,tsc0
2874 * 2. | timespec1 = timespec0 + N
2875 * | tsc1 = tsc0 + M
2876 * 3. transition to guest | transition to guest
2877 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2878 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2879 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2880 *
2881 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2882 *
2883 * - ret0 < ret1
2884 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2885 * ...
2886 * - 0 < N - M => M < N
2887 *
2888 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2889 * always the case (the difference between two distinct xtime instances
2890 * might be smaller then the difference between corresponding TSC reads,
2891 * when updating guest vcpus pvclock areas).
2892 *
2893 * To avoid that problem, do not allow visibility of distinct
2894 * system_timestamp/tsc_timestamp values simultaneously: use a master
2895 * copy of host monotonic time values. Update that master copy
2896 * in lockstep.
2897 *
b48aa97e 2898 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
d828199e
MT
2899 *
2900 */
2901
2902static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2903{
2904#ifdef CONFIG_X86_64
2905 struct kvm_arch *ka = &kvm->arch;
2906 int vclock_mode;
b48aa97e
MT
2907 bool host_tsc_clocksource, vcpus_matched;
2908
869b4421 2909 lockdep_assert_held(&kvm->arch.tsc_write_lock);
b48aa97e
MT
2910 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2911 atomic_read(&kvm->online_vcpus));
d828199e
MT
2912
2913 /*
2914 * If the host uses TSC clock, then passthrough TSC as stable
2915 * to the guest.
2916 */
b48aa97e 2917 host_tsc_clocksource = kvm_get_time_and_clockread(
d828199e
MT
2918 &ka->master_kernel_ns,
2919 &ka->master_cycle_now);
2920
16a96021 2921 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
a826faf1 2922 && !ka->backwards_tsc_observed
54750f2c 2923 && !ka->boot_vcpu_runs_old_kvmclock;
b48aa97e 2924
d828199e
MT
2925 if (ka->use_master_clock)
2926 atomic_set(&kvm_guest_has_master_clock, 1);
2927
2928 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
b48aa97e
MT
2929 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2930 vcpus_matched);
d828199e
MT
2931#endif
2932}
2933
6b6fcd28 2934static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2860c4b1
PB
2935{
2936 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2937}
2938
869b4421 2939static void __kvm_start_pvclock_update(struct kvm *kvm)
2e762ff7 2940{
869b4421
PB
2941 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
2942 write_seqcount_begin(&kvm->arch.pvclock_sc);
2943}
e880c6ea 2944
869b4421
PB
2945static void kvm_start_pvclock_update(struct kvm *kvm)
2946{
2e762ff7 2947 kvm_make_mclock_inprogress_request(kvm);
c2c647f9 2948
2e762ff7 2949 /* no guest entries from this point */
869b4421 2950 __kvm_start_pvclock_update(kvm);
6b6fcd28 2951}
2e762ff7 2952
6b6fcd28
PB
2953static void kvm_end_pvclock_update(struct kvm *kvm)
2954{
2955 struct kvm_arch *ka = &kvm->arch;
2956 struct kvm_vcpu *vcpu;
46808a4c 2957 unsigned long i;
2e762ff7 2958
869b4421
PB
2959 write_seqcount_end(&ka->pvclock_sc);
2960 raw_spin_unlock_irq(&ka->tsc_write_lock);
2e762ff7 2961 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 2962 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2e762ff7
MT
2963
2964 /* guest entries allowed */
2965 kvm_for_each_vcpu(i, vcpu, kvm)
72875d8a 2966 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2e762ff7
MT
2967}
2968
6b6fcd28
PB
2969static void kvm_update_masterclock(struct kvm *kvm)
2970{
42dcbe7d 2971 kvm_hv_request_tsc_page_update(kvm);
6b6fcd28
PB
2972 kvm_start_pvclock_update(kvm);
2973 pvclock_update_vm_gtod_copy(kvm);
2974 kvm_end_pvclock_update(kvm);
2e762ff7
MT
2975}
2976
869b4421
PB
2977/* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
2978static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
108b249c 2979{
108b249c 2980 struct kvm_arch *ka = &kvm->arch;
8b953440 2981 struct pvclock_vcpu_time_info hv_clock;
8b953440 2982
e2c2206a
WL
2983 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2984 get_cpu();
2985
869b4421
PB
2986 data->flags = 0;
2987 if (ka->use_master_clock && __this_cpu_read(cpu_tsc_khz)) {
c68dc1b5
OU
2988#ifdef CONFIG_X86_64
2989 struct timespec64 ts;
2990
2991 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
2992 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
2993 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
2994 } else
2995#endif
2996 data->host_tsc = rdtsc();
2997
869b4421
PB
2998 data->flags |= KVM_CLOCK_TSC_STABLE;
2999 hv_clock.tsc_timestamp = ka->master_cycle_now;
3000 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
e70b57a6
WL
3001 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
3002 &hv_clock.tsc_shift,
3003 &hv_clock.tsc_to_system_mul);
c68dc1b5 3004 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
55c0cefb
OU
3005 } else {
3006 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3007 }
e2c2206a
WL
3008
3009 put_cpu();
55c0cefb 3010}
e2c2206a 3011
869b4421
PB
3012static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3013{
3014 struct kvm_arch *ka = &kvm->arch;
3015 unsigned seq;
3016
3017 do {
3018 seq = read_seqcount_begin(&ka->pvclock_sc);
3019 __get_kvmclock(kvm, data);
3020 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3021}
3022
55c0cefb
OU
3023u64 get_kvmclock_ns(struct kvm *kvm)
3024{
3025 struct kvm_clock_data data;
3026
55c0cefb
OU
3027 get_kvmclock(kvm, &data);
3028 return data.clock;
108b249c
PB
3029}
3030
916d3608
DW
3031static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
3032 struct gfn_to_pfn_cache *gpc,
3033 unsigned int offset)
0d6dd2ff
PB
3034{
3035 struct kvm_vcpu_arch *vcpu = &v->arch;
916d3608
DW
3036 struct pvclock_vcpu_time_info *guest_hv_clock;
3037 unsigned long flags;
0d6dd2ff 3038
916d3608 3039 read_lock_irqsave(&gpc->lock, flags);
aba3caef
ML
3040 while (!kvm_gpc_check(v->kvm, gpc, gpc->gpa,
3041 offset + sizeof(*guest_hv_clock))) {
916d3608
DW
3042 read_unlock_irqrestore(&gpc->lock, flags);
3043
aba3caef
ML
3044 if (kvm_gpc_refresh(v->kvm, gpc, gpc->gpa,
3045 offset + sizeof(*guest_hv_clock)))
916d3608 3046 return;
0d6dd2ff 3047
916d3608
DW
3048 read_lock_irqsave(&gpc->lock, flags);
3049 }
3050
3051 guest_hv_clock = (void *)(gpc->khva + offset);
3052
3053 /*
3054 * This VCPU is paused, but it's legal for a guest to read another
0d6dd2ff
PB
3055 * VCPU's kvmclock, so we really have to follow the specification where
3056 * it says that version is odd if data is being modified, and even after
3057 * it is consistent.
0d6dd2ff 3058 */
0d6dd2ff 3059
916d3608 3060 guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
0d6dd2ff
PB
3061 smp_wmb();
3062
3063 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
916d3608 3064 vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
0d6dd2ff
PB
3065
3066 if (vcpu->pvclock_set_guest_stopped_request) {
3067 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3068 vcpu->pvclock_set_guest_stopped_request = false;
3069 }
3070
916d3608
DW
3071 memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
3072 smp_wmb();
0d6dd2ff 3073
916d3608 3074 guest_hv_clock->version = ++vcpu->hv_clock.version;
0d6dd2ff 3075
916d3608
DW
3076 mark_page_dirty_in_slot(v->kvm, gpc->memslot, gpc->gpa >> PAGE_SHIFT);
3077 read_unlock_irqrestore(&gpc->lock, flags);
0d6dd2ff 3078
916d3608 3079 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
0d6dd2ff
PB
3080}
3081
34c238a1 3082static int kvm_guest_time_update(struct kvm_vcpu *v)
18068523 3083{
78db6a50 3084 unsigned long flags, tgt_tsc_khz;
869b4421 3085 unsigned seq;
18068523 3086 struct kvm_vcpu_arch *vcpu = &v->arch;
d828199e 3087 struct kvm_arch *ka = &v->kvm->arch;
f25e656d 3088 s64 kernel_ns;
d828199e 3089 u64 tsc_timestamp, host_tsc;
51d59c6b 3090 u8 pvclock_flags;
d828199e
MT
3091 bool use_master_clock;
3092
3093 kernel_ns = 0;
3094 host_tsc = 0;
18068523 3095
d828199e
MT
3096 /*
3097 * If the host uses TSC clock, then passthrough TSC as stable
3098 * to the guest.
3099 */
869b4421
PB
3100 do {
3101 seq = read_seqcount_begin(&ka->pvclock_sc);
3102 use_master_clock = ka->use_master_clock;
3103 if (use_master_clock) {
3104 host_tsc = ka->master_cycle_now;
3105 kernel_ns = ka->master_kernel_ns;
3106 }
3107 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
c09664bb
MT
3108
3109 /* Keep irq disabled to prevent changes to the clock */
3110 local_irq_save(flags);
78db6a50
PB
3111 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
3112 if (unlikely(tgt_tsc_khz == 0)) {
c09664bb
MT
3113 local_irq_restore(flags);
3114 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3115 return 1;
3116 }
d828199e 3117 if (!use_master_clock) {
4ea1636b 3118 host_tsc = rdtsc();
8171cd68 3119 kernel_ns = get_kvmclock_base_ns();
d828199e
MT
3120 }
3121
4ba76538 3122 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
d828199e 3123
c285545f
ZA
3124 /*
3125 * We may have to catch up the TSC to match elapsed wall clock
3126 * time for two reasons, even if kvmclock is used.
3127 * 1) CPU could have been running below the maximum TSC rate
3128 * 2) Broken TSC compensation resets the base at each VCPU
3129 * entry to avoid unknown leaps of TSC even when running
3130 * again on the same CPU. This may cause apparent elapsed
3131 * time to disappear, and the guest to stand still or run
3132 * very slowly.
3133 */
3134 if (vcpu->tsc_catchup) {
3135 u64 tsc = compute_guest_tsc(v, kernel_ns);
3136 if (tsc > tsc_timestamp) {
f1e2b260 3137 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
c285545f
ZA
3138 tsc_timestamp = tsc;
3139 }
50d0a0f9
GH
3140 }
3141
18068523
GOC
3142 local_irq_restore(flags);
3143
0d6dd2ff 3144 /* With all the info we got, fill in the values */
18068523 3145
938c8745 3146 if (kvm_caps.has_tsc_control)
62711e5a 3147 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
fe3eb504 3148 v->arch.l1_tsc_scaling_ratio);
78db6a50
PB
3149
3150 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3ae13faa 3151 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
5f4e3f88
ZA
3152 &vcpu->hv_clock.tsc_shift,
3153 &vcpu->hv_clock.tsc_to_system_mul);
78db6a50 3154 vcpu->hw_tsc_khz = tgt_tsc_khz;
8cfdc000
ZA
3155 }
3156
1d5f066e 3157 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
759379dd 3158 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
28e4639a 3159 vcpu->last_guest_tsc = tsc_timestamp;
51d59c6b 3160
d828199e 3161 /* If the host uses TSC clocksource, then it is stable */
0d6dd2ff 3162 pvclock_flags = 0;
d828199e
MT
3163 if (use_master_clock)
3164 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3165
78c0337a
MT
3166 vcpu->hv_clock.flags = pvclock_flags;
3167
916d3608
DW
3168 if (vcpu->pv_time.active)
3169 kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0);
7caf9571
DW
3170 if (vcpu->xen.vcpu_info_cache.active)
3171 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
3172 offsetof(struct compat_vcpu_info, time));
69d413cf
DW
3173 if (vcpu->xen.vcpu_time_info_cache.active)
3174 kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0);
42dcbe7d 3175 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
8cfdc000 3176 return 0;
c8076604
GH
3177}
3178
0061d53d
MT
3179/*
3180 * kvmclock updates which are isolated to a given vcpu, such as
3181 * vcpu->cpu migration, should not allow system_timestamp from
3182 * the rest of the vcpus to remain static. Otherwise ntp frequency
3183 * correction applies to one vcpu's system_timestamp but not
3184 * the others.
3185 *
3186 * So in those cases, request a kvmclock update for all vcpus.
7e44e449
AJ
3187 * We need to rate-limit these requests though, as they can
3188 * considerably slow guests that have a large number of vcpus.
3189 * The time for a remote vcpu to update its kvmclock is bound
3190 * by the delay we use to rate-limit the updates.
0061d53d
MT
3191 */
3192
7e44e449
AJ
3193#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3194
3195static void kvmclock_update_fn(struct work_struct *work)
0061d53d 3196{
46808a4c 3197 unsigned long i;
7e44e449
AJ
3198 struct delayed_work *dwork = to_delayed_work(work);
3199 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3200 kvmclock_update_work);
3201 struct kvm *kvm = container_of(ka, struct kvm, arch);
0061d53d
MT
3202 struct kvm_vcpu *vcpu;
3203
3204 kvm_for_each_vcpu(i, vcpu, kvm) {
105b21bb 3205 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0061d53d
MT
3206 kvm_vcpu_kick(vcpu);
3207 }
3208}
3209
7e44e449
AJ
3210static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3211{
3212 struct kvm *kvm = v->kvm;
3213
105b21bb 3214 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
7e44e449
AJ
3215 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3216 KVMCLOCK_UPDATE_DELAY);
3217}
3218
332967a3
AJ
3219#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3220
3221static void kvmclock_sync_fn(struct work_struct *work)
3222{
3223 struct delayed_work *dwork = to_delayed_work(work);
3224 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3225 kvmclock_sync_work);
3226 struct kvm *kvm = container_of(ka, struct kvm, arch);
3227
630994b3
MT
3228 if (!kvmclock_periodic_sync)
3229 return;
3230
332967a3
AJ
3231 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3232 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3233 KVMCLOCK_SYNC_PERIOD);
3234}
3235
281b5278
JW
3236/* These helpers are safe iff @msr is known to be an MCx bank MSR. */
3237static bool is_mci_control_msr(u32 msr)
3238{
3239 return (msr & 3) == 0;
3240}
3241static bool is_mci_status_msr(u32 msr)
3242{
3243 return (msr & 3) == 1;
3244}
3245
191c8137
BP
3246/*
3247 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3248 */
3249static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3250{
3251 /* McStatusWrEn enabled? */
23493d0a 3252 if (guest_cpuid_is_amd_or_hygon(vcpu))
191c8137
BP
3253 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3254
3255 return false;
3256}
3257
9ffd986c 3258static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 3259{
890ca9ae
HY
3260 u64 mcg_cap = vcpu->arch.mcg_cap;
3261 unsigned bank_num = mcg_cap & 0xff;
9ffd986c
WL
3262 u32 msr = msr_info->index;
3263 u64 data = msr_info->data;
281b5278 3264 u32 offset, last_msr;
890ca9ae 3265
15c4a640 3266 switch (msr) {
15c4a640 3267 case MSR_IA32_MCG_STATUS:
890ca9ae 3268 vcpu->arch.mcg_status = data;
15c4a640 3269 break;
c7ac679c 3270 case MSR_IA32_MCG_CTL:
44883f01
PB
3271 if (!(mcg_cap & MCG_CTL_P) &&
3272 (data || !msr_info->host_initiated))
890ca9ae
HY
3273 return 1;
3274 if (data != 0 && data != ~(u64)0)
44883f01 3275 return 1;
890ca9ae
HY
3276 vcpu->arch.mcg_ctl = data;
3277 break;
281b5278
JW
3278 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3279 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3280 if (msr > last_msr)
3281 return 1;
191c8137 3282
281b5278
JW
3283 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3284 return 1;
3285 /* An attempt to write a 1 to a reserved bit raises #GP */
3286 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3287 return 1;
3288 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3289 last_msr + 1 - MSR_IA32_MC0_CTL2);
3290 vcpu->arch.mci_ctl2_banks[offset] = data;
3291 break;
3292 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3293 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3294 if (msr > last_msr)
3295 return 1;
3296
3297 /*
3298 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3299 * values are architecturally undefined. But, some Linux
3300 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3301 * issue on AMD K8s, allow bit 10 to be clear when setting all
3302 * other bits in order to avoid an uncaught #GP in the guest.
f5223a33
SC
3303 *
3304 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3305 * single-bit ECC data errors.
281b5278
JW
3306 */
3307 if (is_mci_control_msr(msr) &&
3308 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3309 return 1;
191c8137 3310
281b5278
JW
3311 /*
3312 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3313 * AMD-based CPUs allow non-zero values, but if and only if
3314 * HWCR[McStatusWrEn] is set.
3315 */
3316 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3317 data != 0 && !can_set_mci_status(vcpu))
3318 return 1;
3319
3320 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3321 last_msr + 1 - MSR_IA32_MC0_CTL);
3322 vcpu->arch.mce_banks[offset] = data;
3323 break;
3324 default:
890ca9ae
HY
3325 return 1;
3326 }
3327 return 0;
3328}
3329
2635b5c4
VK
3330static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3331{
3332 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3333
3334 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3335}
3336
344d9588
GN
3337static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3338{
3339 gpa_t gpa = data & ~0x3f;
3340
2635b5c4
VK
3341 /* Bits 4:5 are reserved, Should be zero */
3342 if (data & 0x30)
344d9588
GN
3343 return 1;
3344
66570e96
OU
3345 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3346 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3347 return 1;
3348
3349 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3350 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3351 return 1;
3352
9d3c447c 3353 if (!lapic_in_kernel(vcpu))
d831de17 3354 return data ? 1 : 0;
9d3c447c 3355
2635b5c4 3356 vcpu->arch.apf.msr_en_val = data;
344d9588 3357
2635b5c4 3358 if (!kvm_pv_async_pf_enabled(vcpu)) {
344d9588
GN
3359 kvm_clear_async_pf_completion_queue(vcpu);
3360 kvm_async_pf_hash_reset(vcpu);
3361 return 0;
3362 }
3363
4e335d9e 3364 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
68fd66f1 3365 sizeof(u64)))
344d9588
GN
3366 return 1;
3367
6adba527 3368 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
52a5c155 3369 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2635b5c4 3370
344d9588 3371 kvm_async_pf_wakeup_all(vcpu);
2635b5c4
VK
3372
3373 return 0;
3374}
3375
3376static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3377{
3378 /* Bits 8-63 are reserved */
3379 if (data >> 8)
3380 return 1;
3381
3382 if (!lapic_in_kernel(vcpu))
3383 return 1;
3384
3385 vcpu->arch.apf.msr_int_val = data;
3386
3387 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3388
344d9588
GN
3389 return 0;
3390}
3391
12f9a48f
GC
3392static void kvmclock_reset(struct kvm_vcpu *vcpu)
3393{
52491a38 3394 kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
49dedf0d 3395 vcpu->arch.time = 0;
12f9a48f
GC
3396}
3397
7780938c 3398static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
f38a7b75
WL
3399{
3400 ++vcpu->stat.tlb_flush;
e27bc044 3401 static_call(kvm_x86_flush_tlb_all)(vcpu);
e94cea09
SC
3402
3403 /* Flushing all ASIDs flushes the current ASID... */
3404 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
f38a7b75
WL
3405}
3406
0baedd79
VK
3407static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3408{
3409 ++vcpu->stat.tlb_flush;
b53e84ee
LJ
3410
3411 if (!tdp_enabled) {
61b05a9f 3412 /*
b53e84ee
LJ
3413 * A TLB flush on behalf of the guest is equivalent to
3414 * INVPCID(all), toggling CR4.PGE, etc., which requires
61b05a9f
LJ
3415 * a forced sync of the shadow page tables. Ensure all the
3416 * roots are synced and the guest TLB in hardware is clean.
b53e84ee 3417 */
61b05a9f
LJ
3418 kvm_mmu_sync_roots(vcpu);
3419 kvm_mmu_sync_prev_roots(vcpu);
b53e84ee
LJ
3420 }
3421
e27bc044 3422 static_call(kvm_x86_flush_tlb_guest)(vcpu);
adc43caa
VK
3423
3424 /*
3425 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3426 * grained flushing.
3427 */
0823570f 3428 kvm_hv_vcpu_purge_flush_tlb(vcpu);
0baedd79
VK
3429}
3430
40e5f908
SC
3431
3432static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3433{
3434 ++vcpu->stat.tlb_flush;
e27bc044 3435 static_call(kvm_x86_flush_tlb_current)(vcpu);
40e5f908
SC
3436}
3437
3438/*
3439 * Service "local" TLB flush requests, which are specific to the current MMU
3440 * context. In addition to the generic event handling in vcpu_enter_guest(),
3441 * TLB flushes that are targeted at an MMU context also need to be serviced
3442 * prior before nested VM-Enter/VM-Exit.
3443 */
3444void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3445{
3446 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3447 kvm_vcpu_flush_tlb_current(vcpu);
3448
3449 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3450 kvm_vcpu_flush_tlb_guest(vcpu);
3451}
3452EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3453
c9aaa895
GC
3454static void record_steal_time(struct kvm_vcpu *vcpu)
3455{
7e2175eb
DW
3456 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3457 struct kvm_steal_time __user *st;
3458 struct kvm_memslots *slots;
901d3765 3459 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
7e2175eb
DW
3460 u64 steal;
3461 u32 version;
b0431382 3462
30b5c851
DW
3463 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3464 kvm_xen_runstate_set_running(vcpu);
3465 return;
3466 }
3467
c9aaa895
GC
3468 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3469 return;
3470
7e2175eb 3471 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
c9aaa895
GC
3472 return;
3473
7e2175eb
DW
3474 slots = kvm_memslots(vcpu->kvm);
3475
3476 if (unlikely(slots->generation != ghc->generation ||
901d3765 3477 gpa != ghc->gpa ||
7e2175eb 3478 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
7e2175eb
DW
3479 /* We rely on the fact that it fits in a single page. */
3480 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3481
901d3765 3482 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
7e2175eb
DW
3483 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3484 return;
3485 }
3486
3487 st = (struct kvm_steal_time __user *)ghc->hva;
f38a7b75
WL
3488 /*
3489 * Doing a TLB flush here, on the guest's behalf, can avoid
3490 * expensive IPIs.
3491 */
66570e96 3492 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
7e2175eb
DW
3493 u8 st_preempted = 0;
3494 int err = -EFAULT;
3495
3e067fd8
PB
3496 if (!user_access_begin(st, sizeof(*st)))
3497 return;
3498
7e2175eb
DW
3499 asm volatile("1: xchgb %0, %2\n"
3500 "xor %1, %1\n"
3501 "2:\n"
3502 _ASM_EXTABLE_UA(1b, 2b)
964b7aa0
DW
3503 : "+q" (st_preempted),
3504 "+&r" (err),
3505 "+m" (st->preempted));
7e2175eb
DW
3506 if (err)
3507 goto out;
3508
3509 user_access_end();
3510
3511 vcpu->arch.st.preempted = 0;
af3511ff 3512
66570e96 3513 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
af3511ff
LJ
3514 st_preempted & KVM_VCPU_FLUSH_TLB);
3515 if (st_preempted & KVM_VCPU_FLUSH_TLB)
66570e96 3516 kvm_vcpu_flush_tlb_guest(vcpu);
7e2175eb
DW
3517
3518 if (!user_access_begin(st, sizeof(*st)))
3519 goto dirty;
1eff0ada 3520 } else {
3e067fd8
PB
3521 if (!user_access_begin(st, sizeof(*st)))
3522 return;
3523
7e2175eb
DW
3524 unsafe_put_user(0, &st->preempted, out);
3525 vcpu->arch.st.preempted = 0;
66570e96 3526 }
0b9f6c46 3527
7e2175eb
DW
3528 unsafe_get_user(version, &st->version, out);
3529 if (version & 1)
3530 version += 1; /* first time write, random junk */
35f3fae1 3531
7e2175eb
DW
3532 version += 1;
3533 unsafe_put_user(version, &st->version, out);
35f3fae1
WL
3534
3535 smp_wmb();
3536
7e2175eb
DW
3537 unsafe_get_user(steal, &st->steal, out);
3538 steal += current->sched_info.run_delay -
c54cdf14
LC
3539 vcpu->arch.st.last_steal;
3540 vcpu->arch.st.last_steal = current->sched_info.run_delay;
7e2175eb 3541 unsafe_put_user(steal, &st->steal, out);
35f3fae1 3542
7e2175eb
DW
3543 version += 1;
3544 unsafe_put_user(version, &st->version, out);
35f3fae1 3545
7e2175eb
DW
3546 out:
3547 user_access_end();
3548 dirty:
3549 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
c9aaa895
GC
3550}
3551
8fe8ab46 3552int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
15c4a640 3553{
5753785f 3554 bool pr = false;
8fe8ab46
WA
3555 u32 msr = msr_info->index;
3556 u64 data = msr_info->data;
5753785f 3557
1232f8e6 3558 if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
23200b7a 3559 return kvm_xen_write_hypercall_page(vcpu, data);
1232f8e6 3560
15c4a640 3561 switch (msr) {
2e32b719 3562 case MSR_AMD64_NB_CFG:
2e32b719
BP
3563 case MSR_IA32_UCODE_WRITE:
3564 case MSR_VM_HSAVE_PA:
3565 case MSR_AMD64_PATCH_LOADER:
3566 case MSR_AMD64_BU_CFG2:
405a353a 3567 case MSR_AMD64_DC_CFG:
0e1b869f 3568 case MSR_F15H_EX_CFG:
2e32b719
BP
3569 break;
3570
518e7b94
WL
3571 case MSR_IA32_UCODE_REV:
3572 if (msr_info->host_initiated)
3573 vcpu->arch.microcode_version = data;
3574 break;
0cf9135b
SC
3575 case MSR_IA32_ARCH_CAPABILITIES:
3576 if (!msr_info->host_initiated)
3577 return 1;
3578 vcpu->arch.arch_capabilities = data;
3579 break;
686e0f03 3580 case MSR_IA32_PERF_CAPABILITIES:
d574c539
VK
3581 if (!msr_info->host_initiated)
3582 return 1;
686e0f03 3583 if (data & ~kvm_caps.supported_perf_cap)
d574c539
VK
3584 return 1;
3585
3586 vcpu->arch.perf_capabilities = data;
17a024a8 3587 kvm_pmu_refresh(vcpu);
d574c539 3588 return 0;
15c4a640 3589 case MSR_EFER:
11988499 3590 return set_efer(vcpu, msr_info);
8f1589d9
AP
3591 case MSR_K7_HWCR:
3592 data &= ~(u64)0x40; /* ignore flush filter disable */
82494028 3593 data &= ~(u64)0x100; /* ignore ignne emulation enable */
a223c313 3594 data &= ~(u64)0x8; /* ignore TLB cache disable */
191c8137
BP
3595
3596 /* Handle McStatusWrEn */
3597 if (data == BIT_ULL(18)) {
3598 vcpu->arch.msr_hwcr = data;
3599 } else if (data != 0) {
a737f256
CD
3600 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3601 data);
8f1589d9
AP
3602 return 1;
3603 }
15c4a640 3604 break;
f7c6d140
AP
3605 case MSR_FAM10H_MMIO_CONF_BASE:
3606 if (data != 0) {
a737f256
CD
3607 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3608 "0x%llx\n", data);
f7c6d140
AP
3609 return 1;
3610 }
15c4a640 3611 break;
281b5278
JW
3612 case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
3613 case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
ff53604b 3614 return kvm_mtrr_set_msr(vcpu, msr, data);
15c4a640 3615 case MSR_IA32_APICBASE:
58cb628d 3616 return kvm_set_apic_base(vcpu, msr_info);
bf10bd0b 3617 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
0105d1a5 3618 return kvm_x2apic_msr_write(vcpu, msr, data);
09141ec0 3619 case MSR_IA32_TSC_DEADLINE:
a3e06bbe
LJ
3620 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3621 break;
ba904635 3622 case MSR_IA32_TSC_ADJUST:
d6321d49 3623 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
ba904635 3624 if (!msr_info->host_initiated) {
d913b904 3625 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
d7add054 3626 adjust_tsc_offset_guest(vcpu, adj);
d9130a2d
ZD
3627 /* Before back to guest, tsc_timestamp must be adjusted
3628 * as well, otherwise guest's percpu pvclock time could jump.
3629 */
3630 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
ba904635
WA
3631 }
3632 vcpu->arch.ia32_tsc_adjust_msr = data;
3633 }
3634 break;
bef6ecca
LX
3635 case MSR_IA32_MISC_ENABLE: {
3636 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
d1055173 3637
9fc22296
SC
3638 if (!msr_info->host_initiated) {
3639 /* RO bits */
3640 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3641 return 1;
3642
3643 /* R bits, i.e. writes are ignored, but don't fault. */
3644 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3645 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3646 }
bef6ecca 3647
511a8556 3648 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
bef6ecca 3649 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
511a8556
WL
3650 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3651 return 1;
3652 vcpu->arch.ia32_misc_enable_msr = data;
aedbaf4f 3653 kvm_update_cpuid_runtime(vcpu);
511a8556
WL
3654 } else {
3655 vcpu->arch.ia32_misc_enable_msr = data;
3656 }
15c4a640 3657 break;
bef6ecca 3658 }
64d60670 3659 case MSR_IA32_SMBASE:
4b8e1b32 3660 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
64d60670
PB
3661 return 1;
3662 vcpu->arch.smbase = data;
3663 break;
73f624f4
PB
3664 case MSR_IA32_POWER_CTL:
3665 vcpu->arch.msr_ia32_power_ctl = data;
3666 break;
dd259935 3667 case MSR_IA32_TSC:
0c899c25
PB
3668 if (msr_info->host_initiated) {
3669 kvm_synchronize_tsc(vcpu, data);
3670 } else {
9b399dfd 3671 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
0c899c25
PB
3672 adjust_tsc_offset_guest(vcpu, adj);
3673 vcpu->arch.ia32_tsc_adjust_msr += adj;
3674 }
dd259935 3675 break;
864e2ab2
AL
3676 case MSR_IA32_XSS:
3677 if (!msr_info->host_initiated &&
3678 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3679 return 1;
3680 /*
a1bead2a
SC
3681 * KVM supports exposing PT to the guest, but does not support
3682 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3683 * XSAVES/XRSTORS to save/restore PT MSRs.
864e2ab2 3684 */
938c8745 3685 if (data & ~kvm_caps.supported_xss)
864e2ab2
AL
3686 return 1;
3687 vcpu->arch.ia32_xss = data;
4c282e51 3688 kvm_update_cpuid_runtime(vcpu);
864e2ab2 3689 break;
52797bf9
LA
3690 case MSR_SMI_COUNT:
3691 if (!msr_info->host_initiated)
3692 return 1;
3693 vcpu->arch.smi_count = data;
3694 break;
11c6bffa 3695 case MSR_KVM_WALL_CLOCK_NEW:
66570e96
OU
3696 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3697 return 1;
3698
629b5348
JM
3699 vcpu->kvm->arch.wall_clock = data;
3700 kvm_write_wall_clock(vcpu->kvm, data, 0);
66570e96 3701 break;
18068523 3702 case MSR_KVM_WALL_CLOCK:
66570e96
OU
3703 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3704 return 1;
3705
629b5348
JM
3706 vcpu->kvm->arch.wall_clock = data;
3707 kvm_write_wall_clock(vcpu->kvm, data, 0);
18068523 3708 break;
11c6bffa 3709 case MSR_KVM_SYSTEM_TIME_NEW:
66570e96
OU
3710 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3711 return 1;
3712
5b9bb0eb
OU
3713 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3714 break;
3715 case MSR_KVM_SYSTEM_TIME:
66570e96
OU
3716 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3717 return 1;
3718
3719 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
18068523 3720 break;
344d9588 3721 case MSR_KVM_ASYNC_PF_EN:
66570e96
OU
3722 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3723 return 1;
3724
344d9588
GN
3725 if (kvm_pv_enable_async_pf(vcpu, data))
3726 return 1;
3727 break;
2635b5c4 3728 case MSR_KVM_ASYNC_PF_INT:
66570e96
OU
3729 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3730 return 1;
3731
2635b5c4
VK
3732 if (kvm_pv_enable_async_pf_int(vcpu, data))
3733 return 1;
3734 break;
557a961a 3735 case MSR_KVM_ASYNC_PF_ACK:
0a31df68 3736 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
66570e96 3737 return 1;
557a961a
VK
3738 if (data & 0x1) {
3739 vcpu->arch.apf.pageready_pending = false;
3740 kvm_check_async_pf_completion(vcpu);
3741 }
3742 break;
c9aaa895 3743 case MSR_KVM_STEAL_TIME:
66570e96
OU
3744 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3745 return 1;
c9aaa895
GC
3746
3747 if (unlikely(!sched_info_on()))
3748 return 1;
3749
3750 if (data & KVM_STEAL_RESERVED_MASK)
3751 return 1;
3752
c9aaa895
GC
3753 vcpu->arch.st.msr_val = data;
3754
3755 if (!(data & KVM_MSR_ENABLED))
3756 break;
3757
c9aaa895
GC
3758 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3759
3760 break;
ae7a2a3f 3761 case MSR_KVM_PV_EOI_EN:
66570e96
OU
3762 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3763 return 1;
3764
77c3323f 3765 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
ae7a2a3f
MT
3766 return 1;
3767 break;
c9aaa895 3768
2d5ba19b 3769 case MSR_KVM_POLL_CONTROL:
66570e96
OU
3770 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3771 return 1;
3772
2d5ba19b
MT
3773 /* only enable bit supported */
3774 if (data & (-1ULL << 1))
3775 return 1;
3776
3777 vcpu->arch.msr_kvm_poll_control = data;
3778 break;
3779
890ca9ae
HY
3780 case MSR_IA32_MCG_CTL:
3781 case MSR_IA32_MCG_STATUS:
81760dcc 3782 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
281b5278 3783 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
9ffd986c 3784 return set_msr_mce(vcpu, msr_info);
71db6023 3785
6912ac32
WH
3786 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3787 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
df561f66
GS
3788 pr = true;
3789 fallthrough;
6912ac32
WH
3790 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3791 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 3792 if (kvm_pmu_is_valid_msr(vcpu, msr))
afd80d85 3793 return kvm_pmu_set_msr(vcpu, msr_info);
5753785f
GN
3794
3795 if (pr || data != 0)
a737f256
CD
3796 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3797 "0x%x data 0x%llx\n", msr, data);
5753785f 3798 break;
84e0cefa
JS
3799 case MSR_K7_CLK_CTL:
3800 /*
3801 * Ignore all writes to this no longer documented MSR.
3802 * Writes are only relevant for old K7 processors,
3803 * all pre-dating SVM, but a recommended workaround from
4a969980 3804 * AMD for these chips. It is possible to specify the
84e0cefa
JS
3805 * affected processor models on the command line, hence
3806 * the need to ignore the workaround.
3807 */
3808 break;
55cd8e5a 3809 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
3810 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3811 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
3812 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3813 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 3814 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
3815 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3816 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3817 case HV_X64_MSR_TSC_EMULATION_STATUS:
e7d9513b
AS
3818 return kvm_hv_set_msr_common(vcpu, msr, data,
3819 msr_info->host_initiated);
91c9c3ed 3820 case MSR_IA32_BBL_CR_CTL3:
3821 /* Drop writes to this legacy MSR -- see rdmsr
3822 * counterpart for further detail.
3823 */
fab0aa3b
EM
3824 if (report_ignored_msrs)
3825 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3826 msr, data);
91c9c3ed 3827 break;
2b036c6b 3828 case MSR_AMD64_OSVW_ID_LENGTH:
d6321d49 3829 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
3830 return 1;
3831 vcpu->arch.osvw.length = data;
3832 break;
3833 case MSR_AMD64_OSVW_STATUS:
d6321d49 3834 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b
BO
3835 return 1;
3836 vcpu->arch.osvw.status = data;
3837 break;
db2336a8
KH
3838 case MSR_PLATFORM_INFO:
3839 if (!msr_info->host_initiated ||
db2336a8
KH
3840 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3841 cpuid_fault_enabled(vcpu)))
3842 return 1;
3843 vcpu->arch.msr_platform_info = data;
3844 break;
3845 case MSR_MISC_FEATURES_ENABLES:
3846 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3847 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3848 !supports_cpuid_fault(vcpu)))
3849 return 1;
3850 vcpu->arch.msr_misc_features_enables = data;
3851 break;
820a6ee9
JL
3852#ifdef CONFIG_X86_64
3853 case MSR_IA32_XFD:
3854 if (!msr_info->host_initiated &&
3855 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3856 return 1;
3857
988896bb 3858 if (data & ~kvm_guest_supported_xfd(vcpu))
820a6ee9
JL
3859 return 1;
3860
3861 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
3862 break;
548e8365
JL
3863 case MSR_IA32_XFD_ERR:
3864 if (!msr_info->host_initiated &&
3865 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3866 return 1;
3867
988896bb 3868 if (data & ~kvm_guest_supported_xfd(vcpu))
548e8365
JL
3869 return 1;
3870
3871 vcpu->arch.guest_fpu.xfd_err = data;
3872 break;
820a6ee9 3873#endif
157fc497
SC
3874 case MSR_IA32_PEBS_ENABLE:
3875 case MSR_IA32_DS_AREA:
3876 case MSR_PEBS_DATA_CFG:
ff81a90f 3877 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
157fc497
SC
3878 if (kvm_pmu_is_valid_msr(vcpu, msr))
3879 return kvm_pmu_set_msr(vcpu, msr_info);
3880 /*
3881 * Userspace is allowed to write '0' to MSRs that KVM reports
3882 * as to-be-saved, even if an MSRs isn't fully supported.
3883 */
3884 return !msr_info->host_initiated || data;
15c4a640 3885 default:
c6702c9d 3886 if (kvm_pmu_is_valid_msr(vcpu, msr))
afd80d85 3887 return kvm_pmu_set_msr(vcpu, msr_info);
6abe9c13 3888 return KVM_MSR_RET_INVALID;
15c4a640
CO
3889 }
3890 return 0;
3891}
3892EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3893
44883f01 3894static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
15c4a640
CO
3895{
3896 u64 data;
890ca9ae
HY
3897 u64 mcg_cap = vcpu->arch.mcg_cap;
3898 unsigned bank_num = mcg_cap & 0xff;
281b5278 3899 u32 offset, last_msr;
15c4a640
CO
3900
3901 switch (msr) {
15c4a640
CO
3902 case MSR_IA32_P5_MC_ADDR:
3903 case MSR_IA32_P5_MC_TYPE:
890ca9ae
HY
3904 data = 0;
3905 break;
15c4a640 3906 case MSR_IA32_MCG_CAP:
890ca9ae
HY
3907 data = vcpu->arch.mcg_cap;
3908 break;
c7ac679c 3909 case MSR_IA32_MCG_CTL:
44883f01 3910 if (!(mcg_cap & MCG_CTL_P) && !host)
890ca9ae
HY
3911 return 1;
3912 data = vcpu->arch.mcg_ctl;
3913 break;
3914 case MSR_IA32_MCG_STATUS:
3915 data = vcpu->arch.mcg_status;
3916 break;
281b5278
JW
3917 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3918 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3919 if (msr > last_msr)
3920 return 1;
6ec4c5ee 3921
281b5278
JW
3922 if (!(mcg_cap & MCG_CMCI_P) && !host)
3923 return 1;
3924 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3925 last_msr + 1 - MSR_IA32_MC0_CTL2);
3926 data = vcpu->arch.mci_ctl2_banks[offset];
3927 break;
3928 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3929 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3930 if (msr > last_msr)
3931 return 1;
3932
3933 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3934 last_msr + 1 - MSR_IA32_MC0_CTL);
3935 data = vcpu->arch.mce_banks[offset];
3936 break;
3937 default:
890ca9ae
HY
3938 return 1;
3939 }
3940 *pdata = data;
3941 return 0;
3942}
3943
609e36d3 3944int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
890ca9ae 3945{
609e36d3 3946 switch (msr_info->index) {
890ca9ae 3947 case MSR_IA32_PLATFORM_ID:
15c4a640 3948 case MSR_IA32_EBL_CR_POWERON:
b5e2fec0
AG
3949 case MSR_IA32_LASTBRANCHFROMIP:
3950 case MSR_IA32_LASTBRANCHTOIP:
3951 case MSR_IA32_LASTINTFROMIP:
3952 case MSR_IA32_LASTINTTOIP:
059e5c32 3953 case MSR_AMD64_SYSCFG:
3afb1121
PB
3954 case MSR_K8_TSEG_ADDR:
3955 case MSR_K8_TSEG_MASK:
61a6bd67 3956 case MSR_VM_HSAVE_PA:
1fdbd48c 3957 case MSR_K8_INT_PENDING_MSG:
c323c0e5 3958 case MSR_AMD64_NB_CFG:
f7c6d140 3959 case MSR_FAM10H_MMIO_CONF_BASE:
2e32b719 3960 case MSR_AMD64_BU_CFG2:
0c2df2a1 3961 case MSR_IA32_PERF_CTL:
405a353a 3962 case MSR_AMD64_DC_CFG:
0e1b869f 3963 case MSR_F15H_EX_CFG:
2ca1a06a
VS
3964 /*
3965 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3966 * limit) MSRs. Just return 0, as we do not want to expose the host
3967 * data here. Do not conditionalize this on CPUID, as KVM does not do
3968 * so for existing CPU-specific MSRs.
3969 */
3970 case MSR_RAPL_POWER_UNIT:
3971 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3972 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3973 case MSR_PKG_ENERGY_STATUS: /* Total package */
3974 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
609e36d3 3975 msr_info->data = 0;
15c4a640 3976 break;
157fc497
SC
3977 case MSR_IA32_PEBS_ENABLE:
3978 case MSR_IA32_DS_AREA:
3979 case MSR_PEBS_DATA_CFG:
c51eb52b 3980 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
c28fa560
VK
3981 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3982 return kvm_pmu_get_msr(vcpu, msr_info);
157fc497 3983 /*
bfbcc81b
SC
3984 * Userspace is allowed to read MSRs that KVM reports as
3985 * to-be-saved, even if an MSR isn't fully supported.
157fc497 3986 */
c28fa560
VK
3987 if (!msr_info->host_initiated)
3988 return 1;
3989 msr_info->data = 0;
3990 break;
6912ac32
WH
3991 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3992 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3993 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3994 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
c6702c9d 3995 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 3996 return kvm_pmu_get_msr(vcpu, msr_info);
609e36d3 3997 msr_info->data = 0;
5753785f 3998 break;
742bc670 3999 case MSR_IA32_UCODE_REV:
518e7b94 4000 msr_info->data = vcpu->arch.microcode_version;
742bc670 4001 break;
0cf9135b
SC
4002 case MSR_IA32_ARCH_CAPABILITIES:
4003 if (!msr_info->host_initiated &&
4004 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4005 return 1;
4006 msr_info->data = vcpu->arch.arch_capabilities;
4007 break;
d574c539
VK
4008 case MSR_IA32_PERF_CAPABILITIES:
4009 if (!msr_info->host_initiated &&
4010 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
4011 return 1;
4012 msr_info->data = vcpu->arch.perf_capabilities;
4013 break;
73f624f4
PB
4014 case MSR_IA32_POWER_CTL:
4015 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4016 break;
cc5b54dd
ML
4017 case MSR_IA32_TSC: {
4018 /*
4019 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4020 * even when not intercepted. AMD manual doesn't explicitly
4021 * state this but appears to behave the same.
4022 *
ee6fa053 4023 * On userspace reads and writes, however, we unconditionally
c0623f5e 4024 * return L1's TSC value to ensure backwards-compatible
ee6fa053 4025 * behavior for migration.
cc5b54dd 4026 */
fe3eb504 4027 u64 offset, ratio;
cc5b54dd 4028
fe3eb504
IS
4029 if (msr_info->host_initiated) {
4030 offset = vcpu->arch.l1_tsc_offset;
4031 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4032 } else {
4033 offset = vcpu->arch.tsc_offset;
4034 ratio = vcpu->arch.tsc_scaling_ratio;
4035 }
4036
62711e5a 4037 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
dd259935 4038 break;
cc5b54dd 4039 }
9ba075a6 4040 case MSR_MTRRcap:
281b5278
JW
4041 case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
4042 case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
ff53604b 4043 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
15c4a640 4044 case 0xcd: /* fsb frequency */
609e36d3 4045 msr_info->data = 3;
15c4a640 4046 break;
7b914098
JS
4047 /*
4048 * MSR_EBC_FREQUENCY_ID
4049 * Conservative value valid for even the basic CPU models.
4050 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4051 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4052 * and 266MHz for model 3, or 4. Set Core Clock
4053 * Frequency to System Bus Frequency Ratio to 1 (bits
4054 * 31:24) even though these are only valid for CPU
4055 * models > 2, however guests may end up dividing or
4056 * multiplying by zero otherwise.
4057 */
4058 case MSR_EBC_FREQUENCY_ID:
609e36d3 4059 msr_info->data = 1 << 24;
7b914098 4060 break;
15c4a640 4061 case MSR_IA32_APICBASE:
609e36d3 4062 msr_info->data = kvm_get_apic_base(vcpu);
15c4a640 4063 break;
bf10bd0b 4064 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
609e36d3 4065 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
09141ec0 4066 case MSR_IA32_TSC_DEADLINE:
609e36d3 4067 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
a3e06bbe 4068 break;
ba904635 4069 case MSR_IA32_TSC_ADJUST:
609e36d3 4070 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
ba904635 4071 break;
15c4a640 4072 case MSR_IA32_MISC_ENABLE:
609e36d3 4073 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
15c4a640 4074 break;
64d60670 4075 case MSR_IA32_SMBASE:
4b8e1b32 4076 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
64d60670
PB
4077 return 1;
4078 msr_info->data = vcpu->arch.smbase;
15c4a640 4079 break;
52797bf9
LA
4080 case MSR_SMI_COUNT:
4081 msr_info->data = vcpu->arch.smi_count;
4082 break;
847f0ad8
AG
4083 case MSR_IA32_PERF_STATUS:
4084 /* TSC increment by tick */
609e36d3 4085 msr_info->data = 1000ULL;
847f0ad8 4086 /* CPU multiplier */
b0996ae4 4087 msr_info->data |= (((uint64_t)4ULL) << 40);
847f0ad8 4088 break;
15c4a640 4089 case MSR_EFER:
609e36d3 4090 msr_info->data = vcpu->arch.efer;
15c4a640 4091 break;
18068523 4092 case MSR_KVM_WALL_CLOCK:
1930e5dd
OU
4093 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4094 return 1;
4095
4096 msr_info->data = vcpu->kvm->arch.wall_clock;
4097 break;
11c6bffa 4098 case MSR_KVM_WALL_CLOCK_NEW:
1930e5dd
OU
4099 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4100 return 1;
4101
609e36d3 4102 msr_info->data = vcpu->kvm->arch.wall_clock;
18068523
GOC
4103 break;
4104 case MSR_KVM_SYSTEM_TIME:
1930e5dd
OU
4105 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4106 return 1;
4107
4108 msr_info->data = vcpu->arch.time;
4109 break;
11c6bffa 4110 case MSR_KVM_SYSTEM_TIME_NEW:
1930e5dd
OU
4111 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4112 return 1;
4113
609e36d3 4114 msr_info->data = vcpu->arch.time;
18068523 4115 break;
344d9588 4116 case MSR_KVM_ASYNC_PF_EN:
1930e5dd
OU
4117 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4118 return 1;
4119
2635b5c4
VK
4120 msr_info->data = vcpu->arch.apf.msr_en_val;
4121 break;
4122 case MSR_KVM_ASYNC_PF_INT:
1930e5dd
OU
4123 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4124 return 1;
4125
2635b5c4 4126 msr_info->data = vcpu->arch.apf.msr_int_val;
344d9588 4127 break;
557a961a 4128 case MSR_KVM_ASYNC_PF_ACK:
0a31df68 4129 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
1930e5dd
OU
4130 return 1;
4131
557a961a
VK
4132 msr_info->data = 0;
4133 break;
c9aaa895 4134 case MSR_KVM_STEAL_TIME:
1930e5dd
OU
4135 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4136 return 1;
4137
609e36d3 4138 msr_info->data = vcpu->arch.st.msr_val;
c9aaa895 4139 break;
1d92128f 4140 case MSR_KVM_PV_EOI_EN:
1930e5dd
OU
4141 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4142 return 1;
4143
609e36d3 4144 msr_info->data = vcpu->arch.pv_eoi.msr_val;
1d92128f 4145 break;
2d5ba19b 4146 case MSR_KVM_POLL_CONTROL:
1930e5dd
OU
4147 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4148 return 1;
4149
2d5ba19b
MT
4150 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4151 break;
890ca9ae
HY
4152 case MSR_IA32_P5_MC_ADDR:
4153 case MSR_IA32_P5_MC_TYPE:
4154 case MSR_IA32_MCG_CAP:
4155 case MSR_IA32_MCG_CTL:
4156 case MSR_IA32_MCG_STATUS:
81760dcc 4157 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
281b5278 4158 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
44883f01
PB
4159 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4160 msr_info->host_initiated);
864e2ab2
AL
4161 case MSR_IA32_XSS:
4162 if (!msr_info->host_initiated &&
4163 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4164 return 1;
4165 msr_info->data = vcpu->arch.ia32_xss;
4166 break;
84e0cefa
JS
4167 case MSR_K7_CLK_CTL:
4168 /*
4169 * Provide expected ramp-up count for K7. All other
4170 * are set to zero, indicating minimum divisors for
4171 * every field.
4172 *
4173 * This prevents guest kernels on AMD host with CPU
4174 * type 6, model 8 and higher from exploding due to
4175 * the rdmsr failing.
4176 */
609e36d3 4177 msr_info->data = 0x20000000;
84e0cefa 4178 break;
55cd8e5a 4179 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
f97f5a56
JD
4180 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4181 case HV_X64_MSR_SYNDBG_OPTIONS:
e7d9513b
AS
4182 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4183 case HV_X64_MSR_CRASH_CTL:
1f4b34f8 4184 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
a2e164e7
VK
4185 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4186 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4187 case HV_X64_MSR_TSC_EMULATION_STATUS:
e83d5887 4188 return kvm_hv_get_msr_common(vcpu,
44883f01
PB
4189 msr_info->index, &msr_info->data,
4190 msr_info->host_initiated);
91c9c3ed 4191 case MSR_IA32_BBL_CR_CTL3:
4192 /* This legacy MSR exists but isn't fully documented in current
4193 * silicon. It is however accessed by winxp in very narrow
4194 * scenarios where it sets bit #19, itself documented as
4195 * a "reserved" bit. Best effort attempt to source coherent
4196 * read data here should the balance of the register be
4197 * interpreted by the guest:
4198 *
4199 * L2 cache control register 3: 64GB range, 256KB size,
4200 * enabled, latency 0x1, configured
4201 */
609e36d3 4202 msr_info->data = 0xbe702111;
91c9c3ed 4203 break;
2b036c6b 4204 case MSR_AMD64_OSVW_ID_LENGTH:
d6321d49 4205 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 4206 return 1;
609e36d3 4207 msr_info->data = vcpu->arch.osvw.length;
2b036c6b
BO
4208 break;
4209 case MSR_AMD64_OSVW_STATUS:
d6321d49 4210 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2b036c6b 4211 return 1;
609e36d3 4212 msr_info->data = vcpu->arch.osvw.status;
2b036c6b 4213 break;
db2336a8 4214 case MSR_PLATFORM_INFO:
6fbbde9a
DS
4215 if (!msr_info->host_initiated &&
4216 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4217 return 1;
db2336a8
KH
4218 msr_info->data = vcpu->arch.msr_platform_info;
4219 break;
4220 case MSR_MISC_FEATURES_ENABLES:
4221 msr_info->data = vcpu->arch.msr_misc_features_enables;
4222 break;
191c8137
BP
4223 case MSR_K7_HWCR:
4224 msr_info->data = vcpu->arch.msr_hwcr;
4225 break;
820a6ee9
JL
4226#ifdef CONFIG_X86_64
4227 case MSR_IA32_XFD:
4228 if (!msr_info->host_initiated &&
4229 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4230 return 1;
4231
4232 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4233 break;
548e8365
JL
4234 case MSR_IA32_XFD_ERR:
4235 if (!msr_info->host_initiated &&
4236 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4237 return 1;
4238
4239 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4240 break;
820a6ee9 4241#endif
15c4a640 4242 default:
c6702c9d 4243 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
cbd71758 4244 return kvm_pmu_get_msr(vcpu, msr_info);
6abe9c13 4245 return KVM_MSR_RET_INVALID;
15c4a640 4246 }
15c4a640
CO
4247 return 0;
4248}
4249EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4250
313a3dc7
CO
4251/*
4252 * Read or write a bunch of msrs. All parameters are kernel addresses.
4253 *
4254 * @return number of msrs set successfully.
4255 */
4256static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4257 struct kvm_msr_entry *entries,
4258 int (*do_msr)(struct kvm_vcpu *vcpu,
4259 unsigned index, u64 *data))
4260{
801e459a 4261 int i;
313a3dc7 4262
313a3dc7
CO
4263 for (i = 0; i < msrs->nmsrs; ++i)
4264 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4265 break;
4266
313a3dc7
CO
4267 return i;
4268}
4269
4270/*
4271 * Read or write a bunch of msrs. Parameters are user addresses.
4272 *
4273 * @return number of msrs set successfully.
4274 */
4275static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4276 int (*do_msr)(struct kvm_vcpu *vcpu,
4277 unsigned index, u64 *data),
4278 int writeback)
4279{
4280 struct kvm_msrs msrs;
4281 struct kvm_msr_entry *entries;
4282 int r, n;
4283 unsigned size;
4284
4285 r = -EFAULT;
0e96f31e 4286 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
313a3dc7
CO
4287 goto out;
4288
4289 r = -E2BIG;
4290 if (msrs.nmsrs >= MAX_IO_MSRS)
4291 goto out;
4292
313a3dc7 4293 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
ff5c2c03
SL
4294 entries = memdup_user(user_msrs->entries, size);
4295 if (IS_ERR(entries)) {
4296 r = PTR_ERR(entries);
313a3dc7 4297 goto out;
ff5c2c03 4298 }
313a3dc7
CO
4299
4300 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
4301 if (r < 0)
4302 goto out_free;
4303
4304 r = -EFAULT;
4305 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4306 goto out_free;
4307
4308 r = n;
4309
4310out_free:
7a73c028 4311 kfree(entries);
313a3dc7
CO
4312out:
4313 return r;
4314}
4315
4d5422ce
WL
4316static inline bool kvm_can_mwait_in_guest(void)
4317{
4318 return boot_cpu_has(X86_FEATURE_MWAIT) &&
8e9b29b6
KA
4319 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4320 boot_cpu_has(X86_FEATURE_ARAT);
4d5422ce
WL
4321}
4322
c21d54f0
VK
4323static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4324 struct kvm_cpuid2 __user *cpuid_arg)
4325{
4326 struct kvm_cpuid2 cpuid;
4327 int r;
4328
4329 r = -EFAULT;
4330 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4331 return r;
4332
4333 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4334 if (r)
4335 return r;
4336
4337 r = -EFAULT;
4338 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4339 return r;
4340
4341 return 0;
4342}
4343
784aa3d7 4344int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
018d00d2 4345{
4d5422ce 4346 int r = 0;
018d00d2
ZX
4347
4348 switch (ext) {
4349 case KVM_CAP_IRQCHIP:
4350 case KVM_CAP_HLT:
4351 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
018d00d2 4352 case KVM_CAP_SET_TSS_ADDR:
07716717 4353 case KVM_CAP_EXT_CPUID:
9c15bb1d 4354 case KVM_CAP_EXT_EMUL_CPUID:
c8076604 4355 case KVM_CAP_CLOCKSOURCE:
7837699f 4356 case KVM_CAP_PIT:
a28e4f5a 4357 case KVM_CAP_NOP_IO_DELAY:
62d9f0db 4358 case KVM_CAP_MP_STATE:
ed848624 4359 case KVM_CAP_SYNC_MMU:
a355c85c 4360 case KVM_CAP_USER_NMI:
52d939a0 4361 case KVM_CAP_REINJECT_CONTROL:
4925663a 4362 case KVM_CAP_IRQ_INJECT_STATUS:
d34e6b17 4363 case KVM_CAP_IOEVENTFD:
f848a5a8 4364 case KVM_CAP_IOEVENTFD_NO_LENGTH:
c5ff41ce 4365 case KVM_CAP_PIT2:
e9f42757 4366 case KVM_CAP_PIT_STATE2:
b927a3ce 4367 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3cfc3092 4368 case KVM_CAP_VCPU_EVENTS:
55cd8e5a 4369 case KVM_CAP_HYPERV:
10388a07 4370 case KVM_CAP_HYPERV_VAPIC:
c25bc163 4371 case KVM_CAP_HYPERV_SPIN:
5c919412 4372 case KVM_CAP_HYPERV_SYNIC:
efc479e6 4373 case KVM_CAP_HYPERV_SYNIC2:
d3457c87 4374 case KVM_CAP_HYPERV_VP_INDEX:
faeb7833 4375 case KVM_CAP_HYPERV_EVENTFD:
c1aea919 4376 case KVM_CAP_HYPERV_TLBFLUSH:
214ff83d 4377 case KVM_CAP_HYPERV_SEND_IPI:
2bc39970 4378 case KVM_CAP_HYPERV_CPUID:
644f7067 4379 case KVM_CAP_HYPERV_ENFORCE_CPUID:
c21d54f0 4380 case KVM_CAP_SYS_HYPERV_CPUID:
ab9f4ecb 4381 case KVM_CAP_PCI_SEGMENT:
a1efbe77 4382 case KVM_CAP_DEBUGREGS:
d2be1651 4383 case KVM_CAP_X86_ROBUST_SINGLESTEP:
2d5b5a66 4384 case KVM_CAP_XSAVE:
344d9588 4385 case KVM_CAP_ASYNC_PF:
72de5fa4 4386 case KVM_CAP_ASYNC_PF_INT:
92a1f12d 4387 case KVM_CAP_GET_TSC_KHZ:
1c0b28c2 4388 case KVM_CAP_KVMCLOCK_CTRL:
4d8b81ab 4389 case KVM_CAP_READONLY_MEM:
5f66b620 4390 case KVM_CAP_HYPERV_TIME:
100943c5 4391 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
defcf51f 4392 case KVM_CAP_TSC_DEADLINE_TIMER:
90de4a18 4393 case KVM_CAP_DISABLE_QUIRKS:
d71ba788 4394 case KVM_CAP_SET_BOOT_CPU_ID:
49df6397 4395 case KVM_CAP_SPLIT_IRQCHIP:
460df4c1 4396 case KVM_CAP_IMMEDIATE_EXIT:
66bb8a06 4397 case KVM_CAP_PMU_EVENT_FILTER:
801e459a 4398 case KVM_CAP_GET_MSR_FEATURES:
6fbbde9a 4399 case KVM_CAP_MSR_PLATFORM_INFO:
c4f55198 4400 case KVM_CAP_EXCEPTION_PAYLOAD:
ed235117 4401 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
b9b2782c 4402 case KVM_CAP_SET_GUEST_DEBUG:
1aa561b1 4403 case KVM_CAP_LAST_CPU:
1ae09954 4404 case KVM_CAP_X86_USER_SPACE_MSR:
1a155254 4405 case KVM_CAP_X86_MSR_FILTER:
66570e96 4406 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
fe7e9488
SC
4407#ifdef CONFIG_X86_SGX_KVM
4408 case KVM_CAP_SGX_ATTRIBUTE:
4409#endif
54526d1f 4410 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
30d7c5d6 4411 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6dba9403 4412 case KVM_CAP_SREGS2:
19238e75 4413 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
828ca896 4414 case KVM_CAP_VCPU_ATTRIBUTES:
dd6e6312 4415 case KVM_CAP_SYS_ATTRIBUTES:
8a289785 4416 case KVM_CAP_VAPIC:
127770ac 4417 case KVM_CAP_ENABLE_CAP:
084cc29f 4418 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
018d00d2
ZX
4419 r = 1;
4420 break;
0dbb1123
AK
4421 case KVM_CAP_EXIT_HYPERCALL:
4422 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4423 break;
7e582ccb
ML
4424 case KVM_CAP_SET_GUEST_DEBUG2:
4425 return KVM_GUESTDBG_VALID_MASK;
b59b153d 4426#ifdef CONFIG_KVM_XEN
23200b7a
JM
4427 case KVM_CAP_XEN_HVM:
4428 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
8d4e7e80 4429 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
14243b38 4430 KVM_XEN_HVM_CONFIG_SHARED_INFO |
661a20fa
DW
4431 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4432 KVM_XEN_HVM_CONFIG_EVTCHN_SEND;
30b5c851 4433 if (sched_info_on())
d8ba8ba4
DW
4434 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4435 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
23200b7a 4436 break;
b59b153d 4437#endif
01643c51
KH
4438 case KVM_CAP_SYNC_REGS:
4439 r = KVM_SYNC_X86_VALID_FIELDS;
4440 break;
e3fd9a93 4441 case KVM_CAP_ADJUST_CLOCK:
c68dc1b5 4442 r = KVM_CLOCK_VALID_FLAGS;
e3fd9a93 4443 break;
4d5422ce 4444 case KVM_CAP_X86_DISABLE_EXITS:
b5170063
WL
4445 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
4446 KVM_X86_DISABLE_EXITS_CSTATE;
4d5422ce
WL
4447 if(kvm_can_mwait_in_guest())
4448 r |= KVM_X86_DISABLE_EXITS_MWAIT;
668fffa3 4449 break;
6d396b55 4450 case KVM_CAP_X86_SMM:
4b8e1b32
PB
4451 if (!IS_ENABLED(CONFIG_KVM_SMM))
4452 break;
4453
6d396b55
PB
4454 /* SMBASE is usually relocated above 1M on modern chipsets,
4455 * and SMM handlers might indeed rely on 4G segment limits,
4456 * so do not report SMM to be available if real mode is
4457 * emulated via vm86 mode. Still, do not go to great lengths
4458 * to avoid userspace's usage of the feature, because it is a
4459 * fringe case that is not enabled except via specific settings
4460 * of the module parameters.
4461 */
b3646477 4462 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
6d396b55 4463 break;
f725230a 4464 case KVM_CAP_NR_VCPUS:
2845e735 4465 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
8c3ba334
SL
4466 break;
4467 case KVM_CAP_MAX_VCPUS:
f725230a
AK
4468 r = KVM_MAX_VCPUS;
4469 break;
a86cb413 4470 case KVM_CAP_MAX_VCPU_ID:
a1c42dde 4471 r = KVM_MAX_VCPU_IDS;
a86cb413 4472 break;
a68a6a72
MT
4473 case KVM_CAP_PV_MMU: /* obsolete */
4474 r = 0;
2f333bcb 4475 break;
890ca9ae
HY
4476 case KVM_CAP_MCE:
4477 r = KVM_MAX_MCE_BANKS;
4478 break;
2d5b5a66 4479 case KVM_CAP_XCRS:
d366bf7e 4480 r = boot_cpu_has(X86_FEATURE_XSAVE);
2d5b5a66 4481 break;
92a1f12d 4482 case KVM_CAP_TSC_CONTROL:
ffbb61d0 4483 case KVM_CAP_VM_TSC_CONTROL:
938c8745 4484 r = kvm_caps.has_tsc_control;
92a1f12d 4485 break;
37131313
RK
4486 case KVM_CAP_X2APIC_API:
4487 r = KVM_X2APIC_API_VALID_FLAGS;
4488 break;
8fcc4b59 4489 case KVM_CAP_NESTED_STATE:
33b22172
PB
4490 r = kvm_x86_ops.nested_ops->get_state ?
4491 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
8fcc4b59 4492 break;
344c6c80 4493 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
b83237ad 4494 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
5a0165f6
VK
4495 break;
4496 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
33b22172 4497 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
344c6c80 4498 break;
3edd6839
MG
4499 case KVM_CAP_SMALLER_MAXPHYADDR:
4500 r = (int) allow_smaller_maxphyaddr;
4501 break;
004a0124
AJ
4502 case KVM_CAP_STEAL_TIME:
4503 r = sched_info_on();
4504 break;
fe6b6bc8 4505 case KVM_CAP_X86_BUS_LOCK_EXIT:
938c8745 4506 if (kvm_caps.has_bus_lock_exit)
fe6b6bc8
CQ
4507 r = KVM_BUS_LOCK_DETECTION_OFF |
4508 KVM_BUS_LOCK_DETECTION_EXIT;
4509 else
4510 r = 0;
4511 break;
be50b206
GZ
4512 case KVM_CAP_XSAVE2: {
4513 u64 guest_perm = xstate_get_guest_group_perm();
4514
938c8745 4515 r = xstate_required_size(kvm_caps.supported_xcr0 & guest_perm, false);
be50b206
GZ
4516 if (r < sizeof(struct kvm_xsave))
4517 r = sizeof(struct kvm_xsave);
4518 break;
1c4dc573 4519 }
ba7bb663
DD
4520 case KVM_CAP_PMU_CAPABILITY:
4521 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4522 break;
6d849191
OU
4523 case KVM_CAP_DISABLE_QUIRKS2:
4524 r = KVM_X86_VALID_QUIRKS;
4525 break;
2f4073e0
TX
4526 case KVM_CAP_X86_NOTIFY_VMEXIT:
4527 r = kvm_caps.has_notify_vmexit;
4528 break;
018d00d2 4529 default:
018d00d2
ZX
4530 break;
4531 }
4532 return r;
56f289a8
SC
4533}
4534
4535static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
4536{
4537 void __user *uaddr = (void __user*)(unsigned long)attr->addr;
018d00d2 4538
56f289a8 4539 if ((u64)(unsigned long)uaddr != attr->addr)
6e37ec88 4540 return ERR_PTR_USR(-EFAULT);
56f289a8 4541 return uaddr;
018d00d2
ZX
4542}
4543
dd6e6312
PB
4544static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4545{
4546 u64 __user *uaddr = kvm_get_attr_addr(attr);
4547
4548 if (attr->group)
4549 return -ENXIO;
4550
4551 if (IS_ERR(uaddr))
4552 return PTR_ERR(uaddr);
4553
4554 switch (attr->attr) {
4555 case KVM_X86_XCOMP_GUEST_SUPP:
938c8745 4556 if (put_user(kvm_caps.supported_xcr0, uaddr))
dd6e6312
PB
4557 return -EFAULT;
4558 return 0;
4559 default:
4560 return -ENXIO;
4561 break;
4562 }
4563}
4564
4565static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4566{
4567 if (attr->group)
4568 return -ENXIO;
4569
4570 switch (attr->attr) {
4571 case KVM_X86_XCOMP_GUEST_SUPP:
4572 return 0;
4573 default:
4574 return -ENXIO;
4575 }
4576}
4577
043405e1
CO
4578long kvm_arch_dev_ioctl(struct file *filp,
4579 unsigned int ioctl, unsigned long arg)
4580{
4581 void __user *argp = (void __user *)arg;
4582 long r;
4583
4584 switch (ioctl) {
4585 case KVM_GET_MSR_INDEX_LIST: {
4586 struct kvm_msr_list __user *user_msr_list = argp;
4587 struct kvm_msr_list msr_list;
4588 unsigned n;
4589
4590 r = -EFAULT;
0e96f31e 4591 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
043405e1
CO
4592 goto out;
4593 n = msr_list.nmsrs;
62ef68bb 4594 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
0e96f31e 4595 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
043405e1
CO
4596 goto out;
4597 r = -E2BIG;
e125e7b6 4598 if (n < msr_list.nmsrs)
043405e1
CO
4599 goto out;
4600 r = -EFAULT;
4601 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4602 num_msrs_to_save * sizeof(u32)))
4603 goto out;
e125e7b6 4604 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
043405e1 4605 &emulated_msrs,
62ef68bb 4606 num_emulated_msrs * sizeof(u32)))
043405e1
CO
4607 goto out;
4608 r = 0;
4609 break;
4610 }
9c15bb1d
BP
4611 case KVM_GET_SUPPORTED_CPUID:
4612 case KVM_GET_EMULATED_CPUID: {
674eea0f
AK
4613 struct kvm_cpuid2 __user *cpuid_arg = argp;
4614 struct kvm_cpuid2 cpuid;
4615
4616 r = -EFAULT;
0e96f31e 4617 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
674eea0f 4618 goto out;
9c15bb1d
BP
4619
4620 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4621 ioctl);
674eea0f
AK
4622 if (r)
4623 goto out;
4624
4625 r = -EFAULT;
0e96f31e 4626 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
674eea0f
AK
4627 goto out;
4628 r = 0;
4629 break;
4630 }
cf6c26ec 4631 case KVM_X86_GET_MCE_CAP_SUPPORTED:
890ca9ae 4632 r = -EFAULT;
938c8745
SC
4633 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4634 sizeof(kvm_caps.supported_mce_cap)))
890ca9ae
HY
4635 goto out;
4636 r = 0;
4637 break;
801e459a
TL
4638 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4639 struct kvm_msr_list __user *user_msr_list = argp;
4640 struct kvm_msr_list msr_list;
4641 unsigned int n;
4642
4643 r = -EFAULT;
4644 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4645 goto out;
4646 n = msr_list.nmsrs;
4647 msr_list.nmsrs = num_msr_based_features;
4648 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4649 goto out;
4650 r = -E2BIG;
4651 if (n < msr_list.nmsrs)
4652 goto out;
4653 r = -EFAULT;
4654 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4655 num_msr_based_features * sizeof(u32)))
4656 goto out;
4657 r = 0;
4658 break;
4659 }
4660 case KVM_GET_MSRS:
4661 r = msr_io(NULL, argp, do_get_msr_feature, 1);
4662 break;
c21d54f0
VK
4663 case KVM_GET_SUPPORTED_HV_CPUID:
4664 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4665 break;
dd6e6312
PB
4666 case KVM_GET_DEVICE_ATTR: {
4667 struct kvm_device_attr attr;
4668 r = -EFAULT;
4669 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4670 break;
4671 r = kvm_x86_dev_get_attr(&attr);
4672 break;
4673 }
4674 case KVM_HAS_DEVICE_ATTR: {
4675 struct kvm_device_attr attr;
4676 r = -EFAULT;
4677 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4678 break;
4679 r = kvm_x86_dev_has_attr(&attr);
4680 break;
4681 }
043405e1
CO
4682 default:
4683 r = -EINVAL;
cf6c26ec 4684 break;
043405e1
CO
4685 }
4686out:
4687 return r;
4688}
4689
f5f48ee1
SY
4690static void wbinvd_ipi(void *garbage)
4691{
4692 wbinvd();
4693}
4694
4695static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4696{
e0f0bbc5 4697 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
f5f48ee1
SY
4698}
4699
313a3dc7
CO
4700void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4701{
f5f48ee1
SY
4702 /* Address WBINVD may be executed by guest */
4703 if (need_emulate_wbinvd(vcpu)) {
b3646477 4704 if (static_call(kvm_x86_has_wbinvd_exit)())
f5f48ee1
SY
4705 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4706 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4707 smp_call_function_single(vcpu->cpu,
4708 wbinvd_ipi, NULL, 1);
4709 }
4710
b3646477 4711 static_call(kvm_x86_vcpu_load)(vcpu, cpu);
8f6055cb 4712
37486135
BM
4713 /* Save host pkru register if supported */
4714 vcpu->arch.host_pkru = read_pkru();
4715
0dd6a6ed
ZA
4716 /* Apply any externally detected TSC adjustments (due to suspend) */
4717 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4718 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4719 vcpu->arch.tsc_offset_adjustment = 0;
105b21bb 4720 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed 4721 }
8f6055cb 4722
b0c39dc6 4723 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
6f526ec5 4724 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4ea1636b 4725 rdtsc() - vcpu->arch.last_host_tsc;
e48672fa
ZA
4726 if (tsc_delta < 0)
4727 mark_tsc_unstable("KVM discovered backwards TSC");
ce7a058a 4728
b0c39dc6 4729 if (kvm_check_tsc_unstable()) {
9b399dfd 4730 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
b183aa58 4731 vcpu->arch.last_guest_tsc);
a545ab6a 4732 kvm_vcpu_write_tsc_offset(vcpu, offset);
c285545f 4733 vcpu->arch.tsc_catchup = 1;
c285545f 4734 }
a749e247
PB
4735
4736 if (kvm_lapic_hv_timer_in_use(vcpu))
4737 kvm_lapic_restart_hv_timer(vcpu);
4738
d98d07ca
MT
4739 /*
4740 * On a host with synchronized TSC, there is no need to update
4741 * kvmclock on vcpu->cpu migration
4742 */
4743 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
0061d53d 4744 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
c285545f 4745 if (vcpu->cpu != cpu)
1bd2009e 4746 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
e48672fa 4747 vcpu->cpu = cpu;
6b7d7e76 4748 }
c9aaa895 4749
c9aaa895 4750 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
313a3dc7
CO
4751}
4752
0b9f6c46
PX
4753static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4754{
7e2175eb
DW
4755 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
4756 struct kvm_steal_time __user *st;
4757 struct kvm_memslots *slots;
4758 static const u8 preempted = KVM_VCPU_PREEMPTED;
c3c28d24 4759 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
b0431382 4760
6cd88243
PB
4761 /*
4762 * The vCPU can be marked preempted if and only if the VM-Exit was on
4763 * an instruction boundary and will not trigger guest emulation of any
4764 * kind (see vcpu_run). Vendor specific code controls (conservatively)
4765 * when this is true, for example allowing the vCPU to be marked
4766 * preempted if and only if the VM-Exit was due to a host interrupt.
4767 */
4768 if (!vcpu->arch.at_instruction_boundary) {
4769 vcpu->stat.preemption_other++;
4770 return;
4771 }
4772
4773 vcpu->stat.preemption_reported++;
0b9f6c46
PX
4774 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4775 return;
4776
a6bd811f 4777 if (vcpu->arch.st.preempted)
8c6de56a
BO
4778 return;
4779
7e2175eb
DW
4780 /* This happens on process exit */
4781 if (unlikely(current->mm != vcpu->kvm->mm))
9c1a0744 4782 return;
b0431382 4783
7e2175eb
DW
4784 slots = kvm_memslots(vcpu->kvm);
4785
4786 if (unlikely(slots->generation != ghc->generation ||
c3c28d24 4787 gpa != ghc->gpa ||
7e2175eb 4788 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
9c1a0744 4789 return;
b0431382 4790
7e2175eb
DW
4791 st = (struct kvm_steal_time __user *)ghc->hva;
4792 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
0b9f6c46 4793
7e2175eb
DW
4794 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
4795 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
0b9f6c46 4796
7e2175eb 4797 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
0b9f6c46
PX
4798}
4799
313a3dc7
CO
4800void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4801{
9c1a0744
WL
4802 int idx;
4803
54aa83c9
PB
4804 if (vcpu->preempted) {
4805 if (!vcpu->arch.guest_state_protected)
4806 vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
de63ad4c 4807
54aa83c9
PB
4808 /*
4809 * Take the srcu lock as memslots will be accessed to check the gfn
4810 * cache generation against the memslots generation.
4811 */
4812 idx = srcu_read_lock(&vcpu->kvm->srcu);
4813 if (kvm_xen_msr_enabled(vcpu->kvm))
4814 kvm_xen_runstate_set_preempted(vcpu);
4815 else
4816 kvm_steal_time_set_preempted(vcpu);
4817 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4818 }
30b5c851 4819
b3646477 4820 static_call(kvm_x86_vcpu_put)(vcpu);
4ea1636b 4821 vcpu->arch.last_host_tsc = rdtsc();
313a3dc7
CO
4822}
4823
313a3dc7
CO
4824static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4825 struct kvm_lapic_state *s)
4826{
37c4dbf3 4827 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
d62caabb 4828
a92e2543 4829 return kvm_apic_get_state(vcpu, s);
313a3dc7
CO
4830}
4831
4832static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4833 struct kvm_lapic_state *s)
4834{
a92e2543
RK
4835 int r;
4836
4837 r = kvm_apic_set_state(vcpu, s);
4838 if (r)
4839 return r;
cb142eb7 4840 update_cr8_intercept(vcpu);
313a3dc7
CO
4841
4842 return 0;
4843}
4844
127a457a
MG
4845static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4846{
71cc849b
PB
4847 /*
4848 * We can accept userspace's request for interrupt injection
4849 * as long as we have a place to store the interrupt number.
4850 * The actual injection will happen when the CPU is able to
4851 * deliver the interrupt.
4852 */
4853 if (kvm_cpu_has_extint(vcpu))
4854 return false;
4855
4856 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
127a457a
MG
4857 return (!lapic_in_kernel(vcpu) ||
4858 kvm_apic_accept_pic_intr(vcpu));
4859}
4860
782d422b
MG
4861static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4862{
fa7a549d
PB
4863 /*
4864 * Do not cause an interrupt window exit if an exception
4865 * is pending or an event needs reinjection; userspace
4866 * might want to inject the interrupt manually using KVM_SET_REGS
4867 * or KVM_SET_SREGS. For that to work, we must be at an
4868 * instruction boundary and with no events half-injected.
4869 */
4870 return (kvm_arch_interrupt_allowed(vcpu) &&
4871 kvm_cpu_accept_dm_intr(vcpu) &&
4872 !kvm_event_needs_reinjection(vcpu) &&
7709aba8 4873 !kvm_is_exception_pending(vcpu));
782d422b
MG
4874}
4875
f77bc6a4
ZX
4876static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4877 struct kvm_interrupt *irq)
4878{
02cdb50f 4879 if (irq->irq >= KVM_NR_INTERRUPTS)
f77bc6a4 4880 return -EINVAL;
1c1a9ce9
SR
4881
4882 if (!irqchip_in_kernel(vcpu->kvm)) {
4883 kvm_queue_interrupt(vcpu, irq->irq, false);
4884 kvm_make_request(KVM_REQ_EVENT, vcpu);
4885 return 0;
4886 }
4887
4888 /*
4889 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4890 * fail for in-kernel 8259.
4891 */
4892 if (pic_in_kernel(vcpu->kvm))
f77bc6a4 4893 return -ENXIO;
f77bc6a4 4894
1c1a9ce9
SR
4895 if (vcpu->arch.pending_external_vector != -1)
4896 return -EEXIST;
f77bc6a4 4897
1c1a9ce9 4898 vcpu->arch.pending_external_vector = irq->irq;
934bf653 4899 kvm_make_request(KVM_REQ_EVENT, vcpu);
f77bc6a4
ZX
4900 return 0;
4901}
4902
c4abb7c9
JK
4903static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4904{
c4abb7c9 4905 kvm_inject_nmi(vcpu);
c4abb7c9
JK
4906
4907 return 0;
4908}
4909
b209749f
AK
4910static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4911 struct kvm_tpr_access_ctl *tac)
4912{
4913 if (tac->flags)
4914 return -EINVAL;
4915 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4916 return 0;
4917}
4918
890ca9ae
HY
4919static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4920 u64 mcg_cap)
4921{
4922 int r;
4923 unsigned bank_num = mcg_cap & 0xff, bank;
4924
4925 r = -EINVAL;
c4e0e4ab 4926 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
890ca9ae 4927 goto out;
938c8745 4928 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
890ca9ae
HY
4929 goto out;
4930 r = 0;
4931 vcpu->arch.mcg_cap = mcg_cap;
4932 /* Init IA32_MCG_CTL to all 1s */
4933 if (mcg_cap & MCG_CTL_P)
4934 vcpu->arch.mcg_ctl = ~(u64)0;
281b5278
JW
4935 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
4936 for (bank = 0; bank < bank_num; bank++) {
890ca9ae 4937 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
281b5278
JW
4938 if (mcg_cap & MCG_CMCI_P)
4939 vcpu->arch.mci_ctl2_banks[bank] = 0;
4940 }
f83894b2
SC
4941
4942 kvm_apic_after_set_mcg_cap(vcpu);
c45dcc71 4943
b3646477 4944 static_call(kvm_x86_setup_mce)(vcpu);
890ca9ae
HY
4945out:
4946 return r;
4947}
4948
aebc3ca1
JW
4949/*
4950 * Validate this is an UCNA (uncorrectable no action) error by checking the
4951 * MCG_STATUS and MCi_STATUS registers:
4952 * - none of the bits for Machine Check Exceptions are set
4953 * - both the VAL (valid) and UC (uncorrectable) bits are set
4954 * MCI_STATUS_PCC - Processor Context Corrupted
4955 * MCI_STATUS_S - Signaled as a Machine Check Exception
4956 * MCI_STATUS_AR - Software recoverable Action Required
4957 */
4958static bool is_ucna(struct kvm_x86_mce *mce)
4959{
4960 return !mce->mcg_status &&
4961 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
4962 (mce->status & MCI_STATUS_VAL) &&
4963 (mce->status & MCI_STATUS_UC);
4964}
4965
4966static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
4967{
4968 u64 mcg_cap = vcpu->arch.mcg_cap;
4969
4970 banks[1] = mce->status;
4971 banks[2] = mce->addr;
4972 banks[3] = mce->misc;
4973 vcpu->arch.mcg_status = mce->mcg_status;
4974
4975 if (!(mcg_cap & MCG_CMCI_P) ||
4976 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
4977 return 0;
4978
4979 if (lapic_in_kernel(vcpu))
4980 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
4981
4982 return 0;
4983}
4984
890ca9ae
HY
4985static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4986 struct kvm_x86_mce *mce)
4987{
4988 u64 mcg_cap = vcpu->arch.mcg_cap;
4989 unsigned bank_num = mcg_cap & 0xff;
4990 u64 *banks = vcpu->arch.mce_banks;
4991
4992 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4993 return -EINVAL;
aebc3ca1
JW
4994
4995 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
4996
4997 if (is_ucna(mce))
4998 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
4999
890ca9ae
HY
5000 /*
5001 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5002 * reporting is disabled
5003 */
5004 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5005 vcpu->arch.mcg_ctl != ~(u64)0)
5006 return 0;
890ca9ae
HY
5007 /*
5008 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5009 * reporting is disabled for the bank
5010 */
5011 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5012 return 0;
5013 if (mce->status & MCI_STATUS_UC) {
5014 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
fc78f519 5015 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
a8eeb04a 5016 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
890ca9ae
HY
5017 return 0;
5018 }
5019 if (banks[1] & MCI_STATUS_VAL)
5020 mce->status |= MCI_STATUS_OVER;
5021 banks[2] = mce->addr;
5022 banks[3] = mce->misc;
5023 vcpu->arch.mcg_status = mce->mcg_status;
5024 banks[1] = mce->status;
5025 kvm_queue_exception(vcpu, MC_VECTOR);
5026 } else if (!(banks[1] & MCI_STATUS_VAL)
5027 || !(banks[1] & MCI_STATUS_UC)) {
5028 if (banks[1] & MCI_STATUS_VAL)
5029 mce->status |= MCI_STATUS_OVER;
5030 banks[2] = mce->addr;
5031 banks[3] = mce->misc;
5032 banks[1] = mce->status;
5033 } else
5034 banks[1] |= MCI_STATUS_OVER;
5035 return 0;
5036}
5037
3cfc3092
JK
5038static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5039 struct kvm_vcpu_events *events)
5040{
7709aba8 5041 struct kvm_queued_exception *ex;
d4963e31 5042
7460fb4a 5043 process_nmi(vcpu);
59073aaf 5044
cf7316d0 5045#ifdef CONFIG_KVM_SMM
1f7becf1
JZ
5046 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5047 process_smi(vcpu);
cf7316d0 5048#endif
1f7becf1 5049
a06230b6 5050 /*
7709aba8
SC
5051 * KVM's ABI only allows for one exception to be migrated. Luckily,
5052 * the only time there can be two queued exceptions is if there's a
5053 * non-exiting _injected_ exception, and a pending exiting exception.
5054 * In that case, ignore the VM-Exiting exception as it's an extension
5055 * of the injected exception.
5056 */
5057 if (vcpu->arch.exception_vmexit.pending &&
5058 !vcpu->arch.exception.pending &&
5059 !vcpu->arch.exception.injected)
5060 ex = &vcpu->arch.exception_vmexit;
5061 else
5062 ex = &vcpu->arch.exception;
5063
a06230b6 5064 /*
d4963e31
SC
5065 * In guest mode, payload delivery should be deferred if the exception
5066 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5067 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5068 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5069 * propagate the payload and so it cannot be safely deferred. Deliver
5070 * the payload if the capability hasn't been requested.
a06230b6
OU
5071 */
5072 if (!vcpu->kvm->arch.exception_payload_enabled &&
d4963e31
SC
5073 ex->pending && ex->has_payload)
5074 kvm_deliver_exception_payload(vcpu, ex);
a06230b6 5075
85672346
PB
5076 memset(events, 0, sizeof(*events));
5077
664f8e26 5078 /*
59073aaf
JM
5079 * The API doesn't provide the instruction length for software
5080 * exceptions, so don't report them. As long as the guest RIP
5081 * isn't advanced, we should expect to encounter the exception
5082 * again.
664f8e26 5083 */
85672346 5084 if (!kvm_exception_is_soft(ex->vector)) {
d4963e31
SC
5085 events->exception.injected = ex->injected;
5086 events->exception.pending = ex->pending;
59073aaf
JM
5087 /*
5088 * For ABI compatibility, deliberately conflate
5089 * pending and injected exceptions when
5090 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5091 */
5092 if (!vcpu->kvm->arch.exception_payload_enabled)
d4963e31 5093 events->exception.injected |= ex->pending;
59073aaf 5094 }
d4963e31
SC
5095 events->exception.nr = ex->vector;
5096 events->exception.has_error_code = ex->has_error_code;
5097 events->exception.error_code = ex->error_code;
5098 events->exception_has_payload = ex->has_payload;
5099 events->exception_payload = ex->payload;
3cfc3092 5100
03b82a30 5101 events->interrupt.injected =
04140b41 5102 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
3cfc3092 5103 events->interrupt.nr = vcpu->arch.interrupt.nr;
b3646477 5104 events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
3cfc3092
JK
5105
5106 events->nmi.injected = vcpu->arch.nmi_injected;
7460fb4a 5107 events->nmi.pending = vcpu->arch.nmi_pending != 0;
b3646477 5108 events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
3cfc3092 5109
85672346 5110 /* events->sipi_vector is never valid when reporting to user space */
3cfc3092 5111
a7662aa5 5112#ifdef CONFIG_KVM_SMM
f077825a
PB
5113 events->smi.smm = is_smm(vcpu);
5114 events->smi.pending = vcpu->arch.smi_pending;
5115 events->smi.smm_inside_nmi =
5116 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
a7662aa5 5117#endif
f077825a
PB
5118 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5119
dab4b911 5120 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
f077825a
PB
5121 | KVM_VCPUEVENT_VALID_SHADOW
5122 | KVM_VCPUEVENT_VALID_SMM);
59073aaf
JM
5123 if (vcpu->kvm->arch.exception_payload_enabled)
5124 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
ed235117
CQ
5125 if (vcpu->kvm->arch.triple_fault_event) {
5126 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5127 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5128 }
3cfc3092
JK
5129}
5130
5131static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5132 struct kvm_vcpu_events *events)
5133{
dab4b911 5134 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64 5135 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
f077825a 5136 | KVM_VCPUEVENT_VALID_SHADOW
59073aaf 5137 | KVM_VCPUEVENT_VALID_SMM
ed235117
CQ
5138 | KVM_VCPUEVENT_VALID_PAYLOAD
5139 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
3cfc3092
JK
5140 return -EINVAL;
5141
59073aaf
JM
5142 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5143 if (!vcpu->kvm->arch.exception_payload_enabled)
5144 return -EINVAL;
5145 if (events->exception.pending)
5146 events->exception.injected = 0;
5147 else
5148 events->exception_has_payload = 0;
5149 } else {
5150 events->exception.pending = 0;
5151 events->exception_has_payload = 0;
5152 }
5153
5154 if ((events->exception.injected || events->exception.pending) &&
5155 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
78e546c8
PB
5156 return -EINVAL;
5157
28bf2888
DH
5158 /* INITs are latched while in SMM */
5159 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5160 (events->smi.smm || events->smi.pending) &&
5161 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5162 return -EINVAL;
5163
7460fb4a 5164 process_nmi(vcpu);
7709aba8
SC
5165
5166 /*
5167 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5168 * morph the exception to a VM-Exit if appropriate. Do this only for
5169 * pending exceptions, already-injected exceptions are not subject to
5170 * intercpetion. Note, userspace that conflates pending and injected
5171 * is hosed, and will incorrectly convert an injected exception into a
5172 * pending exception, which in turn may cause a spurious VM-Exit.
5173 */
5174 vcpu->arch.exception_from_userspace = events->exception.pending;
5175
5176 vcpu->arch.exception_vmexit.pending = false;
5177
59073aaf
JM
5178 vcpu->arch.exception.injected = events->exception.injected;
5179 vcpu->arch.exception.pending = events->exception.pending;
d4963e31 5180 vcpu->arch.exception.vector = events->exception.nr;
3cfc3092
JK
5181 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5182 vcpu->arch.exception.error_code = events->exception.error_code;
59073aaf
JM
5183 vcpu->arch.exception.has_payload = events->exception_has_payload;
5184 vcpu->arch.exception.payload = events->exception_payload;
3cfc3092 5185
04140b41 5186 vcpu->arch.interrupt.injected = events->interrupt.injected;
3cfc3092
JK
5187 vcpu->arch.interrupt.nr = events->interrupt.nr;
5188 vcpu->arch.interrupt.soft = events->interrupt.soft;
48005f64 5189 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
b3646477
JB
5190 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
5191 events->interrupt.shadow);
3cfc3092
JK
5192
5193 vcpu->arch.nmi_injected = events->nmi.injected;
dab4b911
JK
5194 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
5195 vcpu->arch.nmi_pending = events->nmi.pending;
b3646477 5196 static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
3cfc3092 5197
66450a21 5198 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
bce87cce 5199 lapic_in_kernel(vcpu))
66450a21 5200 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3cfc3092 5201
f077825a 5202 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4b8e1b32 5203#ifdef CONFIG_KVM_SMM
f7e57078 5204 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
f9697df2 5205 kvm_leave_nested(vcpu);
dc87275f 5206 kvm_smm_changed(vcpu, events->smi.smm);
f7e57078 5207 }
6ef4e07e 5208
f077825a 5209 vcpu->arch.smi_pending = events->smi.pending;
f4ef1910
WL
5210
5211 if (events->smi.smm) {
5212 if (events->smi.smm_inside_nmi)
5213 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
f077825a 5214 else
f4ef1910 5215 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
ff90afa7
LA
5216 }
5217
4b8e1b32
PB
5218#else
5219 if (events->smi.smm || events->smi.pending ||
5220 events->smi.smm_inside_nmi)
5221 return -EINVAL;
5222#endif
5223
ff90afa7
LA
5224 if (lapic_in_kernel(vcpu)) {
5225 if (events->smi.latched_init)
5226 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5227 else
5228 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
f077825a
PB
5229 }
5230 }
5231
ed235117
CQ
5232 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5233 if (!vcpu->kvm->arch.triple_fault_event)
5234 return -EINVAL;
5235 if (events->triple_fault.pending)
5236 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5237 else
5238 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5239 }
5240
3842d135
AK
5241 kvm_make_request(KVM_REQ_EVENT, vcpu);
5242
3cfc3092
JK
5243 return 0;
5244}
5245
a1efbe77
JK
5246static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5247 struct kvm_debugregs *dbgregs)
5248{
73aaf249
JK
5249 unsigned long val;
5250
a1efbe77 5251 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
16f8a6f9 5252 kvm_get_dr(vcpu, 6, &val);
73aaf249 5253 dbgregs->dr6 = val;
a1efbe77
JK
5254 dbgregs->dr7 = vcpu->arch.dr7;
5255 dbgregs->flags = 0;
97e69aa6 5256 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
a1efbe77
JK
5257}
5258
5259static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5260 struct kvm_debugregs *dbgregs)
5261{
5262 if (dbgregs->flags)
5263 return -EINVAL;
5264
fd238002 5265 if (!kvm_dr6_valid(dbgregs->dr6))
d14bdb55 5266 return -EINVAL;
fd238002 5267 if (!kvm_dr7_valid(dbgregs->dr7))
d14bdb55
PB
5268 return -EINVAL;
5269
a1efbe77 5270 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
ae561ede 5271 kvm_update_dr0123(vcpu);
a1efbe77
JK
5272 vcpu->arch.dr6 = dbgregs->dr6;
5273 vcpu->arch.dr7 = dbgregs->dr7;
9926c9fd 5274 kvm_update_dr7(vcpu);
a1efbe77 5275
a1efbe77
JK
5276 return 0;
5277}
5278
2d5b5a66
SY
5279static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5280 struct kvm_xsave *guest_xsave)
5281{
d69c1382 5282 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
ed02b213
TL
5283 return;
5284
d69c1382
TG
5285 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5286 guest_xsave->region,
5287 sizeof(guest_xsave->region),
5288 vcpu->arch.pkru);
2d5b5a66
SY
5289}
5290
be50b206
GZ
5291static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5292 u8 *state, unsigned int size)
5293{
5294 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5295 return;
5296
5297 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5298 state, size, vcpu->arch.pkru);
5299}
5300
2d5b5a66
SY
5301static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5302 struct kvm_xsave *guest_xsave)
5303{
d69c1382 5304 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
ed02b213
TL
5305 return 0;
5306
d69c1382
TG
5307 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5308 guest_xsave->region,
938c8745
SC
5309 kvm_caps.supported_xcr0,
5310 &vcpu->arch.pkru);
2d5b5a66
SY
5311}
5312
5313static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5314 struct kvm_xcrs *guest_xcrs)
5315{
d366bf7e 5316 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
2d5b5a66
SY
5317 guest_xcrs->nr_xcrs = 0;
5318 return;
5319 }
5320
5321 guest_xcrs->nr_xcrs = 1;
5322 guest_xcrs->flags = 0;
5323 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5324 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5325}
5326
5327static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5328 struct kvm_xcrs *guest_xcrs)
5329{
5330 int i, r = 0;
5331
d366bf7e 5332 if (!boot_cpu_has(X86_FEATURE_XSAVE))
2d5b5a66
SY
5333 return -EINVAL;
5334
5335 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5336 return -EINVAL;
5337
5338 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5339 /* Only support XCR0 currently */
c67a04cb 5340 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
2d5b5a66 5341 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
c67a04cb 5342 guest_xcrs->xcrs[i].value);
2d5b5a66
SY
5343 break;
5344 }
5345 if (r)
5346 r = -EINVAL;
5347 return r;
5348}
5349
1c0b28c2
EM
5350/*
5351 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5352 * stopped by the hypervisor. This function will be called from the host only.
5353 * EINVAL is returned when the host attempts to set the flag for a guest that
5354 * does not support pv clocks.
5355 */
5356static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5357{
916d3608 5358 if (!vcpu->arch.pv_time.active)
1c0b28c2 5359 return -EINVAL;
51d59c6b 5360 vcpu->arch.pvclock_set_guest_stopped_request = true;
1c0b28c2
EM
5361 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5362 return 0;
5363}
5364
828ca896
OU
5365static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5366 struct kvm_device_attr *attr)
5367{
5368 int r;
5369
5370 switch (attr->attr) {
5371 case KVM_VCPU_TSC_OFFSET:
5372 r = 0;
5373 break;
5374 default:
5375 r = -ENXIO;
5376 }
5377
5378 return r;
5379}
5380
5381static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5382 struct kvm_device_attr *attr)
5383{
56f289a8 5384 u64 __user *uaddr = kvm_get_attr_addr(attr);
828ca896
OU
5385 int r;
5386
56f289a8
SC
5387 if (IS_ERR(uaddr))
5388 return PTR_ERR(uaddr);
828ca896
OU
5389
5390 switch (attr->attr) {
5391 case KVM_VCPU_TSC_OFFSET:
5392 r = -EFAULT;
5393 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5394 break;
5395 r = 0;
5396 break;
5397 default:
5398 r = -ENXIO;
5399 }
5400
5401 return r;
5402}
5403
5404static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5405 struct kvm_device_attr *attr)
5406{
56f289a8 5407 u64 __user *uaddr = kvm_get_attr_addr(attr);
828ca896
OU
5408 struct kvm *kvm = vcpu->kvm;
5409 int r;
5410
56f289a8
SC
5411 if (IS_ERR(uaddr))
5412 return PTR_ERR(uaddr);
828ca896
OU
5413
5414 switch (attr->attr) {
5415 case KVM_VCPU_TSC_OFFSET: {
5416 u64 offset, tsc, ns;
5417 unsigned long flags;
5418 bool matched;
5419
5420 r = -EFAULT;
5421 if (get_user(offset, uaddr))
5422 break;
5423
5424 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5425
5426 matched = (vcpu->arch.virtual_tsc_khz &&
5427 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5428 kvm->arch.last_tsc_offset == offset);
5429
62711e5a 5430 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
828ca896
OU
5431 ns = get_kvmclock_base_ns();
5432
5433 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5434 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5435
5436 r = 0;
5437 break;
5438 }
5439 default:
5440 r = -ENXIO;
5441 }
5442
5443 return r;
5444}
5445
5446static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5447 unsigned int ioctl,
5448 void __user *argp)
5449{
5450 struct kvm_device_attr attr;
5451 int r;
5452
5453 if (copy_from_user(&attr, argp, sizeof(attr)))
5454 return -EFAULT;
5455
5456 if (attr.group != KVM_VCPU_TSC_CTRL)
5457 return -ENXIO;
5458
5459 switch (ioctl) {
5460 case KVM_HAS_DEVICE_ATTR:
5461 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5462 break;
5463 case KVM_GET_DEVICE_ATTR:
5464 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5465 break;
5466 case KVM_SET_DEVICE_ATTR:
5467 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5468 break;
5469 }
5470
5471 return r;
5472}
5473
5c919412
AS
5474static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5475 struct kvm_enable_cap *cap)
5476{
57b119da
VK
5477 int r;
5478 uint16_t vmcs_version;
5479 void __user *user_ptr;
5480
5c919412
AS
5481 if (cap->flags)
5482 return -EINVAL;
5483
5484 switch (cap->cap) {
efc479e6
RK
5485 case KVM_CAP_HYPERV_SYNIC2:
5486 if (cap->args[0])
5487 return -EINVAL;
df561f66 5488 fallthrough;
b2869f28 5489
5c919412 5490 case KVM_CAP_HYPERV_SYNIC:
546d87e5
WL
5491 if (!irqchip_in_kernel(vcpu->kvm))
5492 return -EINVAL;
efc479e6
RK
5493 return kvm_hv_activate_synic(vcpu, cap->cap ==
5494 KVM_CAP_HYPERV_SYNIC2);
57b119da 5495 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
33b22172 5496 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5158917c 5497 return -ENOTTY;
33b22172 5498 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
57b119da
VK
5499 if (!r) {
5500 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5501 if (copy_to_user(user_ptr, &vmcs_version,
5502 sizeof(vmcs_version)))
5503 r = -EFAULT;
5504 }
5505 return r;
344c6c80 5506 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
b83237ad 5507 if (!kvm_x86_ops.enable_l2_tlb_flush)
344c6c80
TL
5508 return -ENOTTY;
5509
b83237ad 5510 return static_call(kvm_x86_enable_l2_tlb_flush)(vcpu);
57b119da 5511
644f7067
VK
5512 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5513 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5514
66570e96
OU
5515 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5516 vcpu->arch.pv_cpuid.enforce = cap->args[0];
01b4f510
OU
5517 if (vcpu->arch.pv_cpuid.enforce)
5518 kvm_update_pv_runtime(vcpu);
66570e96
OU
5519
5520 return 0;
5c919412
AS
5521 default:
5522 return -EINVAL;
5523 }
5524}
5525
313a3dc7
CO
5526long kvm_arch_vcpu_ioctl(struct file *filp,
5527 unsigned int ioctl, unsigned long arg)
5528{
5529 struct kvm_vcpu *vcpu = filp->private_data;
5530 void __user *argp = (void __user *)arg;
5531 int r;
d1ac91d8 5532 union {
6dba9403 5533 struct kvm_sregs2 *sregs2;
d1ac91d8
AK
5534 struct kvm_lapic_state *lapic;
5535 struct kvm_xsave *xsave;
5536 struct kvm_xcrs *xcrs;
5537 void *buffer;
5538 } u;
5539
9b062471
CD
5540 vcpu_load(vcpu);
5541
d1ac91d8 5542 u.buffer = NULL;
313a3dc7
CO
5543 switch (ioctl) {
5544 case KVM_GET_LAPIC: {
2204ae3c 5545 r = -EINVAL;
bce87cce 5546 if (!lapic_in_kernel(vcpu))
2204ae3c 5547 goto out;
254272ce
BG
5548 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5549 GFP_KERNEL_ACCOUNT);
313a3dc7 5550
b772ff36 5551 r = -ENOMEM;
d1ac91d8 5552 if (!u.lapic)
b772ff36 5553 goto out;
d1ac91d8 5554 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
313a3dc7
CO
5555 if (r)
5556 goto out;
5557 r = -EFAULT;
d1ac91d8 5558 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
313a3dc7
CO
5559 goto out;
5560 r = 0;
5561 break;
5562 }
5563 case KVM_SET_LAPIC: {
2204ae3c 5564 r = -EINVAL;
bce87cce 5565 if (!lapic_in_kernel(vcpu))
2204ae3c 5566 goto out;
ff5c2c03 5567 u.lapic = memdup_user(argp, sizeof(*u.lapic));
9b062471
CD
5568 if (IS_ERR(u.lapic)) {
5569 r = PTR_ERR(u.lapic);
5570 goto out_nofree;
5571 }
ff5c2c03 5572
d1ac91d8 5573 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
313a3dc7
CO
5574 break;
5575 }
f77bc6a4
ZX
5576 case KVM_INTERRUPT: {
5577 struct kvm_interrupt irq;
5578
5579 r = -EFAULT;
0e96f31e 5580 if (copy_from_user(&irq, argp, sizeof(irq)))
f77bc6a4
ZX
5581 goto out;
5582 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
f77bc6a4
ZX
5583 break;
5584 }
c4abb7c9
JK
5585 case KVM_NMI: {
5586 r = kvm_vcpu_ioctl_nmi(vcpu);
c4abb7c9
JK
5587 break;
5588 }
f077825a 5589 case KVM_SMI: {
b0b42197 5590 r = kvm_inject_smi(vcpu);
f077825a
PB
5591 break;
5592 }
313a3dc7
CO
5593 case KVM_SET_CPUID: {
5594 struct kvm_cpuid __user *cpuid_arg = argp;
5595 struct kvm_cpuid cpuid;
5596
5597 r = -EFAULT;
0e96f31e 5598 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
313a3dc7
CO
5599 goto out;
5600 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
313a3dc7
CO
5601 break;
5602 }
07716717
DK
5603 case KVM_SET_CPUID2: {
5604 struct kvm_cpuid2 __user *cpuid_arg = argp;
5605 struct kvm_cpuid2 cpuid;
5606
5607 r = -EFAULT;
0e96f31e 5608 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
5609 goto out;
5610 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
19355475 5611 cpuid_arg->entries);
07716717
DK
5612 break;
5613 }
5614 case KVM_GET_CPUID2: {
5615 struct kvm_cpuid2 __user *cpuid_arg = argp;
5616 struct kvm_cpuid2 cpuid;
5617
5618 r = -EFAULT;
0e96f31e 5619 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
07716717
DK
5620 goto out;
5621 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
19355475 5622 cpuid_arg->entries);
07716717
DK
5623 if (r)
5624 goto out;
5625 r = -EFAULT;
0e96f31e 5626 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
07716717
DK
5627 goto out;
5628 r = 0;
5629 break;
5630 }
801e459a
TL
5631 case KVM_GET_MSRS: {
5632 int idx = srcu_read_lock(&vcpu->kvm->srcu);
609e36d3 5633 r = msr_io(vcpu, argp, do_get_msr, 1);
801e459a 5634 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 5635 break;
801e459a
TL
5636 }
5637 case KVM_SET_MSRS: {
5638 int idx = srcu_read_lock(&vcpu->kvm->srcu);
313a3dc7 5639 r = msr_io(vcpu, argp, do_set_msr, 0);
801e459a 5640 srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc7 5641 break;
801e459a 5642 }
b209749f
AK
5643 case KVM_TPR_ACCESS_REPORTING: {
5644 struct kvm_tpr_access_ctl tac;
5645
5646 r = -EFAULT;
0e96f31e 5647 if (copy_from_user(&tac, argp, sizeof(tac)))
b209749f
AK
5648 goto out;
5649 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5650 if (r)
5651 goto out;
5652 r = -EFAULT;
0e96f31e 5653 if (copy_to_user(argp, &tac, sizeof(tac)))
b209749f
AK
5654 goto out;
5655 r = 0;
5656 break;
5657 };
b93463aa
AK
5658 case KVM_SET_VAPIC_ADDR: {
5659 struct kvm_vapic_addr va;
7301d6ab 5660 int idx;
b93463aa
AK
5661
5662 r = -EINVAL;
35754c98 5663 if (!lapic_in_kernel(vcpu))
b93463aa
AK
5664 goto out;
5665 r = -EFAULT;
0e96f31e 5666 if (copy_from_user(&va, argp, sizeof(va)))
b93463aa 5667 goto out;
7301d6ab 5668 idx = srcu_read_lock(&vcpu->kvm->srcu);
fda4e2e8 5669 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
7301d6ab 5670 srcu_read_unlock(&vcpu->kvm->srcu, idx);
b93463aa
AK
5671 break;
5672 }
890ca9ae
HY
5673 case KVM_X86_SETUP_MCE: {
5674 u64 mcg_cap;
5675
5676 r = -EFAULT;
0e96f31e 5677 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
890ca9ae
HY
5678 goto out;
5679 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
5680 break;
5681 }
5682 case KVM_X86_SET_MCE: {
5683 struct kvm_x86_mce mce;
5684
5685 r = -EFAULT;
0e96f31e 5686 if (copy_from_user(&mce, argp, sizeof(mce)))
890ca9ae
HY
5687 goto out;
5688 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
5689 break;
5690 }
3cfc3092
JK
5691 case KVM_GET_VCPU_EVENTS: {
5692 struct kvm_vcpu_events events;
5693
5694 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
5695
5696 r = -EFAULT;
5697 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
5698 break;
5699 r = 0;
5700 break;
5701 }
5702 case KVM_SET_VCPU_EVENTS: {
5703 struct kvm_vcpu_events events;
5704
5705 r = -EFAULT;
5706 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
5707 break;
5708
5709 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
5710 break;
5711 }
a1efbe77
JK
5712 case KVM_GET_DEBUGREGS: {
5713 struct kvm_debugregs dbgregs;
5714
5715 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
5716
5717 r = -EFAULT;
5718 if (copy_to_user(argp, &dbgregs,
5719 sizeof(struct kvm_debugregs)))
5720 break;
5721 r = 0;
5722 break;
5723 }
5724 case KVM_SET_DEBUGREGS: {
5725 struct kvm_debugregs dbgregs;
5726
5727 r = -EFAULT;
5728 if (copy_from_user(&dbgregs, argp,
5729 sizeof(struct kvm_debugregs)))
5730 break;
5731
5732 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
5733 break;
5734 }
2d5b5a66 5735 case KVM_GET_XSAVE: {
be50b206
GZ
5736 r = -EINVAL;
5737 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
5738 break;
5739
254272ce 5740 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
2d5b5a66 5741 r = -ENOMEM;
d1ac91d8 5742 if (!u.xsave)
2d5b5a66
SY
5743 break;
5744
d1ac91d8 5745 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2d5b5a66
SY
5746
5747 r = -EFAULT;
d1ac91d8 5748 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2d5b5a66
SY
5749 break;
5750 r = 0;
5751 break;
5752 }
5753 case KVM_SET_XSAVE: {
be50b206
GZ
5754 int size = vcpu->arch.guest_fpu.uabi_size;
5755
5756 u.xsave = memdup_user(argp, size);
9b062471
CD
5757 if (IS_ERR(u.xsave)) {
5758 r = PTR_ERR(u.xsave);
5759 goto out_nofree;
5760 }
2d5b5a66 5761
d1ac91d8 5762 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2d5b5a66
SY
5763 break;
5764 }
be50b206
GZ
5765
5766 case KVM_GET_XSAVE2: {
5767 int size = vcpu->arch.guest_fpu.uabi_size;
5768
5769 u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
5770 r = -ENOMEM;
5771 if (!u.xsave)
5772 break;
5773
5774 kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
5775
5776 r = -EFAULT;
5777 if (copy_to_user(argp, u.xsave, size))
5778 break;
5779
5780 r = 0;
5781 break;
5782 }
5783
2d5b5a66 5784 case KVM_GET_XCRS: {
254272ce 5785 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
2d5b5a66 5786 r = -ENOMEM;
d1ac91d8 5787 if (!u.xcrs)
2d5b5a66
SY
5788 break;
5789
d1ac91d8 5790 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
5791
5792 r = -EFAULT;
d1ac91d8 5793 if (copy_to_user(argp, u.xcrs,
2d5b5a66
SY
5794 sizeof(struct kvm_xcrs)))
5795 break;
5796 r = 0;
5797 break;
5798 }
5799 case KVM_SET_XCRS: {
ff5c2c03 5800 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
9b062471
CD
5801 if (IS_ERR(u.xcrs)) {
5802 r = PTR_ERR(u.xcrs);
5803 goto out_nofree;
5804 }
2d5b5a66 5805
d1ac91d8 5806 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2d5b5a66
SY
5807 break;
5808 }
92a1f12d
JR
5809 case KVM_SET_TSC_KHZ: {
5810 u32 user_tsc_khz;
5811
5812 r = -EINVAL;
92a1f12d
JR
5813 user_tsc_khz = (u32)arg;
5814
938c8745
SC
5815 if (kvm_caps.has_tsc_control &&
5816 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
92a1f12d
JR
5817 goto out;
5818
cc578287
ZA
5819 if (user_tsc_khz == 0)
5820 user_tsc_khz = tsc_khz;
5821
381d585c
HZ
5822 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
5823 r = 0;
92a1f12d 5824
92a1f12d
JR
5825 goto out;
5826 }
5827 case KVM_GET_TSC_KHZ: {
cc578287 5828 r = vcpu->arch.virtual_tsc_khz;
92a1f12d
JR
5829 goto out;
5830 }
1c0b28c2
EM
5831 case KVM_KVMCLOCK_CTRL: {
5832 r = kvm_set_guest_paused(vcpu);
5833 goto out;
5834 }
5c919412
AS
5835 case KVM_ENABLE_CAP: {
5836 struct kvm_enable_cap cap;
5837
5838 r = -EFAULT;
5839 if (copy_from_user(&cap, argp, sizeof(cap)))
5840 goto out;
5841 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5842 break;
5843 }
8fcc4b59
JM
5844 case KVM_GET_NESTED_STATE: {
5845 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5846 u32 user_data_size;
5847
5848 r = -EINVAL;
33b22172 5849 if (!kvm_x86_ops.nested_ops->get_state)
8fcc4b59
JM
5850 break;
5851
5852 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
26b471c7 5853 r = -EFAULT;
8fcc4b59 5854 if (get_user(user_data_size, &user_kvm_nested_state->size))
26b471c7 5855 break;
8fcc4b59 5856
33b22172
PB
5857 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5858 user_data_size);
8fcc4b59 5859 if (r < 0)
26b471c7 5860 break;
8fcc4b59
JM
5861
5862 if (r > user_data_size) {
5863 if (put_user(r, &user_kvm_nested_state->size))
26b471c7
LA
5864 r = -EFAULT;
5865 else
5866 r = -E2BIG;
5867 break;
8fcc4b59 5868 }
26b471c7 5869
8fcc4b59
JM
5870 r = 0;
5871 break;
5872 }
5873 case KVM_SET_NESTED_STATE: {
5874 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5875 struct kvm_nested_state kvm_state;
ad5996d9 5876 int idx;
8fcc4b59
JM
5877
5878 r = -EINVAL;
33b22172 5879 if (!kvm_x86_ops.nested_ops->set_state)
8fcc4b59
JM
5880 break;
5881
26b471c7 5882 r = -EFAULT;
8fcc4b59 5883 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
26b471c7 5884 break;
8fcc4b59 5885
26b471c7 5886 r = -EINVAL;
8fcc4b59 5887 if (kvm_state.size < sizeof(kvm_state))
26b471c7 5888 break;
8fcc4b59
JM
5889
5890 if (kvm_state.flags &
8cab6507 5891 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
cc440cda
PB
5892 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5893 | KVM_STATE_NESTED_GIF_SET))
26b471c7 5894 break;
8fcc4b59
JM
5895
5896 /* nested_run_pending implies guest_mode. */
8cab6507
VK
5897 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5898 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
26b471c7 5899 break;
8fcc4b59 5900
ad5996d9 5901 idx = srcu_read_lock(&vcpu->kvm->srcu);
33b22172 5902 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
ad5996d9 5903 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8fcc4b59
JM
5904 break;
5905 }
c21d54f0
VK
5906 case KVM_GET_SUPPORTED_HV_CPUID:
5907 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
2bc39970 5908 break;
b59b153d 5909#ifdef CONFIG_KVM_XEN
3e324615
DW
5910 case KVM_XEN_VCPU_GET_ATTR: {
5911 struct kvm_xen_vcpu_attr xva;
5912
5913 r = -EFAULT;
5914 if (copy_from_user(&xva, argp, sizeof(xva)))
5915 goto out;
5916 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5917 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5918 r = -EFAULT;
5919 break;
5920 }
5921 case KVM_XEN_VCPU_SET_ATTR: {
5922 struct kvm_xen_vcpu_attr xva;
5923
5924 r = -EFAULT;
5925 if (copy_from_user(&xva, argp, sizeof(xva)))
5926 goto out;
5927 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5928 break;
5929 }
b59b153d 5930#endif
6dba9403
ML
5931 case KVM_GET_SREGS2: {
5932 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
5933 r = -ENOMEM;
5934 if (!u.sregs2)
5935 goto out;
5936 __get_sregs2(vcpu, u.sregs2);
5937 r = -EFAULT;
5938 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
5939 goto out;
5940 r = 0;
5941 break;
5942 }
5943 case KVM_SET_SREGS2: {
5944 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
5945 if (IS_ERR(u.sregs2)) {
5946 r = PTR_ERR(u.sregs2);
5947 u.sregs2 = NULL;
5948 goto out;
5949 }
5950 r = __set_sregs2(vcpu, u.sregs2);
5951 break;
5952 }
828ca896
OU
5953 case KVM_HAS_DEVICE_ATTR:
5954 case KVM_GET_DEVICE_ATTR:
5955 case KVM_SET_DEVICE_ATTR:
5956 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
5957 break;
313a3dc7
CO
5958 default:
5959 r = -EINVAL;
5960 }
5961out:
d1ac91d8 5962 kfree(u.buffer);
9b062471
CD
5963out_nofree:
5964 vcpu_put(vcpu);
313a3dc7
CO
5965 return r;
5966}
5967
1499fa80 5968vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5b1c1493
CO
5969{
5970 return VM_FAULT_SIGBUS;
5971}
5972
1fe779f8
CO
5973static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5974{
5975 int ret;
5976
5977 if (addr > (unsigned int)(-3 * PAGE_SIZE))
951179ce 5978 return -EINVAL;
b3646477 5979 ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
1fe779f8
CO
5980 return ret;
5981}
5982
b927a3ce
SY
5983static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5984 u64 ident_addr)
5985{
b3646477 5986 return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
b927a3ce
SY
5987}
5988
1fe779f8 5989static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
bc8a3d89 5990 unsigned long kvm_nr_mmu_pages)
1fe779f8
CO
5991{
5992 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5993 return -EINVAL;
5994
79fac95e 5995 mutex_lock(&kvm->slots_lock);
1fe779f8
CO
5996
5997 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
f05e70ac 5998 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1fe779f8 5999
79fac95e 6000 mutex_unlock(&kvm->slots_lock);
1fe779f8
CO
6001 return 0;
6002}
6003
bc8a3d89 6004static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1fe779f8 6005{
39de71ec 6006 return kvm->arch.n_max_mmu_pages;
1fe779f8
CO
6007}
6008
1fe779f8
CO
6009static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6010{
90bca052 6011 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
6012 int r;
6013
6014 r = 0;
6015 switch (chip->chip_id) {
6016 case KVM_IRQCHIP_PIC_MASTER:
90bca052 6017 memcpy(&chip->chip.pic, &pic->pics[0],
1fe779f8
CO
6018 sizeof(struct kvm_pic_state));
6019 break;
6020 case KVM_IRQCHIP_PIC_SLAVE:
90bca052 6021 memcpy(&chip->chip.pic, &pic->pics[1],
1fe779f8
CO
6022 sizeof(struct kvm_pic_state));
6023 break;
6024 case KVM_IRQCHIP_IOAPIC:
33392b49 6025 kvm_get_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
6026 break;
6027 default:
6028 r = -EINVAL;
6029 break;
6030 }
6031 return r;
6032}
6033
6034static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6035{
90bca052 6036 struct kvm_pic *pic = kvm->arch.vpic;
1fe779f8
CO
6037 int r;
6038
6039 r = 0;
6040 switch (chip->chip_id) {
6041 case KVM_IRQCHIP_PIC_MASTER:
90bca052
DH
6042 spin_lock(&pic->lock);
6043 memcpy(&pic->pics[0], &chip->chip.pic,
1fe779f8 6044 sizeof(struct kvm_pic_state));
90bca052 6045 spin_unlock(&pic->lock);
1fe779f8
CO
6046 break;
6047 case KVM_IRQCHIP_PIC_SLAVE:
90bca052
DH
6048 spin_lock(&pic->lock);
6049 memcpy(&pic->pics[1], &chip->chip.pic,
1fe779f8 6050 sizeof(struct kvm_pic_state));
90bca052 6051 spin_unlock(&pic->lock);
1fe779f8
CO
6052 break;
6053 case KVM_IRQCHIP_IOAPIC:
33392b49 6054 kvm_set_ioapic(kvm, &chip->chip.ioapic);
1fe779f8
CO
6055 break;
6056 default:
6057 r = -EINVAL;
6058 break;
6059 }
90bca052 6060 kvm_pic_update_irq(pic);
1fe779f8
CO
6061 return r;
6062}
6063
e0f63cb9
SY
6064static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6065{
34f3941c
RK
6066 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6067
6068 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6069
6070 mutex_lock(&kps->lock);
6071 memcpy(ps, &kps->channels, sizeof(*ps));
6072 mutex_unlock(&kps->lock);
2da29bcc 6073 return 0;
e0f63cb9
SY
6074}
6075
6076static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6077{
0185604c 6078 int i;
09edea72
RK
6079 struct kvm_pit *pit = kvm->arch.vpit;
6080
6081 mutex_lock(&pit->pit_state.lock);
34f3941c 6082 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
0185604c 6083 for (i = 0; i < 3; i++)
09edea72
RK
6084 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6085 mutex_unlock(&pit->pit_state.lock);
2da29bcc 6086 return 0;
e9f42757
BK
6087}
6088
6089static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6090{
e9f42757
BK
6091 mutex_lock(&kvm->arch.vpit->pit_state.lock);
6092 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6093 sizeof(ps->channels));
6094 ps->flags = kvm->arch.vpit->pit_state.flags;
6095 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
97e69aa6 6096 memset(&ps->reserved, 0, sizeof(ps->reserved));
2da29bcc 6097 return 0;
e9f42757
BK
6098}
6099
6100static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6101{
2da29bcc 6102 int start = 0;
0185604c 6103 int i;
e9f42757 6104 u32 prev_legacy, cur_legacy;
09edea72
RK
6105 struct kvm_pit *pit = kvm->arch.vpit;
6106
6107 mutex_lock(&pit->pit_state.lock);
6108 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
e9f42757
BK
6109 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6110 if (!prev_legacy && cur_legacy)
6111 start = 1;
09edea72
RK
6112 memcpy(&pit->pit_state.channels, &ps->channels,
6113 sizeof(pit->pit_state.channels));
6114 pit->pit_state.flags = ps->flags;
0185604c 6115 for (i = 0; i < 3; i++)
09edea72 6116 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
e5e57e7a 6117 start && i == 0);
09edea72 6118 mutex_unlock(&pit->pit_state.lock);
2da29bcc 6119 return 0;
e0f63cb9
SY
6120}
6121
52d939a0
MT
6122static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6123 struct kvm_reinject_control *control)
6124{
71474e2f
RK
6125 struct kvm_pit *pit = kvm->arch.vpit;
6126
71474e2f
RK
6127 /* pit->pit_state.lock was overloaded to prevent userspace from getting
6128 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6129 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
6130 */
6131 mutex_lock(&pit->pit_state.lock);
6132 kvm_pit_set_reinject(pit, control->pit_reinject);
6133 mutex_unlock(&pit->pit_state.lock);
b39c90b6 6134
52d939a0
MT
6135 return 0;
6136}
6137
0dff0846 6138void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
5bb064dc 6139{
a018eba5 6140
88178fd4 6141 /*
a018eba5
SC
6142 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6143 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6144 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6145 * VM-Exit.
88178fd4 6146 */
a018eba5 6147 struct kvm_vcpu *vcpu;
46808a4c 6148 unsigned long i;
a018eba5
SC
6149
6150 kvm_for_each_vcpu(i, vcpu, kvm)
6151 kvm_vcpu_kick(vcpu);
5bb064dc
ZX
6152}
6153
aa2fbe6d
YZ
6154int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6155 bool line_status)
23d43cf9
CD
6156{
6157 if (!irqchip_in_kernel(kvm))
6158 return -ENXIO;
6159
6160 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
aa2fbe6d
YZ
6161 irq_event->irq, irq_event->level,
6162 line_status);
23d43cf9
CD
6163 return 0;
6164}
6165
e5d83c74
PB
6166int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6167 struct kvm_enable_cap *cap)
90de4a18
NA
6168{
6169 int r;
6170
6171 if (cap->flags)
6172 return -EINVAL;
6173
6174 switch (cap->cap) {
6d849191
OU
6175 case KVM_CAP_DISABLE_QUIRKS2:
6176 r = -EINVAL;
6177 if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
6178 break;
6179 fallthrough;
90de4a18
NA
6180 case KVM_CAP_DISABLE_QUIRKS:
6181 kvm->arch.disabled_quirks = cap->args[0];
6182 r = 0;
6183 break;
49df6397
SR
6184 case KVM_CAP_SPLIT_IRQCHIP: {
6185 mutex_lock(&kvm->lock);
b053b2ae
SR
6186 r = -EINVAL;
6187 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6188 goto split_irqchip_unlock;
49df6397
SR
6189 r = -EEXIST;
6190 if (irqchip_in_kernel(kvm))
6191 goto split_irqchip_unlock;
557abc40 6192 if (kvm->created_vcpus)
49df6397
SR
6193 goto split_irqchip_unlock;
6194 r = kvm_setup_empty_irq_routing(kvm);
5c0aea0e 6195 if (r)
49df6397
SR
6196 goto split_irqchip_unlock;
6197 /* Pairs with irqchip_in_kernel. */
6198 smp_wmb();
49776faf 6199 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
b053b2ae 6200 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
320af55a 6201 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
49df6397
SR
6202 r = 0;
6203split_irqchip_unlock:
6204 mutex_unlock(&kvm->lock);
6205 break;
6206 }
37131313
RK
6207 case KVM_CAP_X2APIC_API:
6208 r = -EINVAL;
6209 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6210 break;
6211
6212 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6213 kvm->arch.x2apic_format = true;
c519265f
RK
6214 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6215 kvm->arch.x2apic_broadcast_quirk_disabled = true;
37131313
RK
6216
6217 r = 0;
6218 break;
4d5422ce
WL
6219 case KVM_CAP_X86_DISABLE_EXITS:
6220 r = -EINVAL;
6221 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
6222 break;
6223
6224 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
6225 kvm_can_mwait_in_guest())
6226 kvm->arch.mwait_in_guest = true;
766d3571 6227 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
caa057a2 6228 kvm->arch.hlt_in_guest = true;
b31c114b
WL
6229 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6230 kvm->arch.pause_in_guest = true;
b5170063
WL
6231 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6232 kvm->arch.cstate_in_guest = true;
4d5422ce
WL
6233 r = 0;
6234 break;
6fbbde9a
DS
6235 case KVM_CAP_MSR_PLATFORM_INFO:
6236 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6237 r = 0;
c4f55198
JM
6238 break;
6239 case KVM_CAP_EXCEPTION_PAYLOAD:
6240 kvm->arch.exception_payload_enabled = cap->args[0];
6241 r = 0;
6fbbde9a 6242 break;
ed235117
CQ
6243 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6244 kvm->arch.triple_fault_event = cap->args[0];
6245 r = 0;
6246 break;
1ae09954 6247 case KVM_CAP_X86_USER_SPACE_MSR:
cf5029d5 6248 r = -EINVAL;
db205f7e 6249 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
cf5029d5 6250 break;
1ae09954
AG
6251 kvm->arch.user_space_msr_mask = cap->args[0];
6252 r = 0;
6253 break;
fe6b6bc8
CQ
6254 case KVM_CAP_X86_BUS_LOCK_EXIT:
6255 r = -EINVAL;
6256 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6257 break;
6258
6259 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6260 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6261 break;
6262
938c8745 6263 if (kvm_caps.has_bus_lock_exit &&
fe6b6bc8
CQ
6264 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6265 kvm->arch.bus_lock_detection_enabled = true;
6266 r = 0;
6267 break;
fe7e9488
SC
6268#ifdef CONFIG_X86_SGX_KVM
6269 case KVM_CAP_SGX_ATTRIBUTE: {
6270 unsigned long allowed_attributes = 0;
6271
6272 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6273 if (r)
6274 break;
6275
6276 /* KVM only supports the PROVISIONKEY privileged attribute. */
6277 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6278 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6279 kvm->arch.sgx_provisioning_allowed = true;
6280 else
6281 r = -EINVAL;
6282 break;
6283 }
6284#endif
54526d1f
NT
6285 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6286 r = -EINVAL;
7ad02ef0
SC
6287 if (!kvm_x86_ops.vm_copy_enc_context_from)
6288 break;
6289
6290 r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
6291 break;
b5663931
PG
6292 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6293 r = -EINVAL;
7ad02ef0
SC
6294 if (!kvm_x86_ops.vm_move_enc_context_from)
6295 break;
6296
6297 r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
6298 break;
0dbb1123
AK
6299 case KVM_CAP_EXIT_HYPERCALL:
6300 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6301 r = -EINVAL;
6302 break;
6303 }
6304 kvm->arch.hypercall_exit_enabled = cap->args[0];
6305 r = 0;
6306 break;
19238e75
AL
6307 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6308 r = -EINVAL;
6309 if (cap->args[0] & ~1)
6310 break;
6311 kvm->arch.exit_on_emulation_error = cap->args[0];
6312 r = 0;
6313 break;
ba7bb663
DD
6314 case KVM_CAP_PMU_CAPABILITY:
6315 r = -EINVAL;
6316 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6317 break;
6318
6319 mutex_lock(&kvm->lock);
6320 if (!kvm->created_vcpus) {
6321 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6322 r = 0;
6323 }
6324 mutex_unlock(&kvm->lock);
6325 break;
35875316
ZG
6326 case KVM_CAP_MAX_VCPU_ID:
6327 r = -EINVAL;
6328 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6329 break;
6330
6331 mutex_lock(&kvm->lock);
6332 if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6333 r = 0;
6334 } else if (!kvm->arch.max_vcpu_ids) {
6335 kvm->arch.max_vcpu_ids = cap->args[0];
6336 r = 0;
6337 }
6338 mutex_unlock(&kvm->lock);
6339 break;
2f4073e0
TX
6340 case KVM_CAP_X86_NOTIFY_VMEXIT:
6341 r = -EINVAL;
6342 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6343 break;
6344 if (!kvm_caps.has_notify_vmexit)
6345 break;
6346 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6347 break;
6348 mutex_lock(&kvm->lock);
6349 if (!kvm->created_vcpus) {
6350 kvm->arch.notify_window = cap->args[0] >> 32;
6351 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6352 r = 0;
6353 }
6354 mutex_unlock(&kvm->lock);
6355 break;
084cc29f
BG
6356 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6357 r = -EINVAL;
6358
6359 /*
6360 * Since the risk of disabling NX hugepages is a guest crashing
6361 * the system, ensure the userspace process has permission to
6362 * reboot the system.
6363 *
6364 * Note that unlike the reboot() syscall, the process must have
6365 * this capability in the root namespace because exposing
6366 * /dev/kvm into a container does not limit the scope of the
6367 * iTLB multihit bug to that container. In other words,
6368 * this must use capable(), not ns_capable().
6369 */
6370 if (!capable(CAP_SYS_BOOT)) {
6371 r = -EPERM;
6372 break;
6373 }
6374
6375 if (cap->args[0])
6376 break;
6377
6378 mutex_lock(&kvm->lock);
6379 if (!kvm->created_vcpus) {
6380 kvm->arch.disable_nx_huge_pages = true;
6381 r = 0;
6382 }
6383 mutex_unlock(&kvm->lock);
6384 break;
90de4a18
NA
6385 default:
6386 r = -EINVAL;
6387 break;
6388 }
6389 return r;
6390}
6391
b318e8de
SC
6392static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6393{
6394 struct kvm_x86_msr_filter *msr_filter;
6395
6396 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6397 if (!msr_filter)
6398 return NULL;
6399
6400 msr_filter->default_allow = default_allow;
6401 return msr_filter;
6402}
6403
6404static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
1a155254
AG
6405{
6406 u32 i;
1a155254 6407
b318e8de
SC
6408 if (!msr_filter)
6409 return;
6410
6411 for (i = 0; i < msr_filter->count; i++)
6412 kfree(msr_filter->ranges[i].bitmap);
1a155254 6413
b318e8de 6414 kfree(msr_filter);
1a155254
AG
6415}
6416
b318e8de
SC
6417static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6418 struct kvm_msr_filter_range *user_range)
1a155254 6419{
1a155254
AG
6420 unsigned long *bitmap = NULL;
6421 size_t bitmap_size;
1a155254
AG
6422
6423 if (!user_range->nmsrs)
6424 return 0;
6425
8aff460f 6426 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
aca35288
SC
6427 return -EINVAL;
6428
6429 if (!user_range->flags)
6430 return -EINVAL;
6431
1a155254
AG
6432 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6433 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6434 return -EINVAL;
6435
6436 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6437 if (IS_ERR(bitmap))
6438 return PTR_ERR(bitmap);
6439
aca35288 6440 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
1a155254
AG
6441 .flags = user_range->flags,
6442 .base = user_range->base,
6443 .nmsrs = user_range->nmsrs,
6444 .bitmap = bitmap,
6445 };
6446
b318e8de 6447 msr_filter->count++;
1a155254 6448 return 0;
1a155254
AG
6449}
6450
2e3272bc
AG
6451static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6452 struct kvm_msr_filter *filter)
1a155254 6453{
b318e8de 6454 struct kvm_x86_msr_filter *new_filter, *old_filter;
1a155254 6455 bool default_allow;
043248b3 6456 bool empty = true;
b318e8de 6457 int r = 0;
1a155254
AG
6458 u32 i;
6459
c1340fe3 6460 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
cf5029d5
AL
6461 return -EINVAL;
6462
2e3272bc
AG
6463 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6464 empty &= !filter->ranges[i].nmsrs;
1a155254 6465
2e3272bc 6466 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
043248b3
PB
6467 if (empty && !default_allow)
6468 return -EINVAL;
6469
b318e8de
SC
6470 new_filter = kvm_alloc_msr_filter(default_allow);
6471 if (!new_filter)
6472 return -ENOMEM;
1a155254 6473
2e3272bc
AG
6474 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6475 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
b318e8de
SC
6476 if (r) {
6477 kvm_free_msr_filter(new_filter);
6478 return r;
6479 }
1a155254
AG
6480 }
6481
b318e8de
SC
6482 mutex_lock(&kvm->lock);
6483
6484 /* The per-VM filter is protected by kvm->lock... */
6485 old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
6486
6487 rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
6488 synchronize_srcu(&kvm->srcu);
6489
6490 kvm_free_msr_filter(old_filter);
6491
1a155254
AG
6492 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6493 mutex_unlock(&kvm->lock);
6494
b318e8de 6495 return 0;
1a155254
AG
6496}
6497
1739c701
AG
6498#ifdef CONFIG_KVM_COMPAT
6499/* for KVM_X86_SET_MSR_FILTER */
6500struct kvm_msr_filter_range_compat {
6501 __u32 flags;
6502 __u32 nmsrs;
6503 __u32 base;
6504 __u32 bitmap;
6505};
6506
6507struct kvm_msr_filter_compat {
6508 __u32 flags;
6509 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6510};
6511
6512#define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6513
6514long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6515 unsigned long arg)
6516{
6517 void __user *argp = (void __user *)arg;
6518 struct kvm *kvm = filp->private_data;
6519 long r = -ENOTTY;
6520
6521 switch (ioctl) {
6522 case KVM_X86_SET_MSR_FILTER_COMPAT: {
6523 struct kvm_msr_filter __user *user_msr_filter = argp;
6524 struct kvm_msr_filter_compat filter_compat;
6525 struct kvm_msr_filter filter;
6526 int i;
6527
6528 if (copy_from_user(&filter_compat, user_msr_filter,
6529 sizeof(filter_compat)))
6530 return -EFAULT;
6531
6532 filter.flags = filter_compat.flags;
6533 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6534 struct kvm_msr_filter_range_compat *cr;
6535
6536 cr = &filter_compat.ranges[i];
6537 filter.ranges[i] = (struct kvm_msr_filter_range) {
6538 .flags = cr->flags,
6539 .nmsrs = cr->nmsrs,
6540 .base = cr->base,
6541 .bitmap = (__u8 *)(ulong)cr->bitmap,
6542 };
6543 }
6544
6545 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6546 break;
6547 }
6548 }
6549
6550 return r;
6551}
6552#endif
6553
7d62874f
SS
6554#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6555static int kvm_arch_suspend_notifier(struct kvm *kvm)
6556{
6557 struct kvm_vcpu *vcpu;
46808a4c
MZ
6558 unsigned long i;
6559 int ret = 0;
7d62874f
SS
6560
6561 mutex_lock(&kvm->lock);
6562 kvm_for_each_vcpu(i, vcpu, kvm) {
916d3608 6563 if (!vcpu->arch.pv_time.active)
7d62874f
SS
6564 continue;
6565
6566 ret = kvm_set_guest_paused(vcpu);
6567 if (ret) {
6568 kvm_err("Failed to pause guest VCPU%d: %d\n",
6569 vcpu->vcpu_id, ret);
6570 break;
6571 }
6572 }
6573 mutex_unlock(&kvm->lock);
6574
6575 return ret ? NOTIFY_BAD : NOTIFY_DONE;
6576}
6577
6578int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6579{
6580 switch (state) {
6581 case PM_HIBERNATION_PREPARE:
6582 case PM_SUSPEND_PREPARE:
6583 return kvm_arch_suspend_notifier(kvm);
6584 }
6585
6586 return NOTIFY_DONE;
6587}
6588#endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6589
45e6c2fa
PB
6590static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6591{
869b4421 6592 struct kvm_clock_data data = { 0 };
45e6c2fa 6593
55c0cefb 6594 get_kvmclock(kvm, &data);
45e6c2fa
PB
6595 if (copy_to_user(argp, &data, sizeof(data)))
6596 return -EFAULT;
6597
6598 return 0;
6599}
6600
6601static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6602{
6603 struct kvm_arch *ka = &kvm->arch;
6604 struct kvm_clock_data data;
c68dc1b5 6605 u64 now_raw_ns;
45e6c2fa
PB
6606
6607 if (copy_from_user(&data, argp, sizeof(data)))
6608 return -EFAULT;
6609
c68dc1b5
OU
6610 /*
6611 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6612 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6613 */
6614 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
45e6c2fa
PB
6615 return -EINVAL;
6616
42dcbe7d 6617 kvm_hv_request_tsc_page_update(kvm);
45e6c2fa
PB
6618 kvm_start_pvclock_update(kvm);
6619 pvclock_update_vm_gtod_copy(kvm);
6620
6621 /*
6622 * This pairs with kvm_guest_time_update(): when masterclock is
6623 * in use, we use master_kernel_ns + kvmclock_offset to set
6624 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6625 * is slightly ahead) here we risk going negative on unsigned
6626 * 'system_time' when 'data.clock' is very small.
6627 */
c68dc1b5
OU
6628 if (data.flags & KVM_CLOCK_REALTIME) {
6629 u64 now_real_ns = ktime_get_real_ns();
6630
6631 /*
6632 * Avoid stepping the kvmclock backwards.
6633 */
6634 if (now_real_ns > data.realtime)
6635 data.clock += now_real_ns - data.realtime;
6636 }
6637
6638 if (ka->use_master_clock)
6639 now_raw_ns = ka->master_kernel_ns;
45e6c2fa 6640 else
c68dc1b5
OU
6641 now_raw_ns = get_kvmclock_base_ns();
6642 ka->kvmclock_offset = data.clock - now_raw_ns;
45e6c2fa
PB
6643 kvm_end_pvclock_update(kvm);
6644 return 0;
6645}
6646
1fe779f8
CO
6647long kvm_arch_vm_ioctl(struct file *filp,
6648 unsigned int ioctl, unsigned long arg)
6649{
6650 struct kvm *kvm = filp->private_data;
6651 void __user *argp = (void __user *)arg;
367e1319 6652 int r = -ENOTTY;
f0d66275
DH
6653 /*
6654 * This union makes it completely explicit to gcc-3.x
6655 * that these two variables' stack usage should be
6656 * combined, not added together.
6657 */
6658 union {
6659 struct kvm_pit_state ps;
e9f42757 6660 struct kvm_pit_state2 ps2;
c5ff41ce 6661 struct kvm_pit_config pit_config;
f0d66275 6662 } u;
1fe779f8
CO
6663
6664 switch (ioctl) {
6665 case KVM_SET_TSS_ADDR:
6666 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1fe779f8 6667 break;
b927a3ce
SY
6668 case KVM_SET_IDENTITY_MAP_ADDR: {
6669 u64 ident_addr;
6670
1af1ac91
DH
6671 mutex_lock(&kvm->lock);
6672 r = -EINVAL;
6673 if (kvm->created_vcpus)
6674 goto set_identity_unlock;
b927a3ce 6675 r = -EFAULT;
0e96f31e 6676 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
1af1ac91 6677 goto set_identity_unlock;
b927a3ce 6678 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
1af1ac91
DH
6679set_identity_unlock:
6680 mutex_unlock(&kvm->lock);
b927a3ce
SY
6681 break;
6682 }
1fe779f8
CO
6683 case KVM_SET_NR_MMU_PAGES:
6684 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1fe779f8
CO
6685 break;
6686 case KVM_GET_NR_MMU_PAGES:
6687 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
6688 break;
3ddea128 6689 case KVM_CREATE_IRQCHIP: {
3ddea128 6690 mutex_lock(&kvm->lock);
09941366 6691
3ddea128 6692 r = -EEXIST;
35e6eaa3 6693 if (irqchip_in_kernel(kvm))
3ddea128 6694 goto create_irqchip_unlock;
09941366 6695
3e515705 6696 r = -EINVAL;
557abc40 6697 if (kvm->created_vcpus)
3e515705 6698 goto create_irqchip_unlock;
09941366
RK
6699
6700 r = kvm_pic_init(kvm);
6701 if (r)
3ddea128 6702 goto create_irqchip_unlock;
09941366
RK
6703
6704 r = kvm_ioapic_init(kvm);
6705 if (r) {
09941366 6706 kvm_pic_destroy(kvm);
3ddea128 6707 goto create_irqchip_unlock;
09941366
RK
6708 }
6709
399ec807
AK
6710 r = kvm_setup_default_irq_routing(kvm);
6711 if (r) {
72bb2fcd 6712 kvm_ioapic_destroy(kvm);
09941366 6713 kvm_pic_destroy(kvm);
71ba994c 6714 goto create_irqchip_unlock;
399ec807 6715 }
49776faf 6716 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
71ba994c 6717 smp_wmb();
49776faf 6718 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
320af55a 6719 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
3ddea128
MT
6720 create_irqchip_unlock:
6721 mutex_unlock(&kvm->lock);
1fe779f8 6722 break;
3ddea128 6723 }
7837699f 6724 case KVM_CREATE_PIT:
c5ff41ce
JK
6725 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
6726 goto create_pit;
6727 case KVM_CREATE_PIT2:
6728 r = -EFAULT;
6729 if (copy_from_user(&u.pit_config, argp,
6730 sizeof(struct kvm_pit_config)))
6731 goto out;
6732 create_pit:
250715a6 6733 mutex_lock(&kvm->lock);
269e05e4
AK
6734 r = -EEXIST;
6735 if (kvm->arch.vpit)
6736 goto create_pit_unlock;
7837699f 6737 r = -ENOMEM;
c5ff41ce 6738 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7837699f
SY
6739 if (kvm->arch.vpit)
6740 r = 0;
269e05e4 6741 create_pit_unlock:
250715a6 6742 mutex_unlock(&kvm->lock);
7837699f 6743 break;
1fe779f8
CO
6744 case KVM_GET_IRQCHIP: {
6745 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 6746 struct kvm_irqchip *chip;
1fe779f8 6747
ff5c2c03
SL
6748 chip = memdup_user(argp, sizeof(*chip));
6749 if (IS_ERR(chip)) {
6750 r = PTR_ERR(chip);
1fe779f8 6751 goto out;
ff5c2c03
SL
6752 }
6753
1fe779f8 6754 r = -ENXIO;
826da321 6755 if (!irqchip_kernel(kvm))
f0d66275
DH
6756 goto get_irqchip_out;
6757 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1fe779f8 6758 if (r)
f0d66275 6759 goto get_irqchip_out;
1fe779f8 6760 r = -EFAULT;
0e96f31e 6761 if (copy_to_user(argp, chip, sizeof(*chip)))
f0d66275 6762 goto get_irqchip_out;
1fe779f8 6763 r = 0;
f0d66275
DH
6764 get_irqchip_out:
6765 kfree(chip);
1fe779f8
CO
6766 break;
6767 }
6768 case KVM_SET_IRQCHIP: {
6769 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c03 6770 struct kvm_irqchip *chip;
1fe779f8 6771
ff5c2c03
SL
6772 chip = memdup_user(argp, sizeof(*chip));
6773 if (IS_ERR(chip)) {
6774 r = PTR_ERR(chip);
1fe779f8 6775 goto out;
ff5c2c03
SL
6776 }
6777
1fe779f8 6778 r = -ENXIO;
826da321 6779 if (!irqchip_kernel(kvm))
f0d66275
DH
6780 goto set_irqchip_out;
6781 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
f0d66275
DH
6782 set_irqchip_out:
6783 kfree(chip);
1fe779f8
CO
6784 break;
6785 }
e0f63cb9 6786 case KVM_GET_PIT: {
e0f63cb9 6787 r = -EFAULT;
f0d66275 6788 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
6789 goto out;
6790 r = -ENXIO;
6791 if (!kvm->arch.vpit)
6792 goto out;
f0d66275 6793 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
e0f63cb9
SY
6794 if (r)
6795 goto out;
6796 r = -EFAULT;
f0d66275 6797 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
e0f63cb9
SY
6798 goto out;
6799 r = 0;
6800 break;
6801 }
6802 case KVM_SET_PIT: {
e0f63cb9 6803 r = -EFAULT;
0e96f31e 6804 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
e0f63cb9 6805 goto out;
7289fdb5 6806 mutex_lock(&kvm->lock);
e0f63cb9
SY
6807 r = -ENXIO;
6808 if (!kvm->arch.vpit)
7289fdb5 6809 goto set_pit_out;
f0d66275 6810 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7289fdb5
SR
6811set_pit_out:
6812 mutex_unlock(&kvm->lock);
e0f63cb9
SY
6813 break;
6814 }
e9f42757
BK
6815 case KVM_GET_PIT2: {
6816 r = -ENXIO;
6817 if (!kvm->arch.vpit)
6818 goto out;
6819 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
6820 if (r)
6821 goto out;
6822 r = -EFAULT;
6823 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
6824 goto out;
6825 r = 0;
6826 break;
6827 }
6828 case KVM_SET_PIT2: {
6829 r = -EFAULT;
6830 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
6831 goto out;
7289fdb5 6832 mutex_lock(&kvm->lock);
e9f42757
BK
6833 r = -ENXIO;
6834 if (!kvm->arch.vpit)
7289fdb5 6835 goto set_pit2_out;
e9f42757 6836 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7289fdb5
SR
6837set_pit2_out:
6838 mutex_unlock(&kvm->lock);
e9f42757
BK
6839 break;
6840 }
52d939a0
MT
6841 case KVM_REINJECT_CONTROL: {
6842 struct kvm_reinject_control control;
6843 r = -EFAULT;
6844 if (copy_from_user(&control, argp, sizeof(control)))
6845 goto out;
cad23e72
ML
6846 r = -ENXIO;
6847 if (!kvm->arch.vpit)
6848 goto out;
52d939a0 6849 r = kvm_vm_ioctl_reinject(kvm, &control);
52d939a0
MT
6850 break;
6851 }
d71ba788
PB
6852 case KVM_SET_BOOT_CPU_ID:
6853 r = 0;
6854 mutex_lock(&kvm->lock);
557abc40 6855 if (kvm->created_vcpus)
d71ba788
PB
6856 r = -EBUSY;
6857 else
6858 kvm->arch.bsp_vcpu_id = arg;
6859 mutex_unlock(&kvm->lock);
6860 break;
b59b153d 6861#ifdef CONFIG_KVM_XEN
ffde22ac 6862 case KVM_XEN_HVM_CONFIG: {
51776043 6863 struct kvm_xen_hvm_config xhc;
ffde22ac 6864 r = -EFAULT;
51776043 6865 if (copy_from_user(&xhc, argp, sizeof(xhc)))
ffde22ac 6866 goto out;
78e9878c 6867 r = kvm_xen_hvm_config(kvm, &xhc);
ffde22ac
ES
6868 break;
6869 }
a76b9641
JM
6870 case KVM_XEN_HVM_GET_ATTR: {
6871 struct kvm_xen_hvm_attr xha;
6872
6873 r = -EFAULT;
6874 if (copy_from_user(&xha, argp, sizeof(xha)))
ffde22ac 6875 goto out;
a76b9641
JM
6876 r = kvm_xen_hvm_get_attr(kvm, &xha);
6877 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
6878 r = -EFAULT;
6879 break;
6880 }
6881 case KVM_XEN_HVM_SET_ATTR: {
6882 struct kvm_xen_hvm_attr xha;
6883
6884 r = -EFAULT;
6885 if (copy_from_user(&xha, argp, sizeof(xha)))
6886 goto out;
6887 r = kvm_xen_hvm_set_attr(kvm, &xha);
ffde22ac
ES
6888 break;
6889 }
35025735
DW
6890 case KVM_XEN_HVM_EVTCHN_SEND: {
6891 struct kvm_irq_routing_xen_evtchn uxe;
6892
6893 r = -EFAULT;
6894 if (copy_from_user(&uxe, argp, sizeof(uxe)))
6895 goto out;
6896 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
6897 break;
6898 }
b59b153d 6899#endif
45e6c2fa
PB
6900 case KVM_SET_CLOCK:
6901 r = kvm_vm_ioctl_set_clock(kvm, argp);
afbcf7ab 6902 break;
45e6c2fa
PB
6903 case KVM_GET_CLOCK:
6904 r = kvm_vm_ioctl_get_clock(kvm, argp);
afbcf7ab 6905 break;
ffbb61d0
DW
6906 case KVM_SET_TSC_KHZ: {
6907 u32 user_tsc_khz;
6908
6909 r = -EINVAL;
6910 user_tsc_khz = (u32)arg;
6911
938c8745
SC
6912 if (kvm_caps.has_tsc_control &&
6913 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
ffbb61d0
DW
6914 goto out;
6915
6916 if (user_tsc_khz == 0)
6917 user_tsc_khz = tsc_khz;
6918
6919 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
6920 r = 0;
6921
6922 goto out;
6923 }
6924 case KVM_GET_TSC_KHZ: {
6925 r = READ_ONCE(kvm->arch.default_tsc_khz);
6926 goto out;
6927 }
5acc5c06
BS
6928 case KVM_MEMORY_ENCRYPT_OP: {
6929 r = -ENOTTY;
03d004cd
SC
6930 if (!kvm_x86_ops.mem_enc_ioctl)
6931 goto out;
6932
6933 r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
5acc5c06
BS
6934 break;
6935 }
69eaedee
BS
6936 case KVM_MEMORY_ENCRYPT_REG_REGION: {
6937 struct kvm_enc_region region;
6938
6939 r = -EFAULT;
6940 if (copy_from_user(&region, argp, sizeof(region)))
6941 goto out;
6942
6943 r = -ENOTTY;
03d004cd
SC
6944 if (!kvm_x86_ops.mem_enc_register_region)
6945 goto out;
6946
6947 r = static_call(kvm_x86_mem_enc_register_region)(kvm, &region);
69eaedee
BS
6948 break;
6949 }
6950 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
6951 struct kvm_enc_region region;
6952
6953 r = -EFAULT;
6954 if (copy_from_user(&region, argp, sizeof(region)))
6955 goto out;
6956
6957 r = -ENOTTY;
03d004cd
SC
6958 if (!kvm_x86_ops.mem_enc_unregister_region)
6959 goto out;
6960
6961 r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, &region);
69eaedee
BS
6962 break;
6963 }
faeb7833
RK
6964 case KVM_HYPERV_EVENTFD: {
6965 struct kvm_hyperv_eventfd hvevfd;
6966
6967 r = -EFAULT;
6968 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
6969 goto out;
6970 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
6971 break;
6972 }
66bb8a06
EH
6973 case KVM_SET_PMU_EVENT_FILTER:
6974 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
6975 break;
2e3272bc
AG
6976 case KVM_X86_SET_MSR_FILTER: {
6977 struct kvm_msr_filter __user *user_msr_filter = argp;
6978 struct kvm_msr_filter filter;
6979
6980 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
6981 return -EFAULT;
6982
6983 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
1a155254 6984 break;
2e3272bc 6985 }
1fe779f8 6986 default:
ad6260da 6987 r = -ENOTTY;
1fe779f8
CO
6988 }
6989out:
6990 return r;
6991}
6992
a16b043c 6993static void kvm_init_msr_list(void)
043405e1
CO
6994{
6995 u32 dummy[2];
7a5ee6ed 6996 unsigned i;
043405e1 6997
0144ba0c 6998 BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
7a5ee6ed 6999 "Please update the fixed PMCs in msrs_to_saved_all[]");
24c29b7a 7000
6cbee2b9
XL
7001 num_msrs_to_save = 0;
7002 num_emulated_msrs = 0;
7003 num_msr_based_features = 0;
7004
7a5ee6ed
CQ
7005 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
7006 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
043405e1 7007 continue;
93c4adc7
PB
7008
7009 /*
7010 * Even MSRs that are valid in the host may not be exposed
9dbe6cf9 7011 * to the guests in some cases.
93c4adc7 7012 */
7a5ee6ed 7013 switch (msrs_to_save_all[i]) {
93c4adc7 7014 case MSR_IA32_BNDCFGS:
503234b3 7015 if (!kvm_mpx_supported())
93c4adc7
PB
7016 continue;
7017 break;
9dbe6cf9 7018 case MSR_TSC_AUX:
36fa06f9
SC
7019 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7020 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
9dbe6cf9
PB
7021 continue;
7022 break;
f4cfcd2d
ML
7023 case MSR_IA32_UMWAIT_CONTROL:
7024 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7025 continue;
7026 break;
bf8c55d8
CP
7027 case MSR_IA32_RTIT_CTL:
7028 case MSR_IA32_RTIT_STATUS:
7b874c26 7029 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
bf8c55d8
CP
7030 continue;
7031 break;
7032 case MSR_IA32_RTIT_CR3_MATCH:
7b874c26 7033 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
bf8c55d8
CP
7034 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7035 continue;
7036 break;
7037 case MSR_IA32_RTIT_OUTPUT_BASE:
7038 case MSR_IA32_RTIT_OUTPUT_MASK:
7b874c26 7039 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
bf8c55d8
CP
7040 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7041 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7042 continue;
7043 break;
7cb85fc4 7044 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7b874c26 7045 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7a5ee6ed 7046 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
bf8c55d8
CP
7047 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
7048 continue;
7049 break;
4f1fa2a1 7050 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR_MAX:
7a5ee6ed 7051 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
4f1fa2a1 7052 min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
24c29b7a
PB
7053 continue;
7054 break;
4f1fa2a1 7055 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL_MAX:
7a5ee6ed 7056 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
4f1fa2a1 7057 min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
24c29b7a 7058 continue;
7cb85fc4 7059 break;
820a6ee9 7060 case MSR_IA32_XFD:
548e8365 7061 case MSR_IA32_XFD_ERR:
820a6ee9
JL
7062 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7063 continue;
7064 break;
93c4adc7
PB
7065 default:
7066 break;
7067 }
7068
7a5ee6ed 7069 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
043405e1 7070 }
62ef68bb 7071
7a5ee6ed 7072 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
b3646477 7073 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
bc226f07 7074 continue;
62ef68bb 7075
7a5ee6ed 7076 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
62ef68bb 7077 }
801e459a 7078
7a5ee6ed 7079 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
801e459a
TL
7080 struct kvm_msr_entry msr;
7081
7a5ee6ed 7082 msr.index = msr_based_features_all[i];
66421c1e 7083 if (kvm_get_msr_feature(&msr))
801e459a
TL
7084 continue;
7085
7a5ee6ed 7086 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
801e459a 7087 }
043405e1
CO
7088}
7089
bda9020e
MT
7090static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7091 const void *v)
bbd9b64e 7092{
70252a10
AK
7093 int handled = 0;
7094 int n;
7095
7096 do {
7097 n = min(len, 8);
bce87cce 7098 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
7099 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7100 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10
AK
7101 break;
7102 handled += n;
7103 addr += n;
7104 len -= n;
7105 v += n;
7106 } while (len);
bbd9b64e 7107
70252a10 7108 return handled;
bbd9b64e
CO
7109}
7110
bda9020e 7111static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
bbd9b64e 7112{
70252a10
AK
7113 int handled = 0;
7114 int n;
7115
7116 do {
7117 n = min(len, 8);
bce87cce 7118 if (!(lapic_in_kernel(vcpu) &&
e32edf4f
NN
7119 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7120 addr, n, v))
7121 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
70252a10 7122 break;
e39d200f 7123 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
70252a10
AK
7124 handled += n;
7125 addr += n;
7126 len -= n;
7127 v += n;
7128 } while (len);
bbd9b64e 7129
70252a10 7130 return handled;
bbd9b64e
CO
7131}
7132
c53da4f3
PB
7133void kvm_set_segment(struct kvm_vcpu *vcpu,
7134 struct kvm_segment *var, int seg)
2dafc6c2 7135{
b3646477 7136 static_call(kvm_x86_set_segment)(vcpu, var, seg);
2dafc6c2
GN
7137}
7138
7139void kvm_get_segment(struct kvm_vcpu *vcpu,
7140 struct kvm_segment *var, int seg)
7141{
b3646477 7142 static_call(kvm_x86_get_segment)(vcpu, var, seg);
2dafc6c2
GN
7143}
7144
5b22bbe7 7145gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
54987b7a 7146 struct x86_exception *exception)
02f59dc9 7147{
1f5a21ee 7148 struct kvm_mmu *mmu = vcpu->arch.mmu;
02f59dc9 7149 gpa_t t_gpa;
02f59dc9
JR
7150
7151 BUG_ON(!mmu_is_nested(vcpu));
7152
7153 /* NPT walks are always user-walks */
7154 access |= PFERR_USER_MASK;
1f5a21ee 7155 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
02f59dc9
JR
7156
7157 return t_gpa;
7158}
7159
ab9ae313
AK
7160gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7161 struct x86_exception *exception)
1871c602 7162{
1f5a21ee
LJ
7163 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7164
5b22bbe7 7165 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
1f5a21ee 7166 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
1871c602 7167}
54f958cd 7168EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
1871c602 7169
ab9ae313
AK
7170gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7171 struct x86_exception *exception)
1871c602 7172{
1f5a21ee
LJ
7173 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7174
5b22bbe7 7175 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
1871c602 7176 access |= PFERR_WRITE_MASK;
1f5a21ee 7177 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
1871c602 7178}
54f958cd 7179EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
1871c602
GN
7180
7181/* uses this to access any guest's mapped memory without checking CPL */
ab9ae313
AK
7182gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7183 struct x86_exception *exception)
1871c602 7184{
1f5a21ee
LJ
7185 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7186
7187 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
1871c602
GN
7188}
7189
7190static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5b22bbe7 7191 struct kvm_vcpu *vcpu, u64 access,
bcc55cba 7192 struct x86_exception *exception)
bbd9b64e 7193{
1f5a21ee 7194 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
bbd9b64e 7195 void *data = val;
10589a46 7196 int r = X86EMUL_CONTINUE;
bbd9b64e
CO
7197
7198 while (bytes) {
1f5a21ee 7199 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
bbd9b64e 7200 unsigned offset = addr & (PAGE_SIZE-1);
77c2002e 7201 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
bbd9b64e
CO
7202 int ret;
7203
6e1d2a3f 7204 if (gpa == INVALID_GPA)
ab9ae313 7205 return X86EMUL_PROPAGATE_FAULT;
54bf36aa
PB
7206 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7207 offset, toread);
10589a46 7208 if (ret < 0) {
c3cd7ffa 7209 r = X86EMUL_IO_NEEDED;
10589a46
MT
7210 goto out;
7211 }
bbd9b64e 7212
77c2002e
IE
7213 bytes -= toread;
7214 data += toread;
7215 addr += toread;
bbd9b64e 7216 }
10589a46 7217out:
10589a46 7218 return r;
bbd9b64e 7219}
77c2002e 7220
1871c602 7221/* used for instruction fetching */
0f65dd70
AK
7222static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7223 gva_t addr, void *val, unsigned int bytes,
bcc55cba 7224 struct x86_exception *exception)
1871c602 7225{
0f65dd70 7226 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1f5a21ee 7227 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5b22bbe7 7228 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
44583cba
PB
7229 unsigned offset;
7230 int ret;
0f65dd70 7231
44583cba 7232 /* Inline kvm_read_guest_virt_helper for speed. */
1f5a21ee
LJ
7233 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7234 exception);
6e1d2a3f 7235 if (unlikely(gpa == INVALID_GPA))
44583cba
PB
7236 return X86EMUL_PROPAGATE_FAULT;
7237
7238 offset = addr & (PAGE_SIZE-1);
7239 if (WARN_ON(offset + bytes > PAGE_SIZE))
7240 bytes = (unsigned)PAGE_SIZE - offset;
54bf36aa
PB
7241 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7242 offset, bytes);
44583cba
PB
7243 if (unlikely(ret < 0))
7244 return X86EMUL_IO_NEEDED;
7245
7246 return X86EMUL_CONTINUE;
1871c602
GN
7247}
7248
ce14e868 7249int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
0f65dd70 7250 gva_t addr, void *val, unsigned int bytes,
bcc55cba 7251 struct x86_exception *exception)
1871c602 7252{
5b22bbe7 7253 u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70 7254
353c0956
PB
7255 /*
7256 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7257 * is returned, but our callers are not ready for that and they blindly
7258 * call kvm_inject_page_fault. Ensure that they at least do not leak
7259 * uninitialized kernel stack memory into cr2 and error code.
7260 */
7261 memset(exception, 0, sizeof(*exception));
1871c602 7262 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
bcc55cba 7263 exception);
1871c602 7264}
064aea77 7265EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
1871c602 7266
ce14e868
PB
7267static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7268 gva_t addr, void *val, unsigned int bytes,
3c9fa24c 7269 struct x86_exception *exception, bool system)
1871c602 7270{
0f65dd70 7271 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5b22bbe7 7272 u64 access = 0;
3c9fa24c 7273
4f4aa80e
LJ
7274 if (system)
7275 access |= PFERR_IMPLICIT_ACCESS;
7276 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
3c9fa24c
PB
7277 access |= PFERR_USER_MASK;
7278
7279 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
1871c602
GN
7280}
7281
ce14e868 7282static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5b22bbe7 7283 struct kvm_vcpu *vcpu, u64 access,
ce14e868 7284 struct x86_exception *exception)
77c2002e 7285{
1f5a21ee 7286 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
77c2002e
IE
7287 void *data = val;
7288 int r = X86EMUL_CONTINUE;
7289
7290 while (bytes) {
1f5a21ee 7291 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
77c2002e
IE
7292 unsigned offset = addr & (PAGE_SIZE-1);
7293 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7294 int ret;
7295
6e1d2a3f 7296 if (gpa == INVALID_GPA)
ab9ae313 7297 return X86EMUL_PROPAGATE_FAULT;
54bf36aa 7298 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
77c2002e 7299 if (ret < 0) {
c3cd7ffa 7300 r = X86EMUL_IO_NEEDED;
77c2002e
IE
7301 goto out;
7302 }
7303
7304 bytes -= towrite;
7305 data += towrite;
7306 addr += towrite;
7307 }
7308out:
7309 return r;
7310}
ce14e868
PB
7311
7312static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
3c9fa24c
PB
7313 unsigned int bytes, struct x86_exception *exception,
7314 bool system)
ce14e868
PB
7315{
7316 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5b22bbe7 7317 u64 access = PFERR_WRITE_MASK;
3c9fa24c 7318
4f4aa80e
LJ
7319 if (system)
7320 access |= PFERR_IMPLICIT_ACCESS;
7321 else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
3c9fa24c 7322 access |= PFERR_USER_MASK;
ce14e868
PB
7323
7324 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
3c9fa24c 7325 access, exception);
ce14e868
PB
7326}
7327
7328int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7329 unsigned int bytes, struct x86_exception *exception)
7330{
c595ceee
PB
7331 /* kvm_write_guest_virt_system can pull in tons of pages. */
7332 vcpu->arch.l1tf_flush_l1d = true;
7333
ce14e868
PB
7334 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7335 PFERR_WRITE_MASK, exception);
7336}
6a4d7550 7337EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
77c2002e 7338
4d31d9ef
SC
7339static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7340 void *insn, int insn_len)
7341{
7342 return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
7343 insn, insn_len);
7344}
7345
082d06ed
WL
7346int handle_ud(struct kvm_vcpu *vcpu)
7347{
b3dc0695 7348 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
40aaa5b6 7349 int fep_flags = READ_ONCE(force_emulation_prefix);
6c86eedc 7350 int emul_type = EMULTYPE_TRAP_UD;
6c86eedc
WL
7351 char sig[5]; /* ud2; .ascii "kvm" */
7352 struct x86_exception e;
7353
4d31d9ef 7354 if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
09e3e2a1
SC
7355 return 1;
7356
40aaa5b6 7357 if (fep_flags &&
3c9fa24c
PB
7358 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7359 sig, sizeof(sig), &e) == 0 &&
b3dc0695 7360 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
40aaa5b6 7361 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
d500e1ed 7362 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
6c86eedc 7363 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
b4000606 7364 emul_type = EMULTYPE_TRAP_UD_FORCED;
6c86eedc 7365 }
082d06ed 7366
60fc3d02 7367 return kvm_emulate_instruction(vcpu, emul_type);
082d06ed
WL
7368}
7369EXPORT_SYMBOL_GPL(handle_ud);
7370
0f89b207
TL
7371static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7372 gpa_t gpa, bool write)
7373{
7374 /* For APIC access vmexit */
7375 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7376 return 1;
7377
7378 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7379 trace_vcpu_match_mmio(gva, gpa, write, true);
7380 return 1;
7381 }
7382
7383 return 0;
7384}
7385
af7cc7d1
XG
7386static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7387 gpa_t *gpa, struct x86_exception *exception,
7388 bool write)
7389{
1f5a21ee 7390 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5b22bbe7 7391 u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
97d64b78 7392 | (write ? PFERR_WRITE_MASK : 0);
af7cc7d1 7393
be94f6b7
HH
7394 /*
7395 * currently PKRU is only applied to ept enabled guest so
7396 * there is no pkey in EPT page table for L1 guest or EPT
7397 * shadow page table for L2 guest.
7398 */
908b7d43
SC
7399 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7400 !permission_fault(vcpu, vcpu->arch.walk_mmu,
7401 vcpu->arch.mmio_access, 0, access))) {
bebb106a
XG
7402 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7403 (gva & (PAGE_SIZE - 1));
4f022648 7404 trace_vcpu_match_mmio(gva, *gpa, write, false);
bebb106a
XG
7405 return 1;
7406 }
7407
1f5a21ee 7408 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
af7cc7d1 7409
6e1d2a3f 7410 if (*gpa == INVALID_GPA)
af7cc7d1
XG
7411 return -1;
7412
0f89b207 7413 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
af7cc7d1
XG
7414}
7415
3200f405 7416int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
bcc55cba 7417 const void *val, int bytes)
bbd9b64e
CO
7418{
7419 int ret;
7420
54bf36aa 7421 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
9f811285 7422 if (ret < 0)
bbd9b64e 7423 return 0;
0eb05bf2 7424 kvm_page_track_write(vcpu, gpa, val, bytes);
bbd9b64e
CO
7425 return 1;
7426}
7427
77d197b2
XG
7428struct read_write_emulator_ops {
7429 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7430 int bytes);
7431 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7432 void *val, int bytes);
7433 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7434 int bytes, void *val);
7435 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7436 void *val, int bytes);
7437 bool write;
7438};
7439
7440static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7441{
7442 if (vcpu->mmio_read_completed) {
77d197b2 7443 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
e39d200f 7444 vcpu->mmio_fragments[0].gpa, val);
77d197b2
XG
7445 vcpu->mmio_read_completed = 0;
7446 return 1;
7447 }
7448
7449 return 0;
7450}
7451
7452static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7453 void *val, int bytes)
7454{
54bf36aa 7455 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
77d197b2
XG
7456}
7457
7458static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7459 void *val, int bytes)
7460{
7461 return emulator_write_phys(vcpu, gpa, val, bytes);
7462}
7463
7464static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7465{
e39d200f 7466 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
77d197b2
XG
7467 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7468}
7469
7470static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7471 void *val, int bytes)
7472{
e39d200f 7473 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
77d197b2
XG
7474 return X86EMUL_IO_NEEDED;
7475}
7476
7477static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7478 void *val, int bytes)
7479{
f78146b0
AK
7480 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7481
87da7e66 7482 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
77d197b2
XG
7483 return X86EMUL_CONTINUE;
7484}
7485
0fbe9b0b 7486static const struct read_write_emulator_ops read_emultor = {
77d197b2
XG
7487 .read_write_prepare = read_prepare,
7488 .read_write_emulate = read_emulate,
7489 .read_write_mmio = vcpu_mmio_read,
7490 .read_write_exit_mmio = read_exit_mmio,
7491};
7492
0fbe9b0b 7493static const struct read_write_emulator_ops write_emultor = {
77d197b2
XG
7494 .read_write_emulate = write_emulate,
7495 .read_write_mmio = write_mmio,
7496 .read_write_exit_mmio = write_exit_mmio,
7497 .write = true,
7498};
7499
22388a3c
XG
7500static int emulator_read_write_onepage(unsigned long addr, void *val,
7501 unsigned int bytes,
7502 struct x86_exception *exception,
7503 struct kvm_vcpu *vcpu,
0fbe9b0b 7504 const struct read_write_emulator_ops *ops)
bbd9b64e 7505{
af7cc7d1
XG
7506 gpa_t gpa;
7507 int handled, ret;
22388a3c 7508 bool write = ops->write;
f78146b0 7509 struct kvm_mmio_fragment *frag;
c9b8b07c 7510 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
0f89b207
TL
7511
7512 /*
7513 * If the exit was due to a NPF we may already have a GPA.
7514 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7515 * Note, this cannot be used on string operations since string
7516 * operation using rep will only have the initial GPA from the NPF
7517 * occurred.
7518 */
744e699c
SC
7519 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7520 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7521 gpa = ctxt->gpa_val;
618232e2
BS
7522 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7523 } else {
7524 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7525 if (ret < 0)
7526 return X86EMUL_PROPAGATE_FAULT;
0f89b207 7527 }
10589a46 7528
618232e2 7529 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
bbd9b64e
CO
7530 return X86EMUL_CONTINUE;
7531
bbd9b64e
CO
7532 /*
7533 * Is this MMIO handled locally?
7534 */
22388a3c 7535 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
70252a10 7536 if (handled == bytes)
bbd9b64e 7537 return X86EMUL_CONTINUE;
bbd9b64e 7538
70252a10
AK
7539 gpa += handled;
7540 bytes -= handled;
7541 val += handled;
7542
87da7e66
XG
7543 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7544 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7545 frag->gpa = gpa;
7546 frag->data = val;
7547 frag->len = bytes;
f78146b0 7548 return X86EMUL_CONTINUE;
bbd9b64e
CO
7549}
7550
52eb5a6d
XL
7551static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7552 unsigned long addr,
22388a3c
XG
7553 void *val, unsigned int bytes,
7554 struct x86_exception *exception,
0fbe9b0b 7555 const struct read_write_emulator_ops *ops)
bbd9b64e 7556{
0f65dd70 7557 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
f78146b0
AK
7558 gpa_t gpa;
7559 int rc;
7560
7561 if (ops->read_write_prepare &&
7562 ops->read_write_prepare(vcpu, val, bytes))
7563 return X86EMUL_CONTINUE;
7564
7565 vcpu->mmio_nr_fragments = 0;
0f65dd70 7566
bbd9b64e
CO
7567 /* Crossing a page boundary? */
7568 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
f78146b0 7569 int now;
bbd9b64e
CO
7570
7571 now = -addr & ~PAGE_MASK;
22388a3c
XG
7572 rc = emulator_read_write_onepage(addr, val, now, exception,
7573 vcpu, ops);
7574
bbd9b64e
CO
7575 if (rc != X86EMUL_CONTINUE)
7576 return rc;
7577 addr += now;
bac15531
NA
7578 if (ctxt->mode != X86EMUL_MODE_PROT64)
7579 addr = (u32)addr;
bbd9b64e
CO
7580 val += now;
7581 bytes -= now;
7582 }
22388a3c 7583
f78146b0
AK
7584 rc = emulator_read_write_onepage(addr, val, bytes, exception,
7585 vcpu, ops);
7586 if (rc != X86EMUL_CONTINUE)
7587 return rc;
7588
7589 if (!vcpu->mmio_nr_fragments)
7590 return rc;
7591
7592 gpa = vcpu->mmio_fragments[0].gpa;
7593
7594 vcpu->mmio_needed = 1;
7595 vcpu->mmio_cur_fragment = 0;
7596
87da7e66 7597 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
f78146b0
AK
7598 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
7599 vcpu->run->exit_reason = KVM_EXIT_MMIO;
7600 vcpu->run->mmio.phys_addr = gpa;
7601
7602 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
22388a3c
XG
7603}
7604
7605static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
7606 unsigned long addr,
7607 void *val,
7608 unsigned int bytes,
7609 struct x86_exception *exception)
7610{
7611 return emulator_read_write(ctxt, addr, val, bytes,
7612 exception, &read_emultor);
7613}
7614
52eb5a6d 7615static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
22388a3c
XG
7616 unsigned long addr,
7617 const void *val,
7618 unsigned int bytes,
7619 struct x86_exception *exception)
7620{
7621 return emulator_read_write(ctxt, addr, (void *)val, bytes,
7622 exception, &write_emultor);
bbd9b64e 7623}
bbd9b64e 7624
1c2361f6
SC
7625#define emulator_try_cmpxchg_user(t, ptr, old, new) \
7626 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
daea3e73 7627
0f65dd70
AK
7628static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
7629 unsigned long addr,
bbd9b64e
CO
7630 const void *old,
7631 const void *new,
7632 unsigned int bytes,
0f65dd70 7633 struct x86_exception *exception)
bbd9b64e 7634{
0f65dd70 7635 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
9de6fe3c 7636 u64 page_line_mask;
1c2361f6 7637 unsigned long hva;
daea3e73 7638 gpa_t gpa;
1c2361f6 7639 int r;
2bacc55c 7640
daea3e73
AK
7641 /* guests cmpxchg8b have to be emulated atomically */
7642 if (bytes > 8 || (bytes & (bytes - 1)))
7643 goto emul_write;
10589a46 7644
daea3e73 7645 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
2bacc55c 7646
6e1d2a3f 7647 if (gpa == INVALID_GPA ||
daea3e73
AK
7648 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7649 goto emul_write;
2bacc55c 7650
9de6fe3c
XL
7651 /*
7652 * Emulate the atomic as a straight write to avoid #AC if SLD is
7653 * enabled in the host and the access splits a cache line.
7654 */
7655 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
7656 page_line_mask = ~(cache_line_size() - 1);
7657 else
7658 page_line_mask = PAGE_MASK;
7659
7660 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
daea3e73 7661 goto emul_write;
72dc67a6 7662
1c2361f6 7663 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
33fbe6be 7664 if (kvm_is_error_hva(hva))
c19b8bd6 7665 goto emul_write;
72dc67a6 7666
1c2361f6 7667 hva += offset_in_page(gpa);
42e35f80 7668
daea3e73
AK
7669 switch (bytes) {
7670 case 1:
1c2361f6 7671 r = emulator_try_cmpxchg_user(u8, hva, old, new);
daea3e73
AK
7672 break;
7673 case 2:
1c2361f6 7674 r = emulator_try_cmpxchg_user(u16, hva, old, new);
daea3e73
AK
7675 break;
7676 case 4:
1c2361f6 7677 r = emulator_try_cmpxchg_user(u32, hva, old, new);
daea3e73
AK
7678 break;
7679 case 8:
1c2361f6 7680 r = emulator_try_cmpxchg_user(u64, hva, old, new);
daea3e73
AK
7681 break;
7682 default:
7683 BUG();
2bacc55c 7684 }
42e35f80 7685
1c2361f6 7686 if (r < 0)
5d6c7de6 7687 return X86EMUL_UNHANDLEABLE;
1c2361f6 7688 if (r)
daea3e73
AK
7689 return X86EMUL_CMPXCHG_FAILED;
7690
0eb05bf2 7691 kvm_page_track_write(vcpu, gpa, new, bytes);
8f6abd06
GN
7692
7693 return X86EMUL_CONTINUE;
4a5f48f6 7694
3200f405 7695emul_write:
daea3e73 7696 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
2bacc55c 7697
0f65dd70 7698 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
bbd9b64e
CO
7699}
7700
6f6fbe98 7701static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
30d583fd 7702 unsigned short port, void *data,
6f6fbe98 7703 unsigned int count, bool in)
cf8f70bf 7704{
0f87ac23
PB
7705 unsigned i;
7706 int r;
cf8f70bf 7707
30d583fd 7708 WARN_ON_ONCE(vcpu->arch.pio.count);
0f87ac23
PB
7709 for (i = 0; i < count; i++) {
7710 if (in)
7711 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
cbfc6c91 7712 else
0f87ac23 7713 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
35ab3b77
PB
7714
7715 if (r) {
7716 if (i == 0)
7717 goto userspace_io;
7718
7719 /*
7720 * Userspace must have unregistered the device while PIO
0c05e10b 7721 * was running. Drop writes / read as 0.
35ab3b77 7722 */
0c05e10b
PB
7723 if (in)
7724 memset(data, 0, size * (count - i));
cbfc6c91 7725 break;
35ab3b77
PB
7726 }
7727
0f87ac23 7728 data += size;
cbfc6c91 7729 }
0f87ac23 7730 return 1;
cf8f70bf 7731
0f87ac23 7732userspace_io:
cf8f70bf 7733 vcpu->arch.pio.port = port;
6f6fbe98 7734 vcpu->arch.pio.in = in;
0c05e10b 7735 vcpu->arch.pio.count = count;
cf8f70bf
GN
7736 vcpu->arch.pio.size = size;
7737
0c05e10b
PB
7738 if (in)
7739 memset(vcpu->arch.pio_data, 0, size * count);
7740 else
7741 memcpy(vcpu->arch.pio_data, data, size * count);
cf8f70bf
GN
7742
7743 vcpu->run->exit_reason = KVM_EXIT_IO;
6f6fbe98 7744 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
cf8f70bf
GN
7745 vcpu->run->io.size = size;
7746 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
7747 vcpu->run->io.count = count;
7748 vcpu->run->io.port = port;
cf8f70bf
GN
7749 return 0;
7750}
7751
f35cee4a
PB
7752static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7753 unsigned short port, void *val, unsigned int count)
cf8f70bf 7754{
0c05e10b
PB
7755 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
7756 if (r)
7757 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
7758
7759 return r;
3b27de27 7760}
ca1d4a9e 7761
6b5efc93 7762static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
3b27de27 7763{
6b5efc93 7764 int size = vcpu->arch.pio.size;
0c05e10b 7765 unsigned int count = vcpu->arch.pio.count;
6b5efc93
PB
7766 memcpy(val, vcpu->arch.pio_data, size * count);
7767 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
3b27de27
PB
7768 vcpu->arch.pio.count = 0;
7769}
cf8f70bf 7770
f35cee4a
PB
7771static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
7772 int size, unsigned short port, void *val,
7773 unsigned int count)
3b27de27 7774{
f35cee4a 7775 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3b27de27 7776 if (vcpu->arch.pio.count) {
d07898ea
SC
7777 /*
7778 * Complete a previous iteration that required userspace I/O.
7779 * Note, @count isn't guaranteed to match pio.count as userspace
7780 * can modify ECX before rerunning the vCPU. Ignore any such
7781 * shenanigans as KVM doesn't support modifying the rep count,
7782 * and the emulator ensures @count doesn't overflow the buffer.
7783 */
0c05e10b
PB
7784 complete_emulator_pio_in(vcpu, val);
7785 return 1;
cf8f70bf
GN
7786 }
7787
f35cee4a 7788 return emulator_pio_in(vcpu, size, port, val, count);
2e3bb4d8 7789}
6f6fbe98 7790
2e3bb4d8
SC
7791static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
7792 unsigned short port, const void *val,
7793 unsigned int count)
7794{
30d583fd 7795 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
0c05e10b 7796 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6f6fbe98
XG
7797}
7798
2e3bb4d8
SC
7799static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
7800 int size, unsigned short port,
7801 const void *val, unsigned int count)
7802{
7803 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
7804}
7805
bbd9b64e
CO
7806static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
7807{
b3646477 7808 return static_call(kvm_x86_get_segment_base)(vcpu, seg);
bbd9b64e
CO
7809}
7810
3cb16fe7 7811static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
bbd9b64e 7812{
3cb16fe7 7813 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
bbd9b64e
CO
7814}
7815
ae6a2375 7816static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
f5f48ee1
SY
7817{
7818 if (!need_emulate_wbinvd(vcpu))
7819 return X86EMUL_CONTINUE;
7820
b3646477 7821 if (static_call(kvm_x86_has_wbinvd_exit)()) {
2eec7343
JK
7822 int cpu = get_cpu();
7823
7824 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
c2162e13 7825 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
f5f48ee1 7826 wbinvd_ipi, NULL, 1);
2eec7343 7827 put_cpu();
f5f48ee1 7828 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
2eec7343
JK
7829 } else
7830 wbinvd();
f5f48ee1
SY
7831 return X86EMUL_CONTINUE;
7832}
5cb56059
JS
7833
7834int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
7835{
6affcbed
KH
7836 kvm_emulate_wbinvd_noskip(vcpu);
7837 return kvm_skip_emulated_instruction(vcpu);
5cb56059 7838}
f5f48ee1
SY
7839EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
7840
5cb56059
JS
7841
7842
bcaf5cc5
AK
7843static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
7844{
5cb56059 7845 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
bcaf5cc5
AK
7846}
7847
29d6ca41
PB
7848static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
7849 unsigned long *dest)
bbd9b64e 7850{
29d6ca41 7851 kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
bbd9b64e
CO
7852}
7853
52eb5a6d
XL
7854static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
7855 unsigned long value)
bbd9b64e 7856{
338dbc97 7857
996ff542 7858 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
bbd9b64e
CO
7859}
7860
52a46617 7861static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5fdbf976 7862{
52a46617 7863 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5fdbf976
MT
7864}
7865
717746e3 7866static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
bbd9b64e 7867{
717746e3 7868 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
52a46617
GN
7869 unsigned long value;
7870
7871 switch (cr) {
7872 case 0:
7873 value = kvm_read_cr0(vcpu);
7874 break;
7875 case 2:
7876 value = vcpu->arch.cr2;
7877 break;
7878 case 3:
9f8fe504 7879 value = kvm_read_cr3(vcpu);
52a46617
GN
7880 break;
7881 case 4:
7882 value = kvm_read_cr4(vcpu);
7883 break;
7884 case 8:
7885 value = kvm_get_cr8(vcpu);
7886 break;
7887 default:
a737f256 7888 kvm_err("%s: unexpected cr %u\n", __func__, cr);
52a46617
GN
7889 return 0;
7890 }
7891
7892 return value;
7893}
7894
717746e3 7895static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
52a46617 7896{
717746e3 7897 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
0f12244f
GN
7898 int res = 0;
7899
52a46617
GN
7900 switch (cr) {
7901 case 0:
49a9b07e 7902 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
52a46617
GN
7903 break;
7904 case 2:
7905 vcpu->arch.cr2 = val;
7906 break;
7907 case 3:
2390218b 7908 res = kvm_set_cr3(vcpu, val);
52a46617
GN
7909 break;
7910 case 4:
a83b29c6 7911 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
52a46617
GN
7912 break;
7913 case 8:
eea1cff9 7914 res = kvm_set_cr8(vcpu, val);
52a46617
GN
7915 break;
7916 default:
a737f256 7917 kvm_err("%s: unexpected cr %u\n", __func__, cr);
0f12244f 7918 res = -1;
52a46617 7919 }
0f12244f
GN
7920
7921 return res;
52a46617
GN
7922}
7923
717746e3 7924static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
9c537244 7925{
b3646477 7926 return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
9c537244
GN
7927}
7928
4bff1e86 7929static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
2dafc6c2 7930{
b3646477 7931 static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
2dafc6c2
GN
7932}
7933
4bff1e86 7934static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
160ce1f1 7935{
b3646477 7936 static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
160ce1f1
MG
7937}
7938
1ac9d0cf
AK
7939static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7940{
b3646477 7941 static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
7942}
7943
7944static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7945{
b3646477 7946 static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
1ac9d0cf
AK
7947}
7948
4bff1e86
AK
7949static unsigned long emulator_get_cached_segment_base(
7950 struct x86_emulate_ctxt *ctxt, int seg)
5951c442 7951{
4bff1e86 7952 return get_segment_base(emul_to_vcpu(ctxt), seg);
5951c442
GN
7953}
7954
1aa36616
AK
7955static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
7956 struct desc_struct *desc, u32 *base3,
7957 int seg)
2dafc6c2
GN
7958{
7959 struct kvm_segment var;
7960
4bff1e86 7961 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
1aa36616 7962 *selector = var.selector;
2dafc6c2 7963
378a8b09
GN
7964 if (var.unusable) {
7965 memset(desc, 0, sizeof(*desc));
f0367ee1
RK
7966 if (base3)
7967 *base3 = 0;
2dafc6c2 7968 return false;
378a8b09 7969 }
2dafc6c2
GN
7970
7971 if (var.g)
7972 var.limit >>= 12;
7973 set_desc_limit(desc, var.limit);
7974 set_desc_base(desc, (unsigned long)var.base);
5601d05b
GN
7975#ifdef CONFIG_X86_64
7976 if (base3)
7977 *base3 = var.base >> 32;
7978#endif
2dafc6c2
GN
7979 desc->type = var.type;
7980 desc->s = var.s;
7981 desc->dpl = var.dpl;
7982 desc->p = var.present;
7983 desc->avl = var.avl;
7984 desc->l = var.l;
7985 desc->d = var.db;
7986 desc->g = var.g;
7987
7988 return true;
7989}
7990
1aa36616
AK
7991static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
7992 struct desc_struct *desc, u32 base3,
7993 int seg)
2dafc6c2 7994{
4bff1e86 7995 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
2dafc6c2
GN
7996 struct kvm_segment var;
7997
1aa36616 7998 var.selector = selector;
2dafc6c2 7999 var.base = get_desc_base(desc);
5601d05b
GN
8000#ifdef CONFIG_X86_64
8001 var.base |= ((u64)base3) << 32;
8002#endif
2dafc6c2
GN
8003 var.limit = get_desc_limit(desc);
8004 if (desc->g)
8005 var.limit = (var.limit << 12) | 0xfff;
8006 var.type = desc->type;
2dafc6c2
GN
8007 var.dpl = desc->dpl;
8008 var.db = desc->d;
8009 var.s = desc->s;
8010 var.l = desc->l;
8011 var.g = desc->g;
8012 var.avl = desc->avl;
8013 var.present = desc->p;
8014 var.unusable = !var.present;
8015 var.padding = 0;
8016
8017 kvm_set_segment(vcpu, &var, seg);
8018 return;
8019}
8020
ac8d6cad
HW
8021static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8022 u32 msr_index, u64 *pdata)
717746e3 8023{
1ae09954
AG
8024 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8025 int r;
8026
ac8d6cad 8027 r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
36d546d5
HW
8028 if (r < 0)
8029 return X86EMUL_UNHANDLEABLE;
1ae09954 8030
36d546d5
HW
8031 if (r) {
8032 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8033 complete_emulated_rdmsr, r))
8034 return X86EMUL_IO_NEEDED;
794663e1
HW
8035
8036 trace_kvm_msr_read_ex(msr_index);
36d546d5 8037 return X86EMUL_PROPAGATE_FAULT;
1ae09954
AG
8038 }
8039
794663e1 8040 trace_kvm_msr_read(msr_index, *pdata);
36d546d5 8041 return X86EMUL_CONTINUE;
717746e3
AK
8042}
8043
ac8d6cad
HW
8044static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8045 u32 msr_index, u64 data)
717746e3 8046{
1ae09954
AG
8047 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8048 int r;
8049
ac8d6cad 8050 r = kvm_set_msr_with_filter(vcpu, msr_index, data);
36d546d5
HW
8051 if (r < 0)
8052 return X86EMUL_UNHANDLEABLE;
1ae09954 8053
36d546d5
HW
8054 if (r) {
8055 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8056 complete_emulated_msr_access, r))
8057 return X86EMUL_IO_NEEDED;
794663e1
HW
8058
8059 trace_kvm_msr_write_ex(msr_index, data);
36d546d5 8060 return X86EMUL_PROPAGATE_FAULT;
1ae09954
AG
8061 }
8062
794663e1 8063 trace_kvm_msr_write(msr_index, data);
36d546d5 8064 return X86EMUL_CONTINUE;
717746e3
AK
8065}
8066
ac8d6cad
HW
8067static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8068 u32 msr_index, u64 *pdata)
8069{
8070 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8071}
8072
67f4d428
NA
8073static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
8074 u32 pmc)
8075{
e6cd31f1
JM
8076 if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
8077 return 0;
8078 return -EINVAL;
67f4d428
NA
8079}
8080
222d21aa
AK
8081static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8082 u32 pmc, u64 *pdata)
8083{
c6702c9d 8084 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
222d21aa
AK
8085}
8086
6c3287f7
AK
8087static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8088{
8089 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8090}
8091
2953538e 8092static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8a76d7f2 8093 struct x86_instruction_info *info,
c4f035c6
AK
8094 enum x86_intercept_stage stage)
8095{
b3646477 8096 return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
21f1b8f2 8097 &ctxt->exception);
c4f035c6
AK
8098}
8099
e911eb3b 8100static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
f91af517
SC
8101 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8102 bool exact_only)
bdb42f5a 8103{
f91af517 8104 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
bdb42f5a
SB
8105}
8106
5ae78e95
SC
8107static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
8108{
8109 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
8110}
8111
8112static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8113{
8114 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8115}
8116
8117static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8118{
8119 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8120}
8121
a836839c
HW
8122static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8123{
8124 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8125}
8126
dd856efa
AK
8127static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8128{
27b4a9c4 8129 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
dd856efa
AK
8130}
8131
8132static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8133{
27b4a9c4 8134 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
dd856efa
AK
8135}
8136
801806d9
NA
8137static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8138{
b3646477 8139 static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
801806d9
NA
8140}
8141
6ed071f0
LP
8142static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
8143{
8144 return emul_to_vcpu(ctxt)->arch.hflags;
8145}
8146
4b8e1b32
PB
8147#ifndef CONFIG_KVM_SMM
8148static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8149{
8150 WARN_ON_ONCE(1);
8151 return X86EMUL_UNHANDLEABLE;
8152}
8153#endif
8154
25b17226
SC
8155static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8156{
8157 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8158}
8159
02d4160f
VK
8160static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8161{
8162 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8163}
8164
1cca2f8c
SC
8165static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8166{
8167 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8168
8169 if (!kvm->vm_bugged)
8170 kvm_vm_bugged(kvm);
8171}
8172
0225fb50 8173static const struct x86_emulate_ops emulate_ops = {
1cca2f8c 8174 .vm_bugged = emulator_vm_bugged,
dd856efa
AK
8175 .read_gpr = emulator_read_gpr,
8176 .write_gpr = emulator_write_gpr,
ce14e868
PB
8177 .read_std = emulator_read_std,
8178 .write_std = emulator_write_std,
1871c602 8179 .fetch = kvm_fetch_guest_virt,
bbd9b64e
CO
8180 .read_emulated = emulator_read_emulated,
8181 .write_emulated = emulator_write_emulated,
8182 .cmpxchg_emulated = emulator_cmpxchg_emulated,
3cb16fe7 8183 .invlpg = emulator_invlpg,
cf8f70bf
GN
8184 .pio_in_emulated = emulator_pio_in_emulated,
8185 .pio_out_emulated = emulator_pio_out_emulated,
1aa36616
AK
8186 .get_segment = emulator_get_segment,
8187 .set_segment = emulator_set_segment,
5951c442 8188 .get_cached_segment_base = emulator_get_cached_segment_base,
2dafc6c2 8189 .get_gdt = emulator_get_gdt,
160ce1f1 8190 .get_idt = emulator_get_idt,
1ac9d0cf
AK
8191 .set_gdt = emulator_set_gdt,
8192 .set_idt = emulator_set_idt,
52a46617
GN
8193 .get_cr = emulator_get_cr,
8194 .set_cr = emulator_set_cr,
9c537244 8195 .cpl = emulator_get_cpl,
35aa5375
GN
8196 .get_dr = emulator_get_dr,
8197 .set_dr = emulator_set_dr,
ac8d6cad
HW
8198 .set_msr_with_filter = emulator_set_msr_with_filter,
8199 .get_msr_with_filter = emulator_get_msr_with_filter,
717746e3 8200 .get_msr = emulator_get_msr,
67f4d428 8201 .check_pmc = emulator_check_pmc,
222d21aa 8202 .read_pmc = emulator_read_pmc,
6c3287f7 8203 .halt = emulator_halt,
bcaf5cc5 8204 .wbinvd = emulator_wbinvd,
d6aa1000 8205 .fix_hypercall = emulator_fix_hypercall,
c4f035c6 8206 .intercept = emulator_intercept,
bdb42f5a 8207 .get_cpuid = emulator_get_cpuid,
5ae78e95
SC
8208 .guest_has_long_mode = emulator_guest_has_long_mode,
8209 .guest_has_movbe = emulator_guest_has_movbe,
8210 .guest_has_fxsr = emulator_guest_has_fxsr,
a836839c 8211 .guest_has_rdpid = emulator_guest_has_rdpid,
801806d9 8212 .set_nmi_mask = emulator_set_nmi_mask,
6ed071f0 8213 .get_hflags = emulator_get_hflags,
ecc513e5 8214 .leave_smm = emulator_leave_smm,
25b17226 8215 .triple_fault = emulator_triple_fault,
02d4160f 8216 .set_xcr = emulator_set_xcr,
bbd9b64e
CO
8217};
8218
95cb2295
GN
8219static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8220{
b3646477 8221 u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
95cb2295
GN
8222 /*
8223 * an sti; sti; sequence only disable interrupts for the first
8224 * instruction. So, if the last instruction, be it emulated or
8225 * not, left the system with the INT_STI flag enabled, it
8226 * means that the last instruction is an sti. We should not
8227 * leave the flag on in this case. The same goes for mov ss
8228 */
37ccdcbe
PB
8229 if (int_shadow & mask)
8230 mask = 0;
6addfc42 8231 if (unlikely(int_shadow || mask)) {
b3646477 8232 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
6addfc42
PB
8233 if (!mask)
8234 kvm_make_request(KVM_REQ_EVENT, vcpu);
8235 }
95cb2295
GN
8236}
8237
7709aba8 8238static void inject_emulated_exception(struct kvm_vcpu *vcpu)
54b8486f 8239{
c9b8b07c 8240 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
ef54bcfe 8241
7709aba8
SC
8242 if (ctxt->exception.vector == PF_VECTOR)
8243 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8244 else if (ctxt->exception.error_code_valid)
da9cb575
AK
8245 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8246 ctxt->exception.error_code);
54b8486f 8247 else
da9cb575 8248 kvm_queue_exception(vcpu, ctxt->exception.vector);
54b8486f
GN
8249}
8250
c9b8b07c
SC
8251static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8252{
8253 struct x86_emulate_ctxt *ctxt;
8254
8255 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8256 if (!ctxt) {
8257 pr_err("kvm: failed to allocate vcpu's emulator\n");
8258 return NULL;
8259 }
8260
8261 ctxt->vcpu = vcpu;
8262 ctxt->ops = &emulate_ops;
8263 vcpu->arch.emulate_ctxt = ctxt;
8264
8265 return ctxt;
8266}
8267
8ec4722d
MG
8268static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8269{
c9b8b07c 8270 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d
MG
8271 int cs_db, cs_l;
8272
b3646477 8273 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8ec4722d 8274
744e699c 8275 ctxt->gpa_available = false;
adf52235 8276 ctxt->eflags = kvm_get_rflags(vcpu);
c8401dda
PB
8277 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8278
adf52235
TY
8279 ctxt->eip = kvm_rip_read(vcpu);
8280 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8281 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
42bf549f 8282 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
adf52235
TY
8283 cs_db ? X86EMUL_MODE_PROT32 :
8284 X86EMUL_MODE_PROT16;
a584539b 8285 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
adf52235 8286
da6393cd
WL
8287 ctxt->interruptibility = 0;
8288 ctxt->have_exception = false;
8289 ctxt->exception.vector = -1;
8290 ctxt->perm_ok = false;
8291
dd856efa 8292 init_decode_cache(ctxt);
7ae441ea 8293 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8ec4722d
MG
8294}
8295
9497e1f2 8296void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
63995653 8297{
c9b8b07c 8298 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
63995653
MG
8299 int ret;
8300
8301 init_emulate_ctxt(vcpu);
8302
9dac77fa
AK
8303 ctxt->op_bytes = 2;
8304 ctxt->ad_bytes = 2;
8305 ctxt->_eip = ctxt->eip + inc_eip;
9d74191a 8306 ret = emulate_int_real(ctxt, irq);
63995653 8307
9497e1f2
SC
8308 if (ret != X86EMUL_CONTINUE) {
8309 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8310 } else {
8311 ctxt->eip = ctxt->_eip;
8312 kvm_rip_write(vcpu, ctxt->eip);
8313 kvm_set_rflags(vcpu, ctxt->eflags);
8314 }
63995653
MG
8315}
8316EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8317
e615e355
DE
8318static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8319 u8 ndata, u8 *insn_bytes, u8 insn_size)
19238e75 8320{
19238e75 8321 struct kvm_run *run = vcpu->run;
e615e355
DE
8322 u64 info[5];
8323 u8 info_start;
8324
8325 /*
8326 * Zero the whole array used to retrieve the exit info, as casting to
8327 * u32 for select entries will leave some chunks uninitialized.
8328 */
8329 memset(&info, 0, sizeof(info));
8330
8331 static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
8332 &info[2], (u32 *)&info[3],
8333 (u32 *)&info[4]);
19238e75
AL
8334
8335 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8336 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
e615e355
DE
8337
8338 /*
8339 * There's currently space for 13 entries, but 5 are used for the exit
8340 * reason and info. Restrict to 4 to reduce the maintenance burden
8341 * when expanding kvm_run.emulation_failure in the future.
8342 */
8343 if (WARN_ON_ONCE(ndata > 4))
8344 ndata = 4;
8345
8346 /* Always include the flags as a 'data' entry. */
8347 info_start = 1;
19238e75
AL
8348 run->emulation_failure.flags = 0;
8349
8350 if (insn_size) {
e615e355
DE
8351 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8352 sizeof(run->emulation_failure.insn_bytes) != 16));
8353 info_start += 2;
19238e75
AL
8354 run->emulation_failure.flags |=
8355 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8356 run->emulation_failure.insn_size = insn_size;
8357 memset(run->emulation_failure.insn_bytes, 0x90,
8358 sizeof(run->emulation_failure.insn_bytes));
e615e355 8359 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
19238e75 8360 }
e615e355
DE
8361
8362 memcpy(&run->internal.data[info_start], info, sizeof(info));
8363 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8364 ndata * sizeof(data[0]));
8365
8366 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
19238e75
AL
8367}
8368
e615e355
DE
8369static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8370{
8371 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8372
8373 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8374 ctxt->fetch.end - ctxt->fetch.data);
8375}
8376
8377void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8378 u8 ndata)
8379{
8380 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
19238e75 8381}
e615e355
DE
8382EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8383
8384void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8385{
8386 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8387}
8388EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
19238e75 8389
e2366171 8390static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6d77dbfc 8391{
19238e75
AL
8392 struct kvm *kvm = vcpu->kvm;
8393
6d77dbfc
GN
8394 ++vcpu->stat.insn_emulation_fail;
8395 trace_kvm_emulate_insn_failed(vcpu);
e2366171 8396
42cbf068
SC
8397 if (emulation_type & EMULTYPE_VMWARE_GP) {
8398 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 8399 return 1;
42cbf068 8400 }
e2366171 8401
19238e75
AL
8402 if (kvm->arch.exit_on_emulation_error ||
8403 (emulation_type & EMULTYPE_SKIP)) {
e615e355 8404 prepare_emulation_ctxt_failure_exit(vcpu);
60fc3d02 8405 return 0;
738fece4
SC
8406 }
8407
22da61c9
SC
8408 kvm_queue_exception(vcpu, UD_VECTOR);
8409
b3646477 8410 if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
e615e355 8411 prepare_emulation_ctxt_failure_exit(vcpu);
60fc3d02 8412 return 0;
fc3a9157 8413 }
e2366171 8414
60fc3d02 8415 return 1;
6d77dbfc
GN
8416}
8417
736c291c 8418static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
991eebf9
GN
8419 bool write_fault_to_shadow_pgtable,
8420 int emulation_type)
a6f177ef 8421{
736c291c 8422 gpa_t gpa = cr2_or_gpa;
ba049e93 8423 kvm_pfn_t pfn;
a6f177ef 8424
92daa48b 8425 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
991eebf9
GN
8426 return false;
8427
92daa48b
SC
8428 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8429 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6c3dfeb6
SC
8430 return false;
8431
347a0d0d 8432 if (!vcpu->arch.mmu->root_role.direct) {
95b3cf69
XG
8433 /*
8434 * Write permission should be allowed since only
8435 * write access need to be emulated.
8436 */
736c291c 8437 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
a6f177ef 8438
95b3cf69
XG
8439 /*
8440 * If the mapping is invalid in guest, let cpu retry
8441 * it to generate fault.
8442 */
6e1d2a3f 8443 if (gpa == INVALID_GPA)
95b3cf69
XG
8444 return true;
8445 }
a6f177ef 8446
8e3d9d06
XG
8447 /*
8448 * Do not retry the unhandleable instruction if it faults on the
8449 * readonly host memory, otherwise it will goto a infinite loop:
8450 * retry instruction -> write #PF -> emulation fail -> retry
8451 * instruction -> ...
8452 */
8453 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
95b3cf69
XG
8454
8455 /*
8456 * If the instruction failed on the error pfn, it can not be fixed,
8457 * report the error to userspace.
8458 */
8459 if (is_error_noslot_pfn(pfn))
8460 return false;
8461
8462 kvm_release_pfn_clean(pfn);
8463
8464 /* The instructions are well-emulated on direct mmu. */
347a0d0d 8465 if (vcpu->arch.mmu->root_role.direct) {
95b3cf69
XG
8466 unsigned int indirect_shadow_pages;
8467
531810ca 8468 write_lock(&vcpu->kvm->mmu_lock);
95b3cf69 8469 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
531810ca 8470 write_unlock(&vcpu->kvm->mmu_lock);
95b3cf69
XG
8471
8472 if (indirect_shadow_pages)
8473 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8474
a6f177ef 8475 return true;
8e3d9d06 8476 }
a6f177ef 8477
95b3cf69
XG
8478 /*
8479 * if emulation was due to access to shadowed page table
8480 * and it failed try to unshadow page and re-enter the
8481 * guest to let CPU execute the instruction.
8482 */
8483 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
93c05d3e
XG
8484
8485 /*
8486 * If the access faults on its page table, it can not
8487 * be fixed by unprotecting shadow page and it should
8488 * be reported to userspace.
8489 */
8490 return !write_fault_to_shadow_pgtable;
a6f177ef
GN
8491}
8492
1cb3f3ae 8493static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
736c291c 8494 gpa_t cr2_or_gpa, int emulation_type)
1cb3f3ae
XG
8495{
8496 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
736c291c 8497 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
1cb3f3ae
XG
8498
8499 last_retry_eip = vcpu->arch.last_retry_eip;
8500 last_retry_addr = vcpu->arch.last_retry_addr;
8501
8502 /*
8503 * If the emulation is caused by #PF and it is non-page_table
8504 * writing instruction, it means the VM-EXIT is caused by shadow
8505 * page protected, we can zap the shadow page and retry this
8506 * instruction directly.
8507 *
8508 * Note: if the guest uses a non-page-table modifying instruction
8509 * on the PDE that points to the instruction, then we will unmap
8510 * the instruction and go to an infinite loop. So, we cache the
8511 * last retried eip and the last fault address, if we meet the eip
8512 * and the address again, we can break out of the potential infinite
8513 * loop.
8514 */
8515 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8516
92daa48b 8517 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
1cb3f3ae
XG
8518 return false;
8519
92daa48b
SC
8520 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8521 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6c3dfeb6
SC
8522 return false;
8523
1cb3f3ae
XG
8524 if (x86_page_table_writing_insn(ctxt))
8525 return false;
8526
736c291c 8527 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
1cb3f3ae
XG
8528 return false;
8529
8530 vcpu->arch.last_retry_eip = ctxt->eip;
736c291c 8531 vcpu->arch.last_retry_addr = cr2_or_gpa;
1cb3f3ae 8532
347a0d0d 8533 if (!vcpu->arch.mmu->root_role.direct)
736c291c 8534 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
1cb3f3ae 8535
22368028 8536 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
1cb3f3ae
XG
8537
8538 return true;
8539}
8540
716d51ab
GN
8541static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8542static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8543
4a1e10d5
PB
8544static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8545 unsigned long *db)
8546{
8547 u32 dr6 = 0;
8548 int i;
8549 u32 enable, rwlen;
8550
8551 enable = dr7;
8552 rwlen = dr7 >> 16;
8553 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8554 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8555 dr6 |= (1 << i);
8556 return dr6;
8557}
8558
120c2c4f 8559static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
663f4c61
PB
8560{
8561 struct kvm_run *kvm_run = vcpu->run;
8562
c8401dda 8563 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9a3ecd5e 8564 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
d5d260c5 8565 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
c8401dda
PB
8566 kvm_run->debug.arch.exception = DB_VECTOR;
8567 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 8568 return 0;
663f4c61 8569 }
120c2c4f 8570 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
60fc3d02 8571 return 1;
663f4c61
PB
8572}
8573
6affcbed
KH
8574int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8575{
b3646477 8576 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
f8ea7c60 8577 int r;
6affcbed 8578
b3646477 8579 r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
60fc3d02 8580 if (unlikely(!r))
f8ea7c60 8581 return 0;
c8401dda 8582
9cd803d4
EH
8583 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8584
c8401dda
PB
8585 /*
8586 * rflags is the old, "raw" value of the flags. The new value has
8587 * not been saved yet.
8588 *
8589 * This is correct even for TF set by the guest, because "the
8590 * processor will not generate this exception after the instruction
8591 * that sets the TF flag".
8592 */
8593 if (unlikely(rflags & X86_EFLAGS_TF))
120c2c4f 8594 r = kvm_vcpu_do_singlestep(vcpu);
60fc3d02 8595 return r;
6affcbed
KH
8596}
8597EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8598
baf67ca8 8599static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
4a1e10d5 8600{
baf67ca8
SC
8601 u32 shadow;
8602
8603 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
8604 return true;
8605
8606 /*
8607 * Intel CPUs inhibit code #DBs when MOV/POP SS blocking is active,
8608 * but AMD CPUs do not. MOV/POP SS blocking is rare, check that first
8609 * to avoid the relatively expensive CPUID lookup.
8610 */
8611 shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
8612 return (shadow & KVM_X86_SHADOW_INT_MOV_SS) &&
8613 guest_cpuid_is_intel(vcpu);
8614}
8615
750f8fcb
SC
8616static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
8617 int emulation_type, int *r)
4a1e10d5 8618{
750f8fcb
SC
8619 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
8620
8621 /*
8622 * Do not check for code breakpoints if hardware has already done the
8623 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
8624 * the instruction has passed all exception checks, and all intercepted
8625 * exceptions that trigger emulation have lower priority than code
8626 * breakpoints, i.e. the fact that the intercepted exception occurred
8627 * means any code breakpoints have already been serviced.
8628 *
8629 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
8630 * hardware has checked the RIP of the magic prefix, but not the RIP of
8631 * the instruction being emulated. The intent of forced emulation is
8632 * to behave as if KVM intercepted the instruction without an exception
8633 * and without a prefix.
8634 */
8635 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
8636 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
8637 return false;
8638
4a1e10d5
PB
8639 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8640 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
82b32774
NA
8641 struct kvm_run *kvm_run = vcpu->run;
8642 unsigned long eip = kvm_get_linear_rip(vcpu);
8643 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
8644 vcpu->arch.guest_debug_dr7,
8645 vcpu->arch.eff_db);
8646
8647 if (dr6 != 0) {
9a3ecd5e 8648 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
82b32774 8649 kvm_run->debug.arch.pc = eip;
4a1e10d5
PB
8650 kvm_run->debug.arch.exception = DB_VECTOR;
8651 kvm_run->exit_reason = KVM_EXIT_DEBUG;
60fc3d02 8652 *r = 0;
4a1e10d5
PB
8653 return true;
8654 }
8655 }
8656
4161a569 8657 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
baf67ca8 8658 !kvm_is_code_breakpoint_inhibited(vcpu)) {
82b32774
NA
8659 unsigned long eip = kvm_get_linear_rip(vcpu);
8660 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
4a1e10d5
PB
8661 vcpu->arch.dr7,
8662 vcpu->arch.db);
8663
8664 if (dr6 != 0) {
4d5523cf 8665 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
60fc3d02 8666 *r = 1;
4a1e10d5
PB
8667 return true;
8668 }
8669 }
8670
8671 return false;
8672}
8673
04789b66
LA
8674static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
8675{
2d7921c4
AM
8676 switch (ctxt->opcode_len) {
8677 case 1:
8678 switch (ctxt->b) {
8679 case 0xe4: /* IN */
8680 case 0xe5:
8681 case 0xec:
8682 case 0xed:
8683 case 0xe6: /* OUT */
8684 case 0xe7:
8685 case 0xee:
8686 case 0xef:
8687 case 0x6c: /* INS */
8688 case 0x6d:
8689 case 0x6e: /* OUTS */
8690 case 0x6f:
8691 return true;
8692 }
8693 break;
8694 case 2:
8695 switch (ctxt->b) {
8696 case 0x33: /* RDPMC */
8697 return true;
8698 }
8699 break;
04789b66
LA
8700 }
8701
8702 return false;
8703}
8704
4aa2691d 8705/*
fee060cd
SC
8706 * Decode an instruction for emulation. The caller is responsible for handling
8707 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
8708 * (and wrong) when emulating on an intercepted fault-like exception[*], as
8709 * code breakpoints have higher priority and thus have already been done by
8710 * hardware.
8711 *
8712 * [*] Except #MC, which is higher priority, but KVM should never emulate in
8713 * response to a machine check.
4aa2691d
WH
8714 */
8715int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
8716 void *insn, int insn_len)
8717{
4aa2691d 8718 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
fee060cd 8719 int r;
4aa2691d
WH
8720
8721 init_emulate_ctxt(vcpu);
8722
b35491e6 8723 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
4aa2691d
WH
8724
8725 trace_kvm_emulate_insn_start(vcpu);
8726 ++vcpu->stat.insn_emulation;
8727
8728 return r;
8729}
8730EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
8731
736c291c
SC
8732int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8733 int emulation_type, void *insn, int insn_len)
bbd9b64e 8734{
95cb2295 8735 int r;
c9b8b07c 8736 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7ae441ea 8737 bool writeback = true;
09e3e2a1
SC
8738 bool write_fault_to_spt;
8739
4d31d9ef 8740 if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
09e3e2a1 8741 return 1;
bbd9b64e 8742
c595ceee
PB
8743 vcpu->arch.l1tf_flush_l1d = true;
8744
93c05d3e
XG
8745 /*
8746 * Clear write_fault_to_shadow_pgtable here to ensure it is
8747 * never reused.
8748 */
09e3e2a1 8749 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
93c05d3e 8750 vcpu->arch.write_fault_to_shadow_pgtable = false;
8d7d8102 8751
571008da 8752 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4aa2691d 8753 kvm_clear_exception_queue(vcpu);
4a1e10d5 8754
fee060cd
SC
8755 /*
8756 * Return immediately if RIP hits a code breakpoint, such #DBs
8757 * are fault-like and are higher priority than any faults on
8758 * the code fetch itself.
8759 */
750f8fcb 8760 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
fee060cd
SC
8761 return r;
8762
4aa2691d
WH
8763 r = x86_decode_emulated_instruction(vcpu, emulation_type,
8764 insn, insn_len);
1d2887e2 8765 if (r != EMULATION_OK) {
b4000606 8766 if ((emulation_type & EMULTYPE_TRAP_UD) ||
c83fad65
SC
8767 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
8768 kvm_queue_exception(vcpu, UD_VECTOR);
60fc3d02 8769 return 1;
c83fad65 8770 }
736c291c
SC
8771 if (reexecute_instruction(vcpu, cr2_or_gpa,
8772 write_fault_to_spt,
8773 emulation_type))
60fc3d02 8774 return 1;
8530a79c 8775 if (ctxt->have_exception) {
c8848cee
JD
8776 /*
8777 * #UD should result in just EMULATION_FAILED, and trap-like
8778 * exception should not be encountered during decode.
8779 */
8780 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
8781 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
8530a79c 8782 inject_emulated_exception(vcpu);
60fc3d02 8783 return 1;
8530a79c 8784 }
e2366171 8785 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
8786 }
8787 }
8788
42cbf068
SC
8789 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
8790 !is_vmware_backdoor_opcode(ctxt)) {
8791 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
60fc3d02 8792 return 1;
42cbf068 8793 }
04789b66 8794
1957aa63 8795 /*
906fa904
HW
8796 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
8797 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
8798 * The caller is responsible for updating interruptibility state and
8799 * injecting single-step #DBs.
1957aa63 8800 */
ba8afb6b 8801 if (emulation_type & EMULTYPE_SKIP) {
5e854864
SC
8802 if (ctxt->mode != X86EMUL_MODE_PROT64)
8803 ctxt->eip = (u32)ctxt->_eip;
8804 else
8805 ctxt->eip = ctxt->_eip;
8806
906fa904
HW
8807 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
8808 r = 1;
8809 goto writeback;
8810 }
8811
5e854864 8812 kvm_rip_write(vcpu, ctxt->eip);
bb663c7a
NA
8813 if (ctxt->eflags & X86_EFLAGS_RF)
8814 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
60fc3d02 8815 return 1;
ba8afb6b
GN
8816 }
8817
736c291c 8818 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
60fc3d02 8819 return 1;
1cb3f3ae 8820
7ae441ea 8821 /* this is needed for vmware backdoor interface to work since it
4d2179e1 8822 changes registers values during IO operation */
7ae441ea
GN
8823 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
8824 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
dd856efa 8825 emulator_invalidate_register_cache(ctxt);
7ae441ea 8826 }
4d2179e1 8827
5cd21917 8828restart:
92daa48b
SC
8829 if (emulation_type & EMULTYPE_PF) {
8830 /* Save the faulting GPA (cr2) in the address field */
8831 ctxt->exception.address = cr2_or_gpa;
8832
8833 /* With shadow page tables, cr2 contains a GVA or nGPA. */
347a0d0d 8834 if (vcpu->arch.mmu->root_role.direct) {
744e699c
SC
8835 ctxt->gpa_available = true;
8836 ctxt->gpa_val = cr2_or_gpa;
92daa48b
SC
8837 }
8838 } else {
8839 /* Sanitize the address out of an abundance of paranoia. */
8840 ctxt->exception.address = 0;
8841 }
0f89b207 8842
9d74191a 8843 r = x86_emulate_insn(ctxt);
bbd9b64e 8844
775fde86 8845 if (r == EMULATION_INTERCEPTED)
60fc3d02 8846 return 1;
775fde86 8847
d2ddd1c4 8848 if (r == EMULATION_FAILED) {
736c291c 8849 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
991eebf9 8850 emulation_type))
60fc3d02 8851 return 1;
c3cd7ffa 8852
e2366171 8853 return handle_emulation_failure(vcpu, emulation_type);
bbd9b64e
CO
8854 }
8855
9d74191a 8856 if (ctxt->have_exception) {
60fc3d02 8857 r = 1;
7709aba8 8858 inject_emulated_exception(vcpu);
d2ddd1c4 8859 } else if (vcpu->arch.pio.count) {
0912c977
PB
8860 if (!vcpu->arch.pio.in) {
8861 /* FIXME: return into emulator if single-stepping. */
3457e419 8862 vcpu->arch.pio.count = 0;
0912c977 8863 } else {
7ae441ea 8864 writeback = false;
716d51ab
GN
8865 vcpu->arch.complete_userspace_io = complete_emulated_pio;
8866 }
60fc3d02 8867 r = 0;
7ae441ea 8868 } else if (vcpu->mmio_needed) {
bc8a0aaf
SC
8869 ++vcpu->stat.mmio_exits;
8870
7ae441ea
GN
8871 if (!vcpu->mmio_is_write)
8872 writeback = false;
60fc3d02 8873 r = 0;
716d51ab 8874 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
adbfb12d
HW
8875 } else if (vcpu->arch.complete_userspace_io) {
8876 writeback = false;
8877 r = 0;
7ae441ea 8878 } else if (r == EMULATION_RESTART)
5cd21917 8879 goto restart;
d2ddd1c4 8880 else
60fc3d02 8881 r = 1;
f850e2e6 8882
906fa904 8883writeback:
7ae441ea 8884 if (writeback) {
b3646477 8885 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
9d74191a 8886 toggle_interruptibility(vcpu, ctxt->interruptibility);
7ae441ea 8887 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5623f751
SC
8888
8889 /*
8890 * Note, EXCPT_DB is assumed to be fault-like as the emulator
8891 * only supports code breakpoints and general detect #DB, both
8892 * of which are fault-like.
8893 */
38827dbd 8894 if (!ctxt->have_exception ||
75ee23b3 8895 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9cd803d4 8896 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
018d70ff
EH
8897 if (ctxt->is_branch)
8898 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
75ee23b3 8899 kvm_rip_write(vcpu, ctxt->eip);
384dea1c 8900 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
120c2c4f 8901 r = kvm_vcpu_do_singlestep(vcpu);
2a890614 8902 static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
38827dbd 8903 __kvm_set_rflags(vcpu, ctxt->eflags);
75ee23b3 8904 }
6addfc42
PB
8905
8906 /*
8907 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
8908 * do nothing, and it will be requested again as soon as
8909 * the shadow expires. But we still need to check here,
8910 * because POPF has no interrupt shadow.
8911 */
8912 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
8913 kvm_make_request(KVM_REQ_EVENT, vcpu);
7ae441ea
GN
8914 } else
8915 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
e85d28f8
GN
8916
8917 return r;
de7d789a 8918}
c60658d1
SC
8919
8920int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
8921{
8922 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
8923}
8924EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
8925
8926int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
8927 void *insn, int insn_len)
8928{
8929 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
8930}
8931EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
de7d789a 8932
8764ed55
SC
8933static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
8934{
8935 vcpu->arch.pio.count = 0;
8936 return 1;
8937}
8938
45def77e
SC
8939static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
8940{
8941 vcpu->arch.pio.count = 0;
8942
8943 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
8944 return 1;
8945
8946 return kvm_skip_emulated_instruction(vcpu);
8947}
8948
dca7f128
SC
8949static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
8950 unsigned short port)
de7d789a 8951{
de3cd117 8952 unsigned long val = kvm_rax_read(vcpu);
2e3bb4d8
SC
8953 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
8954
8764ed55
SC
8955 if (ret)
8956 return ret;
45def77e 8957
8764ed55
SC
8958 /*
8959 * Workaround userspace that relies on old KVM behavior of %rip being
8960 * incremented prior to exiting to userspace to handle "OUT 0x7e".
8961 */
8962 if (port == 0x7e &&
8963 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
8964 vcpu->arch.complete_userspace_io =
8965 complete_fast_pio_out_port_0x7e;
8966 kvm_skip_emulated_instruction(vcpu);
8967 } else {
45def77e
SC
8968 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8969 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
8970 }
8764ed55 8971 return 0;
de7d789a 8972}
de7d789a 8973
8370c3d0
TL
8974static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
8975{
8976 unsigned long val;
8977
8978 /* We should only ever be called with arch.pio.count equal to 1 */
8979 BUG_ON(vcpu->arch.pio.count != 1);
8980
45def77e
SC
8981 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
8982 vcpu->arch.pio.count = 0;
8983 return 1;
8984 }
8985
8370c3d0 8986 /* For size less than 4 we merge, else we zero extend */
de3cd117 8987 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0 8988
7a6177d6 8989 complete_emulator_pio_in(vcpu, &val);
de3cd117 8990 kvm_rax_write(vcpu, val);
8370c3d0 8991
45def77e 8992 return kvm_skip_emulated_instruction(vcpu);
8370c3d0
TL
8993}
8994
dca7f128
SC
8995static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
8996 unsigned short port)
8370c3d0
TL
8997{
8998 unsigned long val;
8999 int ret;
9000
9001 /* For size less than 4 we merge, else we zero extend */
de3cd117 9002 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
8370c3d0 9003
2e3bb4d8 9004 ret = emulator_pio_in(vcpu, size, port, &val, 1);
8370c3d0 9005 if (ret) {
de3cd117 9006 kvm_rax_write(vcpu, val);
8370c3d0
TL
9007 return ret;
9008 }
9009
45def77e 9010 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8370c3d0
TL
9011 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9012
9013 return 0;
9014}
dca7f128
SC
9015
9016int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9017{
45def77e 9018 int ret;
dca7f128 9019
dca7f128 9020 if (in)
45def77e 9021 ret = kvm_fast_pio_in(vcpu, size, port);
dca7f128 9022 else
45def77e
SC
9023 ret = kvm_fast_pio_out(vcpu, size, port);
9024 return ret && kvm_skip_emulated_instruction(vcpu);
dca7f128
SC
9025}
9026EXPORT_SYMBOL_GPL(kvm_fast_pio);
8370c3d0 9027
251a5fd6 9028static int kvmclock_cpu_down_prep(unsigned int cpu)
8cfdc000 9029{
0a3aee0d 9030 __this_cpu_write(cpu_tsc_khz, 0);
251a5fd6 9031 return 0;
8cfdc000
ZA
9032}
9033
9034static void tsc_khz_changed(void *data)
c8076604 9035{
8cfdc000
ZA
9036 struct cpufreq_freqs *freq = data;
9037 unsigned long khz = 0;
9038
9039 if (data)
9040 khz = freq->new;
9041 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9042 khz = cpufreq_quick_get(raw_smp_processor_id());
9043 if (!khz)
9044 khz = tsc_khz;
0a3aee0d 9045 __this_cpu_write(cpu_tsc_khz, khz);
c8076604
GH
9046}
9047
5fa4ec9c 9048#ifdef CONFIG_X86_64
0092e434
VK
9049static void kvm_hyperv_tsc_notifier(void)
9050{
0092e434 9051 struct kvm *kvm;
0092e434
VK
9052 int cpu;
9053
0d9ce162 9054 mutex_lock(&kvm_lock);
0092e434
VK
9055 list_for_each_entry(kvm, &vm_list, vm_list)
9056 kvm_make_mclock_inprogress_request(kvm);
9057
6b6fcd28 9058 /* no guest entries from this point */
0092e434
VK
9059 hyperv_stop_tsc_emulation();
9060
9061 /* TSC frequency always matches when on Hyper-V */
9062 for_each_present_cpu(cpu)
9063 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
938c8745 9064 kvm_caps.max_guest_tsc_khz = tsc_khz;
0092e434
VK
9065
9066 list_for_each_entry(kvm, &vm_list, vm_list) {
869b4421 9067 __kvm_start_pvclock_update(kvm);
0092e434 9068 pvclock_update_vm_gtod_copy(kvm);
6b6fcd28 9069 kvm_end_pvclock_update(kvm);
0092e434 9070 }
6b6fcd28 9071
0d9ce162 9072 mutex_unlock(&kvm_lock);
0092e434 9073}
5fa4ec9c 9074#endif
0092e434 9075
df24014a 9076static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
c8076604 9077{
c8076604
GH
9078 struct kvm *kvm;
9079 struct kvm_vcpu *vcpu;
46808a4c
MZ
9080 int send_ipi = 0;
9081 unsigned long i;
c8076604 9082
8cfdc000
ZA
9083 /*
9084 * We allow guests to temporarily run on slowing clocks,
9085 * provided we notify them after, or to run on accelerating
9086 * clocks, provided we notify them before. Thus time never
9087 * goes backwards.
9088 *
9089 * However, we have a problem. We can't atomically update
9090 * the frequency of a given CPU from this function; it is
9091 * merely a notifier, which can be called from any CPU.
9092 * Changing the TSC frequency at arbitrary points in time
9093 * requires a recomputation of local variables related to
9094 * the TSC for each VCPU. We must flag these local variables
9095 * to be updated and be sure the update takes place with the
9096 * new frequency before any guests proceed.
9097 *
9098 * Unfortunately, the combination of hotplug CPU and frequency
9099 * change creates an intractable locking scenario; the order
9100 * of when these callouts happen is undefined with respect to
9101 * CPU hotplug, and they can race with each other. As such,
9102 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9103 * undefined; you can actually have a CPU frequency change take
9104 * place in between the computation of X and the setting of the
9105 * variable. To protect against this problem, all updates of
9106 * the per_cpu tsc_khz variable are done in an interrupt
9107 * protected IPI, and all callers wishing to update the value
9108 * must wait for a synchronous IPI to complete (which is trivial
9109 * if the caller is on the CPU already). This establishes the
9110 * necessary total order on variable updates.
9111 *
9112 * Note that because a guest time update may take place
9113 * anytime after the setting of the VCPU's request bit, the
9114 * correct TSC value must be set before the request. However,
9115 * to ensure the update actually makes it to any guest which
9116 * starts running in hardware virtualization between the set
9117 * and the acquisition of the spinlock, we must also ping the
9118 * CPU after setting the request bit.
9119 *
9120 */
9121
df24014a 9122 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 9123
0d9ce162 9124 mutex_lock(&kvm_lock);
c8076604 9125 list_for_each_entry(kvm, &vm_list, vm_list) {
988a2cae 9126 kvm_for_each_vcpu(i, vcpu, kvm) {
df24014a 9127 if (vcpu->cpu != cpu)
c8076604 9128 continue;
c285545f 9129 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0d9ce162 9130 if (vcpu->cpu != raw_smp_processor_id())
8cfdc000 9131 send_ipi = 1;
c8076604
GH
9132 }
9133 }
0d9ce162 9134 mutex_unlock(&kvm_lock);
c8076604
GH
9135
9136 if (freq->old < freq->new && send_ipi) {
9137 /*
9138 * We upscale the frequency. Must make the guest
9139 * doesn't see old kvmclock values while running with
9140 * the new frequency, otherwise we risk the guest sees
9141 * time go backwards.
9142 *
9143 * In case we update the frequency for another cpu
9144 * (which might be in guest context) send an interrupt
9145 * to kick the cpu out of guest context. Next time
9146 * guest context is entered kvmclock will be updated,
9147 * so the guest will not see stale values.
9148 */
df24014a 9149 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
c8076604 9150 }
df24014a
VK
9151}
9152
9153static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9154 void *data)
9155{
9156 struct cpufreq_freqs *freq = data;
9157 int cpu;
9158
9159 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9160 return 0;
9161 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9162 return 0;
9163
9164 for_each_cpu(cpu, freq->policy->cpus)
9165 __kvmclock_cpufreq_notifier(freq, cpu);
9166
c8076604
GH
9167 return 0;
9168}
9169
9170static struct notifier_block kvmclock_cpufreq_notifier_block = {
8cfdc000
ZA
9171 .notifier_call = kvmclock_cpufreq_notifier
9172};
9173
251a5fd6 9174static int kvmclock_cpu_online(unsigned int cpu)
8cfdc000 9175{
251a5fd6
SAS
9176 tsc_khz_changed(NULL);
9177 return 0;
8cfdc000
ZA
9178}
9179
b820cc0c
ZA
9180static void kvm_timer_init(void)
9181{
b820cc0c 9182 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
741e511b
SC
9183 max_tsc_khz = tsc_khz;
9184
9185 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9186 struct cpufreq_policy *policy;
9187 int cpu;
9188
9189 cpu = get_cpu();
9190 policy = cpufreq_cpu_get(cpu);
9191 if (policy) {
9192 if (policy->cpuinfo.max_freq)
9193 max_tsc_khz = policy->cpuinfo.max_freq;
9194 cpufreq_cpu_put(policy);
9195 }
9196 put_cpu();
9a11997e 9197 }
b820cc0c
ZA
9198 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9199 CPUFREQ_TRANSITION_NOTIFIER);
9200 }
460dd42e 9201
73c1b41e 9202 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
251a5fd6 9203 kvmclock_cpu_online, kvmclock_cpu_down_prep);
b820cc0c
ZA
9204}
9205
16e8d74d
MT
9206#ifdef CONFIG_X86_64
9207static void pvclock_gtod_update_fn(struct work_struct *work)
9208{
d828199e 9209 struct kvm *kvm;
d828199e 9210 struct kvm_vcpu *vcpu;
46808a4c 9211 unsigned long i;
d828199e 9212
0d9ce162 9213 mutex_lock(&kvm_lock);
d828199e
MT
9214 list_for_each_entry(kvm, &vm_list, vm_list)
9215 kvm_for_each_vcpu(i, vcpu, kvm)
105b21bb 9216 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
d828199e 9217 atomic_set(&kvm_guest_has_master_clock, 0);
0d9ce162 9218 mutex_unlock(&kvm_lock);
16e8d74d
MT
9219}
9220
9221static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9222
3f804f6d
TG
9223/*
9224 * Indirection to move queue_work() out of the tk_core.seq write held
9225 * region to prevent possible deadlocks against time accessors which
9226 * are invoked with work related locks held.
9227 */
9228static void pvclock_irq_work_fn(struct irq_work *w)
9229{
9230 queue_work(system_long_wq, &pvclock_gtod_work);
9231}
9232
9233static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9234
16e8d74d
MT
9235/*
9236 * Notification about pvclock gtod data update.
9237 */
9238static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9239 void *priv)
9240{
9241 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9242 struct timekeeper *tk = priv;
9243
9244 update_pvclock_gtod(tk);
9245
3f804f6d
TG
9246 /*
9247 * Disable master clock if host does not trust, or does not use,
9248 * TSC based clocksource. Delegate queue_work() to irq_work as
9249 * this is invoked with tk_core.seq write held.
16e8d74d 9250 */
b0c39dc6 9251 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
16e8d74d 9252 atomic_read(&kvm_guest_has_master_clock) != 0)
3f804f6d 9253 irq_work_queue(&pvclock_irq_work);
16e8d74d
MT
9254 return 0;
9255}
9256
9257static struct notifier_block pvclock_gtod_notifier = {
9258 .notifier_call = pvclock_gtod_notify,
9259};
9260#endif
9261
f8c16bba 9262int kvm_arch_init(void *opaque)
043405e1 9263{
d008dfdb 9264 struct kvm_x86_init_ops *ops = opaque;
94bda2f4 9265 u64 host_pat;
b820cc0c 9266 int r;
f8c16bba 9267
afaf0b2f 9268 if (kvm_x86_ops.hardware_enable) {
9dadfc4a 9269 pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
82ffad2d 9270 return -EEXIST;
f8c16bba
ZX
9271 }
9272
9273 if (!ops->cpu_has_kvm_support()) {
9dadfc4a
SC
9274 pr_err_ratelimited("kvm: no hardware support for '%s'\n",
9275 ops->runtime_ops->name);
82ffad2d 9276 return -EOPNOTSUPP;
f8c16bba
ZX
9277 }
9278 if (ops->disabled_by_bios()) {
9dadfc4a
SC
9279 pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
9280 ops->runtime_ops->name);
82ffad2d 9281 return -EOPNOTSUPP;
f8c16bba
ZX
9282 }
9283
b666a4b6
MO
9284 /*
9285 * KVM explicitly assumes that the guest has an FPU and
9286 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9287 * vCPU's FPU state as a fxregs_state struct.
9288 */
9289 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9290 printk(KERN_ERR "kvm: inadequate fpu\n");
82ffad2d 9291 return -EOPNOTSUPP;
b666a4b6
MO
9292 }
9293
5e17b2ee
TG
9294 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9295 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
82ffad2d 9296 return -EOPNOTSUPP;
b666a4b6
MO
9297 }
9298
94bda2f4
SC
9299 /*
9300 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9301 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
9302 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
9303 * with an exception. PAT[0] is set to WB on RESET and also by the
9304 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9305 */
9306 if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
9307 (host_pat & GENMASK(2, 0)) != 6) {
9308 pr_err("kvm: host PAT[0] is not WB\n");
82ffad2d 9309 return -EIO;
94bda2f4 9310 }
b666a4b6 9311
c9b8b07c
SC
9312 x86_emulator_cache = kvm_alloc_emulator_cache();
9313 if (!x86_emulator_cache) {
9314 pr_err("kvm: failed to allocate cache for x86 emulator\n");
82ffad2d 9315 return -ENOMEM;
c9b8b07c
SC
9316 }
9317
7e34fbd0
SC
9318 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9319 if (!user_return_msrs) {
9320 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
82ffad2d 9321 r = -ENOMEM;
c9b8b07c 9322 goto out_free_x86_emulator_cache;
013f6a5d 9323 }
e5fda4bb 9324 kvm_nr_uret_msrs = 0;
013f6a5d 9325
1d0e8480 9326 r = kvm_mmu_vendor_module_init();
97db56ce 9327 if (r)
013f6a5d 9328 goto out_free_percpu;
97db56ce 9329
b820cc0c 9330 kvm_timer_init();
c8076604 9331
cfc48181 9332 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
2acf923e 9333 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
938c8745 9334 kvm_caps.supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
cfc48181 9335 }
2acf923e 9336
0c5f81da 9337 if (pi_inject_timer == -1)
04d4e665 9338 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
16e8d74d
MT
9339#ifdef CONFIG_X86_64
9340 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
0092e434 9341
5fa4ec9c 9342 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434 9343 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
16e8d74d
MT
9344#endif
9345
f8c16bba 9346 return 0;
56c6d28a 9347
013f6a5d 9348out_free_percpu:
7e34fbd0 9349 free_percpu(user_return_msrs);
c9b8b07c
SC
9350out_free_x86_emulator_cache:
9351 kmem_cache_destroy(x86_emulator_cache);
56c6d28a 9352 return r;
043405e1 9353}
8776e519 9354
f8c16bba
ZX
9355void kvm_arch_exit(void)
9356{
0092e434 9357#ifdef CONFIG_X86_64
5fa4ec9c 9358 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
0092e434
VK
9359 clear_hv_tscchange_cb();
9360#endif
cef84c30 9361 kvm_lapic_exit();
ff9d07a0 9362
888d256e
JK
9363 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
9364 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9365 CPUFREQ_TRANSITION_NOTIFIER);
251a5fd6 9366 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
16e8d74d
MT
9367#ifdef CONFIG_X86_64
9368 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
3f804f6d 9369 irq_work_sync(&pvclock_irq_work);
594b27e6 9370 cancel_work_sync(&pvclock_gtod_work);
16e8d74d 9371#endif
afaf0b2f 9372 kvm_x86_ops.hardware_enable = NULL;
1d0e8480 9373 kvm_mmu_vendor_module_exit();
7e34fbd0 9374 free_percpu(user_return_msrs);
dfdc0a71 9375 kmem_cache_destroy(x86_emulator_cache);
b59b153d 9376#ifdef CONFIG_KVM_XEN
c462f859 9377 static_key_deferred_flush(&kvm_xen_enabled);
7d6bbebb 9378 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
b59b153d 9379#endif
56c6d28a 9380}
f8c16bba 9381
1460179d 9382static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
8776e519 9383{
91b99ea7
SC
9384 /*
9385 * The vCPU has halted, e.g. executed HLT. Update the run state if the
9386 * local APIC is in-kernel, the run loop will detect the non-runnable
9387 * state and halt the vCPU. Exit to userspace if the local APIC is
9388 * managed by userspace, in which case userspace is responsible for
9389 * handling wake events.
9390 */
8776e519 9391 ++vcpu->stat.halt_exits;
35754c98 9392 if (lapic_in_kernel(vcpu)) {
647daca2 9393 vcpu->arch.mp_state = state;
8776e519
HB
9394 return 1;
9395 } else {
647daca2 9396 vcpu->run->exit_reason = reason;
8776e519
HB
9397 return 0;
9398 }
9399}
647daca2 9400
1460179d 9401int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
647daca2 9402{
1460179d 9403 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
647daca2 9404}
1460179d 9405EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
5cb56059
JS
9406
9407int kvm_emulate_halt(struct kvm_vcpu *vcpu)
9408{
6affcbed
KH
9409 int ret = kvm_skip_emulated_instruction(vcpu);
9410 /*
9411 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
9412 * KVM_EXIT_DEBUG here.
9413 */
1460179d 9414 return kvm_emulate_halt_noskip(vcpu) && ret;
5cb56059 9415}
8776e519
HB
9416EXPORT_SYMBOL_GPL(kvm_emulate_halt);
9417
647daca2
TL
9418int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
9419{
9420 int ret = kvm_skip_emulated_instruction(vcpu);
9421
1460179d
SC
9422 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
9423 KVM_EXIT_AP_RESET_HOLD) && ret;
647daca2
TL
9424}
9425EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
9426
8ef81a9a 9427#ifdef CONFIG_X86_64
55dd00a7
MT
9428static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9429 unsigned long clock_type)
9430{
9431 struct kvm_clock_pairing clock_pairing;
899a31f5 9432 struct timespec64 ts;
80fbd89c 9433 u64 cycle;
55dd00a7
MT
9434 int ret;
9435
9436 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9437 return -KVM_EOPNOTSUPP;
9438
3a55f729
AR
9439 /*
9440 * When tsc is in permanent catchup mode guests won't be able to use
9441 * pvclock_read_retry loop to get consistent view of pvclock
9442 */
9443 if (vcpu->arch.tsc_always_catchup)
9444 return -KVM_EOPNOTSUPP;
9445
7ca7f3b9 9446 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
55dd00a7
MT
9447 return -KVM_EOPNOTSUPP;
9448
9449 clock_pairing.sec = ts.tv_sec;
9450 clock_pairing.nsec = ts.tv_nsec;
9451 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9452 clock_pairing.flags = 0;
bcbfbd8e 9453 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
55dd00a7
MT
9454
9455 ret = 0;
9456 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9457 sizeof(struct kvm_clock_pairing)))
9458 ret = -KVM_EFAULT;
9459
9460 return ret;
9461}
8ef81a9a 9462#endif
55dd00a7 9463
6aef266c
SV
9464/*
9465 * kvm_pv_kick_cpu_op: Kick a vcpu.
9466 *
9467 * @apicid - apicid of vcpu to be kicked.
9468 */
9d68c6f6 9469static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
6aef266c 9470{
8a414f94
VK
9471 /*
9472 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9473 * common code, e.g. for tracing. Defer initialization to the compiler.
9474 */
9475 struct kvm_lapic_irq lapic_irq = {
9476 .delivery_mode = APIC_DM_REMRD,
9477 .dest_mode = APIC_DEST_PHYSICAL,
9478 .shorthand = APIC_DEST_NOSHORT,
9479 .dest_id = apicid,
9480 };
6aef266c 9481
795a149e 9482 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6aef266c
SV
9483}
9484
4e19c36f
SS
9485bool kvm_apicv_activated(struct kvm *kvm)
9486{
9487 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9488}
9489EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9490
d5fa597e
ML
9491bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
9492{
9493 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
9494 ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
9495
9496 return (vm_reasons | vcpu_reasons) == 0;
9497}
9498EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
4f4c4a3e
SC
9499
9500static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
9501 enum kvm_apicv_inhibit reason, bool set)
9502{
9503 if (set)
9504 __set_bit(reason, inhibits);
9505 else
9506 __clear_bit(reason, inhibits);
9507
9508 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
9509}
9510
4651fc56 9511static void kvm_apicv_init(struct kvm *kvm)
4e19c36f 9512{
4f4c4a3e
SC
9513 unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
9514
187c8833 9515 init_rwsem(&kvm->arch.apicv_update_lock);
b0a1637f 9516
4f4c4a3e
SC
9517 set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
9518
ef8b4b72 9519 if (!enable_apicv)
4f4c4a3e 9520 set_or_clear_apicv_inhibit(inhibits,
80f0497c 9521 APICV_INHIBIT_REASON_DISABLE, true);
4e19c36f 9522}
4e19c36f 9523
4a7132ef 9524static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
71506297
WL
9525{
9526 struct kvm_vcpu *target = NULL;
9527 struct kvm_apic_map *map;
9528
4a7132ef
WL
9529 vcpu->stat.directed_yield_attempted++;
9530
72b268a8
WL
9531 if (single_task_running())
9532 goto no_yield;
9533
71506297 9534 rcu_read_lock();
4a7132ef 9535 map = rcu_dereference(vcpu->kvm->arch.apic_map);
71506297
WL
9536
9537 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9538 target = map->phys_map[dest_id]->vcpu;
9539
9540 rcu_read_unlock();
9541
4a7132ef
WL
9542 if (!target || !READ_ONCE(target->ready))
9543 goto no_yield;
9544
a1fa4cbd
WL
9545 /* Ignore requests to yield to self */
9546 if (vcpu == target)
9547 goto no_yield;
9548
4a7132ef
WL
9549 if (kvm_vcpu_yield_to(target) <= 0)
9550 goto no_yield;
9551
9552 vcpu->stat.directed_yield_successful++;
9553
9554no_yield:
9555 return;
71506297
WL
9556}
9557
0dbb1123
AK
9558static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9559{
9560 u64 ret = vcpu->run->hypercall.ret;
9561
9562 if (!is_64_bit_mode(vcpu))
9563 ret = (u32)ret;
9564 kvm_rax_write(vcpu, ret);
9565 ++vcpu->stat.hypercalls;
9566 return kvm_skip_emulated_instruction(vcpu);
9567}
9568
8776e519
HB
9569int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
9570{
9571 unsigned long nr, a0, a1, a2, a3, ret;
6356ee0c 9572 int op_64_bit;
8776e519 9573
23200b7a
JM
9574 if (kvm_xen_hypercall_enabled(vcpu->kvm))
9575 return kvm_xen_hypercall(vcpu);
9576
8f014550 9577 if (kvm_hv_hypercall_enabled(vcpu))
696ca779 9578 return kvm_hv_hypercall(vcpu);
55cd8e5a 9579
de3cd117
SC
9580 nr = kvm_rax_read(vcpu);
9581 a0 = kvm_rbx_read(vcpu);
9582 a1 = kvm_rcx_read(vcpu);
9583 a2 = kvm_rdx_read(vcpu);
9584 a3 = kvm_rsi_read(vcpu);
8776e519 9585
229456fc 9586 trace_kvm_hypercall(nr, a0, a1, a2, a3);
2714d1d3 9587
b5aead00 9588 op_64_bit = is_64_bit_hypercall(vcpu);
a449c7aa 9589 if (!op_64_bit) {
8776e519
HB
9590 nr &= 0xFFFFFFFF;
9591 a0 &= 0xFFFFFFFF;
9592 a1 &= 0xFFFFFFFF;
9593 a2 &= 0xFFFFFFFF;
9594 a3 &= 0xFFFFFFFF;
9595 }
9596
b3646477 9597 if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
07708c4a 9598 ret = -KVM_EPERM;
696ca779 9599 goto out;
07708c4a
JK
9600 }
9601
66570e96
OU
9602 ret = -KVM_ENOSYS;
9603
8776e519 9604 switch (nr) {
b93463aa
AK
9605 case KVM_HC_VAPIC_POLL_IRQ:
9606 ret = 0;
9607 break;
6aef266c 9608 case KVM_HC_KICK_CPU:
66570e96
OU
9609 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
9610 break;
9611
9d68c6f6 9612 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
4a7132ef 9613 kvm_sched_yield(vcpu, a1);
6aef266c
SV
9614 ret = 0;
9615 break;
8ef81a9a 9616#ifdef CONFIG_X86_64
55dd00a7
MT
9617 case KVM_HC_CLOCK_PAIRING:
9618 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
9619 break;
1ed199a4 9620#endif
4180bf1b 9621 case KVM_HC_SEND_IPI:
66570e96
OU
9622 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
9623 break;
9624
4180bf1b
WL
9625 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
9626 break;
71506297 9627 case KVM_HC_SCHED_YIELD:
66570e96
OU
9628 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
9629 break;
9630
4a7132ef 9631 kvm_sched_yield(vcpu, a0);
71506297
WL
9632 ret = 0;
9633 break;
0dbb1123
AK
9634 case KVM_HC_MAP_GPA_RANGE: {
9635 u64 gpa = a0, npages = a1, attrs = a2;
9636
9637 ret = -KVM_ENOSYS;
9638 if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
9639 break;
9640
9641 if (!PAGE_ALIGNED(gpa) || !npages ||
9642 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
9643 ret = -KVM_EINVAL;
9644 break;
9645 }
9646
9647 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
9648 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
9649 vcpu->run->hypercall.args[0] = gpa;
9650 vcpu->run->hypercall.args[1] = npages;
9651 vcpu->run->hypercall.args[2] = attrs;
9652 vcpu->run->hypercall.longmode = op_64_bit;
9653 vcpu->arch.complete_userspace_io = complete_hypercall_exit;
9654 return 0;
9655 }
8776e519
HB
9656 default:
9657 ret = -KVM_ENOSYS;
9658 break;
9659 }
696ca779 9660out:
a449c7aa
NA
9661 if (!op_64_bit)
9662 ret = (u32)ret;
de3cd117 9663 kvm_rax_write(vcpu, ret);
6356ee0c 9664
f11c3a8d 9665 ++vcpu->stat.hypercalls;
6356ee0c 9666 return kvm_skip_emulated_instruction(vcpu);
8776e519
HB
9667}
9668EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
9669
b6785def 9670static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8776e519 9671{
d6aa1000 9672 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8776e519 9673 char instruction[3];
5fdbf976 9674 unsigned long rip = kvm_rip_read(vcpu);
8776e519 9675
f1a9761f
OU
9676 /*
9677 * If the quirk is disabled, synthesize a #UD and let the guest pick up
9678 * the pieces.
9679 */
9680 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
9681 ctxt->exception.error_code_valid = false;
9682 ctxt->exception.vector = UD_VECTOR;
9683 ctxt->have_exception = true;
9684 return X86EMUL_PROPAGATE_FAULT;
9685 }
9686
b3646477 9687 static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
8776e519 9688
ce2e852e
DV
9689 return emulator_write_emulated(ctxt, rip, instruction, 3,
9690 &ctxt->exception);
8776e519
HB
9691}
9692
851ba692 9693static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
b6c7a5dc 9694{
782d422b
MG
9695 return vcpu->run->request_interrupt_window &&
9696 likely(!pic_in_kernel(vcpu->kvm));
b6c7a5dc
HB
9697}
9698
8d25b7be 9699/* Called within kvm->srcu read side. */
851ba692 9700static void post_kvm_run_save(struct kvm_vcpu *vcpu)
b6c7a5dc 9701{
851ba692
AK
9702 struct kvm_run *kvm_run = vcpu->run;
9703
c5063551 9704 kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
2d3ad1f4 9705 kvm_run->cr8 = kvm_get_cr8(vcpu);
b6c7a5dc 9706 kvm_run->apic_base = kvm_get_apic_base(vcpu);
f3d1436d 9707
127a457a
MG
9708 kvm_run->ready_for_interrupt_injection =
9709 pic_in_kernel(vcpu->kvm) ||
782d422b 9710 kvm_vcpu_ready_for_interrupt_injection(vcpu);
15aad3be
CQ
9711
9712 if (is_smm(vcpu))
9713 kvm_run->flags |= KVM_RUN_X86_SMM;
b6c7a5dc
HB
9714}
9715
95ba8273
GN
9716static void update_cr8_intercept(struct kvm_vcpu *vcpu)
9717{
9718 int max_irr, tpr;
9719
afaf0b2f 9720 if (!kvm_x86_ops.update_cr8_intercept)
95ba8273
GN
9721 return;
9722
bce87cce 9723 if (!lapic_in_kernel(vcpu))
88c808fd
AK
9724 return;
9725
ce0a58f4 9726 if (vcpu->arch.apic->apicv_active)
d62caabb
AS
9727 return;
9728
8db3baa2
GN
9729 if (!vcpu->arch.apic->vapic_addr)
9730 max_irr = kvm_lapic_find_highest_irr(vcpu);
9731 else
9732 max_irr = -1;
95ba8273
GN
9733
9734 if (max_irr != -1)
9735 max_irr >>= 4;
9736
9737 tpr = kvm_lapic_get_cr8(vcpu);
9738
b3646477 9739 static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
95ba8273
GN
9740}
9741
b97f0745 9742
cb6a32c2
SC
9743int kvm_check_nested_events(struct kvm_vcpu *vcpu)
9744{
92e7d5c8 9745 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
cb6a32c2
SC
9746 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9747 return 1;
9748 }
9749
9750 return kvm_x86_ops.nested_ops->check_events(vcpu);
9751}
9752
b97f0745
ML
9753static void kvm_inject_exception(struct kvm_vcpu *vcpu)
9754{
d4963e31 9755 trace_kvm_inj_exception(vcpu->arch.exception.vector,
a61d7c54
SC
9756 vcpu->arch.exception.has_error_code,
9757 vcpu->arch.exception.error_code,
9758 vcpu->arch.exception.injected);
9759
b97f0745
ML
9760 if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
9761 vcpu->arch.exception.error_code = false;
6ad75c5c 9762 static_call(kvm_x86_inject_exception)(vcpu);
b97f0745
ML
9763}
9764
e746c1f1
SC
9765/*
9766 * Check for any event (interrupt or exception) that is ready to be injected,
9767 * and if there is at least one event, inject the event with the highest
9768 * priority. This handles both "pending" events, i.e. events that have never
9769 * been injected into the guest, and "injected" events, i.e. events that were
9770 * injected as part of a previous VM-Enter, but weren't successfully delivered
9771 * and need to be re-injected.
9772 *
9773 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
9774 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
9775 * be able to inject exceptions in the "middle" of an instruction, and so must
9776 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
9777 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
9778 * boundaries is necessary and correct.
9779 *
9780 * For simplicity, KVM uses a single path to inject all events (except events
9781 * that are injected directly from L1 to L2) and doesn't explicitly track
9782 * instruction boundaries for asynchronous events. However, because VM-Exits
9783 * that can occur during instruction execution typically result in KVM skipping
9784 * the instruction or injecting an exception, e.g. instruction and exception
9785 * intercepts, and because pending exceptions have higher priority than pending
9786 * interrupts, KVM still honors instruction boundaries in most scenarios.
9787 *
9788 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
9789 * the instruction or inject an exception, then KVM can incorrecty inject a new
9790 * asynchrounous event if the event became pending after the CPU fetched the
9791 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
9792 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
9793 * injected on the restarted instruction instead of being deferred until the
9794 * instruction completes.
9795 *
9796 * In practice, this virtualization hole is unlikely to be observed by the
9797 * guest, and even less likely to cause functional problems. To detect the
9798 * hole, the guest would have to trigger an event on a side effect of an early
9799 * phase of instruction execution, e.g. on the instruction fetch from memory.
9800 * And for it to be a functional problem, the guest would need to depend on the
9801 * ordering between that side effect, the instruction completing, _and_ the
9802 * delivery of the asynchronous event.
9803 */
9804static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
9805 bool *req_immediate_exit)
95ba8273 9806{
28360f88 9807 bool can_inject;
b6b8a145
JK
9808 int r;
9809
6c593b52
SC
9810 /*
9811 * Process nested events first, as nested VM-Exit supercedes event
9812 * re-injection. If there's an event queued for re-injection, it will
9813 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
9814 */
9815 if (is_guest_mode(vcpu))
9816 r = kvm_check_nested_events(vcpu);
9817 else
9818 r = 0;
664f8e26
WL
9819
9820 /*
6c593b52
SC
9821 * Re-inject exceptions and events *especially* if immediate entry+exit
9822 * to/from L2 is needed, as any event that has already been injected
9823 * into L2 needs to complete its lifecycle before injecting a new event.
9824 *
9825 * Don't re-inject an NMI or interrupt if there is a pending exception.
9826 * This collision arises if an exception occurred while vectoring the
9827 * injected event, KVM intercepted said exception, and KVM ultimately
9828 * determined the fault belongs to the guest and queues the exception
9829 * for injection back into the guest.
9830 *
9831 * "Injected" interrupts can also collide with pending exceptions if
9832 * userspace ignores the "ready for injection" flag and blindly queues
9833 * an interrupt. In that case, prioritizing the exception is correct,
9834 * as the exception "occurred" before the exit to userspace. Trap-like
9835 * exceptions, e.g. most #DBs, have higher priority than interrupts.
9836 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
9837 * priority, they're only generated (pended) during instruction
9838 * execution, and interrupts are recognized at instruction boundaries.
9839 * Thus a pending fault-like exception means the fault occurred on the
9840 * *previous* instruction and must be serviced prior to recognizing any
9841 * new events in order to fully complete the previous instruction.
664f8e26 9842 */
6c593b52
SC
9843 if (vcpu->arch.exception.injected)
9844 kvm_inject_exception(vcpu);
7709aba8 9845 else if (kvm_is_exception_pending(vcpu))
6c593b52
SC
9846 ; /* see above */
9847 else if (vcpu->arch.nmi_injected)
9848 static_call(kvm_x86_inject_nmi)(vcpu);
9849 else if (vcpu->arch.interrupt.injected)
9850 static_call(kvm_x86_inject_irq)(vcpu, true);
664f8e26 9851
6c593b52
SC
9852 /*
9853 * Exceptions that morph to VM-Exits are handled above, and pending
9854 * exceptions on top of injected exceptions that do not VM-Exit should
9855 * either morph to #DF or, sadly, override the injected exception.
9856 */
3b82b8d7
SC
9857 WARN_ON_ONCE(vcpu->arch.exception.injected &&
9858 vcpu->arch.exception.pending);
9859
1a680e35 9860 /*
6c593b52
SC
9861 * Bail if immediate entry+exit to/from the guest is needed to complete
9862 * nested VM-Enter or event re-injection so that a different pending
9863 * event can be serviced (or if KVM needs to exit to userspace).
9864 *
9865 * Otherwise, continue processing events even if VM-Exit occurred. The
9866 * VM-Exit will have cleared exceptions that were meant for L2, but
9867 * there may now be events that can be injected into L1.
1a680e35 9868 */
6c593b52
SC
9869 if (r < 0)
9870 goto out;
664f8e26 9871
7709aba8
SC
9872 /*
9873 * A pending exception VM-Exit should either result in nested VM-Exit
9874 * or force an immediate re-entry and exit to/from L2, and exception
9875 * VM-Exits cannot be injected (flag should _never_ be set).
9876 */
9877 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
9878 vcpu->arch.exception_vmexit.pending);
9879
28360f88
SC
9880 /*
9881 * New events, other than exceptions, cannot be injected if KVM needs
9882 * to re-inject a previous event. See above comments on re-injecting
9883 * for why pending exceptions get priority.
9884 */
9885 can_inject = !kvm_event_needs_reinjection(vcpu);
664f8e26 9886
b59bb7bd 9887 if (vcpu->arch.exception.pending) {
5623f751
SC
9888 /*
9889 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
9890 * value pushed on the stack. Trap-like exception and all #DBs
9891 * leave RF as-is (KVM follows Intel's behavior in this regard;
9892 * AMD states that code breakpoint #DBs excplitly clear RF=0).
9893 *
9894 * Note, most versions of Intel's SDM and AMD's APM incorrectly
9895 * describe the behavior of General Detect #DBs, which are
9896 * fault-like. They do _not_ set RF, a la code breakpoints.
9897 */
d4963e31 9898 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
d6e8c854
NA
9899 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
9900 X86_EFLAGS_RF);
9901
d4963e31
SC
9902 if (vcpu->arch.exception.vector == DB_VECTOR) {
9903 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
f10c729f
JM
9904 if (vcpu->arch.dr7 & DR7_GD) {
9905 vcpu->arch.dr7 &= ~DR7_GD;
9906 kvm_update_dr7(vcpu);
9907 }
6bdf0662
NA
9908 }
9909
b97f0745 9910 kvm_inject_exception(vcpu);
a61d7c54
SC
9911
9912 vcpu->arch.exception.pending = false;
9913 vcpu->arch.exception.injected = true;
9914
c6b22f59 9915 can_inject = false;
1a680e35
LA
9916 }
9917
61e5f69e
ML
9918 /* Don't inject interrupts if the user asked to avoid doing so */
9919 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
9920 return 0;
9921
c9d40913
PB
9922 /*
9923 * Finally, inject interrupt events. If an event cannot be injected
9924 * due to architectural conditions (e.g. IF=0) a window-open exit
9925 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
9926 * and can architecturally be injected, but we cannot do it right now:
9927 * an interrupt could have arrived just now and we have to inject it
9928 * as a vmexit, or there could already an event in the queue, which is
9929 * indicated by can_inject. In that case we request an immediate exit
9930 * in order to make progress and get back here for another iteration.
9931 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
9932 */
31e83e21 9933#ifdef CONFIG_KVM_SMM
c9d40913 9934 if (vcpu->arch.smi_pending) {
b3646477 9935 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
c9d40913 9936 if (r < 0)
a5f6909a 9937 goto out;
c9d40913
PB
9938 if (r) {
9939 vcpu->arch.smi_pending = false;
9940 ++vcpu->arch.smi_count;
9941 enter_smm(vcpu);
9942 can_inject = false;
9943 } else
b3646477 9944 static_call(kvm_x86_enable_smi_window)(vcpu);
c9d40913 9945 }
31e83e21 9946#endif
c9d40913
PB
9947
9948 if (vcpu->arch.nmi_pending) {
b3646477 9949 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
c9d40913 9950 if (r < 0)
a5f6909a 9951 goto out;
c9d40913
PB
9952 if (r) {
9953 --vcpu->arch.nmi_pending;
9954 vcpu->arch.nmi_injected = true;
e27bc044 9955 static_call(kvm_x86_inject_nmi)(vcpu);
c9d40913 9956 can_inject = false;
b3646477 9957 WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
c9d40913
PB
9958 }
9959 if (vcpu->arch.nmi_pending)
b3646477 9960 static_call(kvm_x86_enable_nmi_window)(vcpu);
c9d40913 9961 }
1a680e35 9962
c9d40913 9963 if (kvm_cpu_has_injectable_intr(vcpu)) {
b3646477 9964 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
c9d40913 9965 if (r < 0)
a5f6909a 9966 goto out;
c9d40913
PB
9967 if (r) {
9968 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
2d613912 9969 static_call(kvm_x86_inject_irq)(vcpu, false);
b3646477 9970 WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
c9d40913
PB
9971 }
9972 if (kvm_cpu_has_injectable_intr(vcpu))
b3646477 9973 static_call(kvm_x86_enable_irq_window)(vcpu);
95ba8273 9974 }
ee2cd4b7 9975
c9d40913 9976 if (is_guest_mode(vcpu) &&
5b4ac1a1
PB
9977 kvm_x86_ops.nested_ops->has_events &&
9978 kvm_x86_ops.nested_ops->has_events(vcpu))
c9d40913
PB
9979 *req_immediate_exit = true;
9980
dea0d5a2
SC
9981 /*
9982 * KVM must never queue a new exception while injecting an event; KVM
9983 * is done emulating and should only propagate the to-be-injected event
9984 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
9985 * infinite loop as KVM will bail from VM-Enter to inject the pending
9986 * exception and start the cycle all over.
9987 *
9988 * Exempt triple faults as they have special handling and won't put the
9989 * vCPU into an infinite loop. Triple fault can be queued when running
9990 * VMX without unrestricted guest, as that requires KVM to emulate Real
9991 * Mode events (see kvm_inject_realmode_interrupt()).
9992 */
9993 WARN_ON_ONCE(vcpu->arch.exception.pending ||
9994 vcpu->arch.exception_vmexit.pending);
a5f6909a 9995 return 0;
c9d40913 9996
a5f6909a
JM
9997out:
9998 if (r == -EBUSY) {
9999 *req_immediate_exit = true;
10000 r = 0;
10001 }
10002 return r;
95ba8273
GN
10003}
10004
7460fb4a
AK
10005static void process_nmi(struct kvm_vcpu *vcpu)
10006{
10007 unsigned limit = 2;
10008
10009 /*
10010 * x86 is limited to one NMI running, and one NMI pending after it.
10011 * If an NMI is already in progress, limit further NMIs to just one.
10012 * Otherwise, allow two (and we'll inject the first one immediately).
10013 */
b3646477 10014 if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
7460fb4a
AK
10015 limit = 1;
10016
10017 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10018 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10019 kvm_make_request(KVM_REQ_EVENT, vcpu);
10020}
10021
7ee30bc1
NNL
10022void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10023 unsigned long *vcpu_bitmap)
10024{
620b2438 10025 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
7ee30bc1
NNL
10026}
10027
2860c4b1
PB
10028void kvm_make_scan_ioapic_request(struct kvm *kvm)
10029{
10030 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10031}
10032
8df14af4
SS
10033void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10034{
ce0a58f4 10035 struct kvm_lapic *apic = vcpu->arch.apic;
06ef8134
ML
10036 bool activate;
10037
8df14af4
SS
10038 if (!lapic_in_kernel(vcpu))
10039 return;
10040
187c8833 10041 down_read(&vcpu->kvm->arch.apicv_update_lock);
66c768d3 10042 preempt_disable();
b0a1637f 10043
8fc9c7a3
SS
10044 /* Do not activate APICV when APIC is disabled */
10045 activate = kvm_vcpu_apicv_activated(vcpu) &&
10046 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
d5fa597e 10047
ce0a58f4 10048 if (apic->apicv_active == activate)
06ef8134
ML
10049 goto out;
10050
ce0a58f4 10051 apic->apicv_active = activate;
8df14af4 10052 kvm_apic_update_apicv(vcpu);
b3646477 10053 static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
bca66dbc
VK
10054
10055 /*
10056 * When APICv gets disabled, we may still have injected interrupts
10057 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10058 * still active when the interrupt got accepted. Make sure
e746c1f1 10059 * kvm_check_and_inject_events() is called to check for that.
bca66dbc 10060 */
ce0a58f4 10061 if (!apic->apicv_active)
bca66dbc 10062 kvm_make_request(KVM_REQ_EVENT, vcpu);
b0a1637f 10063
06ef8134 10064out:
66c768d3 10065 preempt_enable();
187c8833 10066 up_read(&vcpu->kvm->arch.apicv_update_lock);
8df14af4
SS
10067}
10068EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
10069
320af55a
SC
10070void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10071 enum kvm_apicv_inhibit reason, bool set)
8df14af4 10072{
b0a1637f 10073 unsigned long old, new;
8e205a6b 10074
187c8833
SC
10075 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10076
7491b7b2 10077 if (!static_call(kvm_x86_check_apicv_inhibit_reasons)(reason))
ef8efd7a
SS
10078 return;
10079
b0a1637f
ML
10080 old = new = kvm->arch.apicv_inhibit_reasons;
10081
4f4c4a3e 10082 set_or_clear_apicv_inhibit(&new, reason, set);
8e205a6b 10083
36222b11 10084 if (!!old != !!new) {
ee49a893
SC
10085 /*
10086 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10087 * false positives in the sanity check WARN in svm_vcpu_run().
10088 * This task will wait for all vCPUs to ack the kick IRQ before
10089 * updating apicv_inhibit_reasons, and all other vCPUs will
10090 * block on acquiring apicv_update_lock so that vCPUs can't
10091 * redo svm_vcpu_run() without seeing the new inhibit state.
10092 *
10093 * Note, holding apicv_update_lock and taking it in the read
10094 * side (handling the request) also prevents other vCPUs from
10095 * servicing the request with a stale apicv_inhibit_reasons.
10096 */
36222b11 10097 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
b0a1637f 10098 kvm->arch.apicv_inhibit_reasons = new;
36222b11
ML
10099 if (new) {
10100 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
074c0080
BG
10101 int idx = srcu_read_lock(&kvm->srcu);
10102
36222b11 10103 kvm_zap_gfn_range(kvm, gfn, gfn+1);
074c0080 10104 srcu_read_unlock(&kvm->srcu, idx);
36222b11 10105 }
7491b7b2 10106 } else {
b0a1637f 10107 kvm->arch.apicv_inhibit_reasons = new;
7491b7b2 10108 }
b0a1637f 10109}
7d611233 10110
320af55a
SC
10111void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10112 enum kvm_apicv_inhibit reason, bool set)
b0a1637f 10113{
f1575642
SC
10114 if (!enable_apicv)
10115 return;
10116
187c8833 10117 down_write(&kvm->arch.apicv_update_lock);
320af55a 10118 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
187c8833 10119 up_write(&kvm->arch.apicv_update_lock);
8df14af4 10120}
320af55a 10121EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
8df14af4 10122
3d81bc7e 10123static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
c7c9c56c 10124{
dcbd3e49 10125 if (!kvm_apic_present(vcpu))
3d81bc7e 10126 return;
c7c9c56c 10127
6308630b 10128 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
c7c9c56c 10129
b053b2ae 10130 if (irqchip_split(vcpu->kvm))
6308630b 10131 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
db2bdcbb 10132 else {
37c4dbf3 10133 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
e97f852f
WL
10134 if (ioapic_in_kernel(vcpu->kvm))
10135 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
db2bdcbb 10136 }
e40ff1d6
LA
10137
10138 if (is_guest_mode(vcpu))
10139 vcpu->arch.load_eoi_exitmap_pending = true;
10140 else
10141 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10142}
10143
10144static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10145{
10146 u64 eoi_exit_bitmap[4];
10147
10148 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10149 return;
10150
c5adbb3a 10151 if (to_hv_vcpu(vcpu)) {
f2bc14b6
VK
10152 bitmap_or((ulong *)eoi_exit_bitmap,
10153 vcpu->arch.ioapic_handled_vectors,
10154 to_hv_synic(vcpu)->vec_bitmap, 256);
abb6d479 10155 static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
c5adbb3a 10156 return;
10157 }
f2bc14b6 10158
abb6d479 10159 static_call_cond(kvm_x86_load_eoi_exitmap)(
c5adbb3a 10160 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
c7c9c56c
YZ
10161}
10162
e649b3f0
ET
10163void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
10164 unsigned long start, unsigned long end)
b1394e74
RK
10165{
10166 unsigned long apic_address;
10167
10168 /*
10169 * The physical address of apic access page is stored in the VMCS.
10170 * Update it when it becomes invalid.
10171 */
10172 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
10173 if (start <= apic_address && apic_address < end)
10174 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
10175}
10176
683412cc
MZ
10177void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10178{
10179 static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
10180}
10181
d081a343 10182static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
4256f43f 10183{
35754c98 10184 if (!lapic_in_kernel(vcpu))
f439ed27
PB
10185 return;
10186
2a890614 10187 static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
4256f43f 10188}
4256f43f 10189
d264ee0c
SC
10190void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
10191{
10192 smp_send_reschedule(vcpu->cpu);
10193}
10194EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
10195
9357d939 10196/*
8d25b7be 10197 * Called within kvm->srcu read side.
362c698f 10198 * Returns 1 to let vcpu_run() continue the guest execution loop without
9357d939
TY
10199 * exiting to the userspace. Otherwise, the value will be returned to the
10200 * userspace.
10201 */
851ba692 10202static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
b6c7a5dc
HB
10203{
10204 int r;
62a193ed
MG
10205 bool req_int_win =
10206 dm_request_for_irq_injection(vcpu) &&
10207 kvm_cpu_accept_dm_intr(vcpu);
404d5d7b 10208 fastpath_t exit_fastpath;
62a193ed 10209
730dca42 10210 bool req_immediate_exit = false;
b6c7a5dc 10211
fb04a1ed
PX
10212 /* Forbid vmenter if vcpu dirty ring is soft-full */
10213 if (unlikely(vcpu->kvm->dirty_ring_size &&
10214 kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
10215 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
10216 trace_kvm_dirty_ring_exit(vcpu);
10217 r = 0;
10218 goto out;
10219 }
10220
2fa6e1e1 10221 if (kvm_request_pending(vcpu)) {
f4d31653 10222 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
67369273
SC
10223 r = -EIO;
10224 goto out;
10225 }
729c15c2 10226 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
9a78e158 10227 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
671ddc70
JM
10228 r = 0;
10229 goto out;
10230 }
10231 }
527d5cd7
SC
10232 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10233 kvm_mmu_free_obsolete_roots(vcpu);
a8eeb04a 10234 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
2f599714 10235 __kvm_migrate_timers(vcpu);
d828199e 10236 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6b6fcd28 10237 kvm_update_masterclock(vcpu->kvm);
0061d53d
MT
10238 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10239 kvm_gen_kvmclock_update(vcpu);
34c238a1
ZA
10240 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10241 r = kvm_guest_time_update(vcpu);
8cfdc000
ZA
10242 if (unlikely(r))
10243 goto out;
10244 }
a8eeb04a 10245 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4731d4c7 10246 kvm_mmu_sync_roots(vcpu);
727a7e27
PB
10247 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10248 kvm_mmu_load_pgd(vcpu);
e94cea09
SC
10249
10250 /*
10251 * Note, the order matters here, as flushing "all" TLB entries
10252 * also flushes the "current" TLB entries, i.e. servicing the
10253 * flush "all" will clear any request to flush "current".
10254 */
10255 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
7780938c 10256 kvm_vcpu_flush_tlb_all(vcpu);
eeeb4f67 10257
40e5f908 10258 kvm_service_local_tlb_flush_requests(vcpu);
eeeb4f67 10259
0823570f
VK
10260 /*
10261 * Fall back to a "full" guest flush if Hyper-V's precise
10262 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
10263 * the flushes are considered "remote" and not "local" because
10264 * the requests can be initiated from other vCPUs.
10265 */
10266 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10267 kvm_hv_vcpu_flush_tlb(vcpu))
adc43caa
VK
10268 kvm_vcpu_flush_tlb_guest(vcpu);
10269
a8eeb04a 10270 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
851ba692 10271 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
b93463aa
AK
10272 r = 0;
10273 goto out;
10274 }
92e7d5c8
ML
10275 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10276 if (is_guest_mode(vcpu))
cb6a32c2 10277 kvm_x86_ops.nested_ops->triple_fault(vcpu);
92e7d5c8
ML
10278
10279 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
cb6a32c2
SC
10280 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10281 vcpu->mmio_needed = 0;
10282 r = 0;
df0bb47b 10283 goto out;
cb6a32c2 10284 }
71c4dfaf 10285 }
af585b92
GN
10286 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10287 /* Page is swapped out. Do synthetic halt */
10288 vcpu->arch.apf.halted = true;
10289 r = 1;
10290 goto out;
10291 }
c9aaa895
GC
10292 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10293 record_steal_time(vcpu);
cf7316d0 10294#ifdef CONFIG_KVM_SMM
64d60670
PB
10295 if (kvm_check_request(KVM_REQ_SMI, vcpu))
10296 process_smi(vcpu);
cf7316d0 10297#endif
7460fb4a
AK
10298 if (kvm_check_request(KVM_REQ_NMI, vcpu))
10299 process_nmi(vcpu);
f5132b01 10300 if (kvm_check_request(KVM_REQ_PMU, vcpu))
c6702c9d 10301 kvm_pmu_handle_event(vcpu);
f5132b01 10302 if (kvm_check_request(KVM_REQ_PMI, vcpu))
c6702c9d 10303 kvm_pmu_deliver_pmi(vcpu);
7543a635
SR
10304 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10305 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10306 if (test_bit(vcpu->arch.pending_ioapic_eoi,
6308630b 10307 vcpu->arch.ioapic_handled_vectors)) {
7543a635
SR
10308 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10309 vcpu->run->eoi.vector =
10310 vcpu->arch.pending_ioapic_eoi;
10311 r = 0;
10312 goto out;
10313 }
10314 }
3d81bc7e
YZ
10315 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10316 vcpu_scan_ioapic(vcpu);
e40ff1d6
LA
10317 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10318 vcpu_load_eoi_exitmap(vcpu);
4256f43f
TC
10319 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10320 kvm_vcpu_reload_apic_access_page(vcpu);
2ce79189
AS
10321 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10322 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10323 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
d495f942 10324 vcpu->run->system_event.ndata = 0;
2ce79189
AS
10325 r = 0;
10326 goto out;
10327 }
e516cebb
AS
10328 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10329 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10330 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
d495f942 10331 vcpu->run->system_event.ndata = 0;
e516cebb
AS
10332 r = 0;
10333 goto out;
10334 }
db397571 10335 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
9ff5e030
VK
10336 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10337
db397571 10338 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
9ff5e030 10339 vcpu->run->hyperv = hv_vcpu->exit;
db397571
AS
10340 r = 0;
10341 goto out;
10342 }
f3b138c5
AS
10343
10344 /*
10345 * KVM_REQ_HV_STIMER has to be processed after
10346 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10347 * depend on the guest clock being up-to-date
10348 */
1f4b34f8
AS
10349 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10350 kvm_hv_process_stimers(vcpu);
8df14af4
SS
10351 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10352 kvm_vcpu_update_apicv(vcpu);
557a961a
VK
10353 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10354 kvm_check_async_pf_completion(vcpu);
1a155254 10355 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
b3646477 10356 static_call(kvm_x86_msr_filter_changed)(vcpu);
a85863c2
MS
10357
10358 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10359 static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
2f52d58c 10360 }
b93463aa 10361
40da8ccd
DW
10362 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10363 kvm_xen_has_interrupt(vcpu)) {
0f1e261e 10364 ++vcpu->stat.req_event;
4fe09bcf
JM
10365 r = kvm_apic_accept_events(vcpu);
10366 if (r < 0) {
10367 r = 0;
10368 goto out;
10369 }
66450a21
JK
10370 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10371 r = 1;
10372 goto out;
10373 }
10374
e746c1f1 10375 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
a5f6909a
JM
10376 if (r < 0) {
10377 r = 0;
10378 goto out;
10379 }
c9d40913 10380 if (req_int_win)
b3646477 10381 static_call(kvm_x86_enable_irq_window)(vcpu);
b463a6f7
AK
10382
10383 if (kvm_lapic_enabled(vcpu)) {
10384 update_cr8_intercept(vcpu);
10385 kvm_lapic_sync_to_vapic(vcpu);
10386 }
10387 }
10388
d8368af8
AK
10389 r = kvm_mmu_reload(vcpu);
10390 if (unlikely(r)) {
d905c069 10391 goto cancel_injection;
d8368af8
AK
10392 }
10393
b6c7a5dc
HB
10394 preempt_disable();
10395
e27bc044 10396 static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
b95234c8
PB
10397
10398 /*
10399 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
10400 * IPI are then delayed after guest entry, which ensures that they
10401 * result in virtual interrupt delivery.
10402 */
10403 local_irq_disable();
66fa226c
ML
10404
10405 /* Store vcpu->apicv_active before vcpu->mode. */
10406 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
6b7e2d09 10407
2031f287 10408 kvm_vcpu_srcu_read_unlock(vcpu);
01b71917 10409
0f127d12 10410 /*
b95234c8 10411 * 1) We should set ->mode before checking ->requests. Please see
cde9af6e 10412 * the comment in kvm_vcpu_exiting_guest_mode().
b95234c8 10413 *
81b01667 10414 * 2) For APICv, we should set ->mode before checking PID.ON. This
b95234c8
PB
10415 * pairs with the memory barrier implicit in pi_test_and_set_on
10416 * (see vmx_deliver_posted_interrupt).
10417 *
10418 * 3) This also orders the write to mode from any reads to the page
10419 * tables done while the VCPU is running. Please see the comment
10420 * in kvm_flush_remote_tlbs.
6b7e2d09 10421 */
01b71917 10422 smp_mb__after_srcu_read_unlock();
b6c7a5dc 10423
b95234c8 10424 /*
0f65a9d3
SC
10425 * Process pending posted interrupts to handle the case where the
10426 * notification IRQ arrived in the host, or was never sent (because the
10427 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
10428 * status, KVM doesn't update assigned devices when APICv is inhibited,
10429 * i.e. they can post interrupts even if APICv is temporarily disabled.
b95234c8 10430 */
37c4dbf3
PB
10431 if (kvm_lapic_enabled(vcpu))
10432 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
32f88400 10433
5a9f5443 10434 if (kvm_vcpu_exit_request(vcpu)) {
6b7e2d09 10435 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 10436 smp_wmb();
6c142801
AK
10437 local_irq_enable();
10438 preempt_enable();
2031f287 10439 kvm_vcpu_srcu_read_lock(vcpu);
6c142801 10440 r = 1;
d905c069 10441 goto cancel_injection;
6c142801
AK
10442 }
10443
c43203ca
PB
10444 if (req_immediate_exit) {
10445 kvm_make_request(KVM_REQ_EVENT, vcpu);
b3646477 10446 static_call(kvm_x86_request_immediate_exit)(vcpu);
c43203ca 10447 }
d6185f20 10448
2620fe26
SC
10449 fpregs_assert_state_consistent();
10450 if (test_thread_flag(TIF_NEED_FPU_LOAD))
10451 switch_fpu_return();
5f409e20 10452
ec5be88a
JL
10453 if (vcpu->arch.guest_fpu.xfd_err)
10454 wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10455
42dbaa5a 10456 if (unlikely(vcpu->arch.switch_db_regs)) {
42dbaa5a
JK
10457 set_debugreg(0, 7);
10458 set_debugreg(vcpu->arch.eff_db[0], 0);
10459 set_debugreg(vcpu->arch.eff_db[1], 1);
10460 set_debugreg(vcpu->arch.eff_db[2], 2);
10461 set_debugreg(vcpu->arch.eff_db[3], 3);
f85d4016
LJ
10462 } else if (unlikely(hw_breakpoint_active())) {
10463 set_debugreg(0, 7);
42dbaa5a 10464 }
b6c7a5dc 10465
b2d2af7e
MR
10466 guest_timing_enter_irqoff();
10467
d89d04ab 10468 for (;;) {
ee49a893
SC
10469 /*
10470 * Assert that vCPU vs. VM APICv state is consistent. An APICv
10471 * update must kick and wait for all vCPUs before toggling the
10472 * per-VM state, and responsing vCPUs must wait for the update
10473 * to complete before servicing KVM_REQ_APICV_UPDATE.
10474 */
f8d8ac21
SS
10475 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
10476 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
ee49a893 10477
e27bc044 10478 exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu);
d89d04ab
PB
10479 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
10480 break;
10481
37c4dbf3
PB
10482 if (kvm_lapic_enabled(vcpu))
10483 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
de7cd3f6
PB
10484
10485 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
d89d04ab
PB
10486 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
10487 break;
10488 }
de7cd3f6 10489 }
b6c7a5dc 10490
c77fb5fe
PB
10491 /*
10492 * Do this here before restoring debug registers on the host. And
10493 * since we do this before handling the vmexit, a DR access vmexit
10494 * can (a) read the correct value of the debug registers, (b) set
10495 * KVM_DEBUGREG_WONT_EXIT again.
10496 */
10497 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
c77fb5fe 10498 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
b3646477 10499 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
70e4da7a 10500 kvm_update_dr0123(vcpu);
70e4da7a 10501 kvm_update_dr7(vcpu);
c77fb5fe
PB
10502 }
10503
24f1e32c
FW
10504 /*
10505 * If the guest has used debug registers, at least dr7
10506 * will be disabled while returning to the host.
10507 * If we don't have active breakpoints in the host, we don't
10508 * care about the messed up debug address registers. But if
10509 * we have some of them active, restore the old state.
10510 */
59d8eb53 10511 if (hw_breakpoint_active())
24f1e32c 10512 hw_breakpoint_restore();
42dbaa5a 10513
c967118d 10514 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
4ba76538 10515 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1d5f066e 10516
6b7e2d09 10517 vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9 10518 smp_wmb();
a547c6db 10519
b5274b1b
KT
10520 /*
10521 * Sync xfd before calling handle_exit_irqoff() which may
10522 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
10523 * in #NM irqoff handler).
10524 */
10525 if (vcpu->arch.xfd_no_write_intercept)
10526 fpu_sync_guest_vmexit_xfd_state();
10527
b3646477 10528 static_call(kvm_x86_handle_exit_irqoff)(vcpu);
b6c7a5dc 10529
ec5be88a
JL
10530 if (vcpu->arch.guest_fpu.xfd_err)
10531 wrmsrl(MSR_IA32_XFD_ERR, 0);
10532
d7a08882
SC
10533 /*
10534 * Consume any pending interrupts, including the possible source of
10535 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
10536 * An instruction is required after local_irq_enable() to fully unblock
10537 * interrupts on processors that implement an interrupt shadow, the
10538 * stat.exits increment will do nicely.
10539 */
db215756 10540 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
d7a08882 10541 local_irq_enable();
b6c7a5dc 10542 ++vcpu->stat.exits;
d7a08882
SC
10543 local_irq_disable();
10544 kvm_after_interrupt(vcpu);
b6c7a5dc 10545
16045714
WL
10546 /*
10547 * Wait until after servicing IRQs to account guest time so that any
10548 * ticks that occurred while running the guest are properly accounted
10549 * to the guest. Waiting until IRQs are enabled degrades the accuracy
10550 * of accounting via context tracking, but the loss of accuracy is
10551 * acceptable for all known use cases.
10552 */
b2d2af7e 10553 guest_timing_exit_irqoff();
16045714 10554
f2485b3e 10555 local_irq_enable();
b6c7a5dc
HB
10556 preempt_enable();
10557
2031f287 10558 kvm_vcpu_srcu_read_lock(vcpu);
3200f405 10559
b6c7a5dc
HB
10560 /*
10561 * Profile KVM exit RIPs:
10562 */
10563 if (unlikely(prof_on == KVM_PROFILING)) {
5fdbf976
MT
10564 unsigned long rip = kvm_rip_read(vcpu);
10565 profile_hit(KVM_PROFILING, (void *)rip);
b6c7a5dc
HB
10566 }
10567
cc578287
ZA
10568 if (unlikely(vcpu->arch.tsc_always_catchup))
10569 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
298101da 10570
5cfb1d5a
MT
10571 if (vcpu->arch.apic_attention)
10572 kvm_lapic_sync_from_vapic(vcpu);
b93463aa 10573
b3646477 10574 r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
d905c069
MT
10575 return r;
10576
10577cancel_injection:
8081ad06
SC
10578 if (req_immediate_exit)
10579 kvm_make_request(KVM_REQ_EVENT, vcpu);
b3646477 10580 static_call(kvm_x86_cancel_injection)(vcpu);
ae7a2a3f
MT
10581 if (unlikely(vcpu->arch.apic_attention))
10582 kvm_lapic_sync_from_vapic(vcpu);
d7690175
MT
10583out:
10584 return r;
10585}
b6c7a5dc 10586
8d25b7be 10587/* Called within kvm->srcu read side. */
2031f287 10588static inline int vcpu_block(struct kvm_vcpu *vcpu)
362c698f 10589{
98c25ead
SC
10590 bool hv_timer;
10591
c3e8abf0 10592 if (!kvm_arch_vcpu_runnable(vcpu)) {
98c25ead
SC
10593 /*
10594 * Switch to the software timer before halt-polling/blocking as
10595 * the guest's timer may be a break event for the vCPU, and the
10596 * hypervisor timer runs only when the CPU is in guest mode.
10597 * Switch before halt-polling so that KVM recognizes an expired
10598 * timer before blocking.
10599 */
10600 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
10601 if (hv_timer)
10602 kvm_lapic_switch_to_sw_timer(vcpu);
10603
2031f287 10604 kvm_vcpu_srcu_read_unlock(vcpu);
cdafece4
SC
10605 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10606 kvm_vcpu_halt(vcpu);
10607 else
10608 kvm_vcpu_block(vcpu);
2031f287 10609 kvm_vcpu_srcu_read_lock(vcpu);
bf9f6ac8 10610
98c25ead
SC
10611 if (hv_timer)
10612 kvm_lapic_switch_to_hv_timer(vcpu);
10613
599275c0
PB
10614 /*
10615 * If the vCPU is not runnable, a signal or another host event
10616 * of some kind is pending; service it without changing the
10617 * vCPU's activity state.
10618 */
10619 if (!kvm_arch_vcpu_runnable(vcpu))
9c8fd1ba
PB
10620 return 1;
10621 }
362c698f 10622
26844fee
PB
10623 /*
10624 * Evaluate nested events before exiting the halted state. This allows
10625 * the halt state to be recorded properly in the VMCS12's activity
10626 * state field (AMD does not have a similar field and a VM-Exit always
10627 * causes a spurious wakeup from HLT).
10628 */
10629 if (is_guest_mode(vcpu)) {
10630 if (kvm_check_nested_events(vcpu) < 0)
10631 return 0;
10632 }
10633
4fe09bcf
JM
10634 if (kvm_apic_accept_events(vcpu) < 0)
10635 return 0;
362c698f
PB
10636 switch(vcpu->arch.mp_state) {
10637 case KVM_MP_STATE_HALTED:
647daca2 10638 case KVM_MP_STATE_AP_RESET_HOLD:
362c698f
PB
10639 vcpu->arch.pv.pv_unhalted = false;
10640 vcpu->arch.mp_state =
10641 KVM_MP_STATE_RUNNABLE;
df561f66 10642 fallthrough;
362c698f
PB
10643 case KVM_MP_STATE_RUNNABLE:
10644 vcpu->arch.apf.halted = false;
10645 break;
10646 case KVM_MP_STATE_INIT_RECEIVED:
10647 break;
10648 default:
22c6a0ef
PB
10649 WARN_ON_ONCE(1);
10650 break;
362c698f
PB
10651 }
10652 return 1;
10653}
09cec754 10654
5d9bc648
PB
10655static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
10656{
10657 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
10658 !vcpu->arch.apf.halted);
10659}
10660
8d25b7be 10661/* Called within kvm->srcu read side. */
362c698f 10662static int vcpu_run(struct kvm_vcpu *vcpu)
d7690175
MT
10663{
10664 int r;
10665
c595ceee 10666 vcpu->arch.l1tf_flush_l1d = true;
d7690175 10667
362c698f 10668 for (;;) {
6cd88243
PB
10669 /*
10670 * If another guest vCPU requests a PV TLB flush in the middle
10671 * of instruction emulation, the rest of the emulation could
10672 * use a stale page translation. Assume that any code after
10673 * this point can start executing an instruction.
10674 */
10675 vcpu->arch.at_instruction_boundary = false;
58f800d5 10676 if (kvm_vcpu_running(vcpu)) {
851ba692 10677 r = vcpu_enter_guest(vcpu);
bf9f6ac8 10678 } else {
2031f287 10679 r = vcpu_block(vcpu);
bf9f6ac8
FW
10680 }
10681
09cec754
GN
10682 if (r <= 0)
10683 break;
10684
084071d5 10685 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
7caf9571
DW
10686 if (kvm_xen_has_pending_events(vcpu))
10687 kvm_xen_inject_pending_events(vcpu);
10688
09cec754
GN
10689 if (kvm_cpu_has_pending_timer(vcpu))
10690 kvm_inject_pending_timer_irqs(vcpu);
10691
782d422b
MG
10692 if (dm_request_for_irq_injection(vcpu) &&
10693 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
4ca7dd8c
PB
10694 r = 0;
10695 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
09cec754 10696 ++vcpu->stat.request_irq_exits;
362c698f 10697 break;
09cec754 10698 }
af585b92 10699
f3020b88 10700 if (__xfer_to_guest_mode_work_pending()) {
2031f287 10701 kvm_vcpu_srcu_read_unlock(vcpu);
72c3c0fe 10702 r = xfer_to_guest_mode_handle_work(vcpu);
2031f287 10703 kvm_vcpu_srcu_read_lock(vcpu);
72c3c0fe
TG
10704 if (r)
10705 return r;
d7690175 10706 }
b6c7a5dc
HB
10707 }
10708
b6c7a5dc
HB
10709 return r;
10710}
10711
716d51ab
GN
10712static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
10713{
2d089356 10714 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
716d51ab
GN
10715}
10716
10717static int complete_emulated_pio(struct kvm_vcpu *vcpu)
10718{
10719 BUG_ON(!vcpu->arch.pio.count);
10720
10721 return complete_emulated_io(vcpu);
10722}
10723
f78146b0
AK
10724/*
10725 * Implements the following, as a state machine:
10726 *
10727 * read:
10728 * for each fragment
87da7e66
XG
10729 * for each mmio piece in the fragment
10730 * write gpa, len
10731 * exit
10732 * copy data
f78146b0
AK
10733 * execute insn
10734 *
10735 * write:
10736 * for each fragment
87da7e66
XG
10737 * for each mmio piece in the fragment
10738 * write gpa, len
10739 * copy data
10740 * exit
f78146b0 10741 */
716d51ab 10742static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
5287f194
AK
10743{
10744 struct kvm_run *run = vcpu->run;
f78146b0 10745 struct kvm_mmio_fragment *frag;
87da7e66 10746 unsigned len;
5287f194 10747
716d51ab 10748 BUG_ON(!vcpu->mmio_needed);
5287f194 10749
716d51ab 10750 /* Complete previous fragment */
87da7e66
XG
10751 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
10752 len = min(8u, frag->len);
716d51ab 10753 if (!vcpu->mmio_is_write)
87da7e66
XG
10754 memcpy(frag->data, run->mmio.data, len);
10755
10756 if (frag->len <= 8) {
10757 /* Switch to the next fragment. */
10758 frag++;
10759 vcpu->mmio_cur_fragment++;
10760 } else {
10761 /* Go forward to the next mmio piece. */
10762 frag->data += len;
10763 frag->gpa += len;
10764 frag->len -= len;
10765 }
10766
a08d3b3b 10767 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
716d51ab 10768 vcpu->mmio_needed = 0;
0912c977
PB
10769
10770 /* FIXME: return into emulator if single-stepping. */
cef4dea0 10771 if (vcpu->mmio_is_write)
716d51ab
GN
10772 return 1;
10773 vcpu->mmio_read_completed = 1;
10774 return complete_emulated_io(vcpu);
10775 }
87da7e66 10776
716d51ab
GN
10777 run->exit_reason = KVM_EXIT_MMIO;
10778 run->mmio.phys_addr = frag->gpa;
10779 if (vcpu->mmio_is_write)
87da7e66
XG
10780 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
10781 run->mmio.len = min(8u, frag->len);
716d51ab
GN
10782 run->mmio.is_write = vcpu->mmio_is_write;
10783 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
10784 return 0;
5287f194
AK
10785}
10786
822f312d
SAS
10787/* Swap (qemu) user FPU context for the guest FPU context. */
10788static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
10789{
e27bc044 10790 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
d69c1382 10791 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
822f312d
SAS
10792 trace_kvm_fpu(1);
10793}
10794
10795/* When vcpu_run ends, restore user space FPU context. */
10796static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
10797{
d69c1382 10798 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
822f312d
SAS
10799 ++vcpu->stat.fpu_reload;
10800 trace_kvm_fpu(0);
10801}
10802
1b94f6f8 10803int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
b6c7a5dc 10804{
7709aba8 10805 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1b94f6f8 10806 struct kvm_run *kvm_run = vcpu->run;
b6c7a5dc 10807 int r;
b6c7a5dc 10808
accb757d 10809 vcpu_load(vcpu);
20b7035c 10810 kvm_sigset_activate(vcpu);
15aad3be 10811 kvm_run->flags = 0;
5663d8f9
PX
10812 kvm_load_guest_fpu(vcpu);
10813
2031f287 10814 kvm_vcpu_srcu_read_lock(vcpu);
a4535290 10815 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
2f173d26
JS
10816 if (kvm_run->immediate_exit) {
10817 r = -EINTR;
10818 goto out;
10819 }
98c25ead
SC
10820 /*
10821 * It should be impossible for the hypervisor timer to be in
10822 * use before KVM has ever run the vCPU.
10823 */
10824 WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
8d25b7be 10825
2031f287 10826 kvm_vcpu_srcu_read_unlock(vcpu);
c91d4497 10827 kvm_vcpu_block(vcpu);
2031f287 10828 kvm_vcpu_srcu_read_lock(vcpu);
8d25b7be 10829
4fe09bcf
JM
10830 if (kvm_apic_accept_events(vcpu) < 0) {
10831 r = 0;
10832 goto out;
10833 }
ac9f6dc0 10834 r = -EAGAIN;
a0595000
JS
10835 if (signal_pending(current)) {
10836 r = -EINTR;
1b94f6f8 10837 kvm_run->exit_reason = KVM_EXIT_INTR;
a0595000
JS
10838 ++vcpu->stat.signal_exits;
10839 }
ac9f6dc0 10840 goto out;
b6c7a5dc
HB
10841 }
10842
e489a4a6
SC
10843 if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
10844 (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
01643c51
KH
10845 r = -EINVAL;
10846 goto out;
10847 }
10848
1b94f6f8 10849 if (kvm_run->kvm_dirty_regs) {
01643c51
KH
10850 r = sync_regs(vcpu);
10851 if (r != 0)
10852 goto out;
10853 }
10854
b6c7a5dc 10855 /* re-sync apic's tpr */
35754c98 10856 if (!lapic_in_kernel(vcpu)) {
eea1cff9
AP
10857 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
10858 r = -EINVAL;
10859 goto out;
10860 }
10861 }
b6c7a5dc 10862
7709aba8
SC
10863 /*
10864 * If userspace set a pending exception and L2 is active, convert it to
10865 * a pending VM-Exit if L1 wants to intercept the exception.
10866 */
10867 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
10868 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
10869 ex->error_code)) {
10870 kvm_queue_exception_vmexit(vcpu, ex->vector,
10871 ex->has_error_code, ex->error_code,
10872 ex->has_payload, ex->payload);
10873 ex->injected = false;
10874 ex->pending = false;
10875 }
10876 vcpu->arch.exception_from_userspace = false;
10877
716d51ab
GN
10878 if (unlikely(vcpu->arch.complete_userspace_io)) {
10879 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
10880 vcpu->arch.complete_userspace_io = NULL;
10881 r = cui(vcpu);
10882 if (r <= 0)
5663d8f9 10883 goto out;
0bc27326
SC
10884 } else {
10885 WARN_ON_ONCE(vcpu->arch.pio.count);
10886 WARN_ON_ONCE(vcpu->mmio_needed);
10887 }
5287f194 10888
fc4fad79 10889 if (kvm_run->immediate_exit) {
460df4c1 10890 r = -EINTR;
fc4fad79
SC
10891 goto out;
10892 }
10893
10894 r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
10895 if (r <= 0)
10896 goto out;
10897
10898 r = vcpu_run(vcpu);
b6c7a5dc
HB
10899
10900out:
5663d8f9 10901 kvm_put_guest_fpu(vcpu);
1b94f6f8 10902 if (kvm_run->kvm_valid_regs)
01643c51 10903 store_regs(vcpu);
f1d86e46 10904 post_kvm_run_save(vcpu);
2031f287 10905 kvm_vcpu_srcu_read_unlock(vcpu);
b6c7a5dc 10906
8d25b7be 10907 kvm_sigset_deactivate(vcpu);
accb757d 10908 vcpu_put(vcpu);
b6c7a5dc
HB
10909 return r;
10910}
10911
01643c51 10912static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 10913{
7ae441ea
GN
10914 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
10915 /*
10916 * We are here if userspace calls get_regs() in the middle of
10917 * instruction emulation. Registers state needs to be copied
4a969980 10918 * back from emulation context to vcpu. Userspace shouldn't do
7ae441ea
GN
10919 * that usually, but some bad designed PV devices (vmware
10920 * backdoor interface) need this to work
10921 */
c9b8b07c 10922 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
7ae441ea
GN
10923 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10924 }
de3cd117
SC
10925 regs->rax = kvm_rax_read(vcpu);
10926 regs->rbx = kvm_rbx_read(vcpu);
10927 regs->rcx = kvm_rcx_read(vcpu);
10928 regs->rdx = kvm_rdx_read(vcpu);
10929 regs->rsi = kvm_rsi_read(vcpu);
10930 regs->rdi = kvm_rdi_read(vcpu);
e9c16c78 10931 regs->rsp = kvm_rsp_read(vcpu);
de3cd117 10932 regs->rbp = kvm_rbp_read(vcpu);
b6c7a5dc 10933#ifdef CONFIG_X86_64
de3cd117
SC
10934 regs->r8 = kvm_r8_read(vcpu);
10935 regs->r9 = kvm_r9_read(vcpu);
10936 regs->r10 = kvm_r10_read(vcpu);
10937 regs->r11 = kvm_r11_read(vcpu);
10938 regs->r12 = kvm_r12_read(vcpu);
10939 regs->r13 = kvm_r13_read(vcpu);
10940 regs->r14 = kvm_r14_read(vcpu);
10941 regs->r15 = kvm_r15_read(vcpu);
b6c7a5dc
HB
10942#endif
10943
5fdbf976 10944 regs->rip = kvm_rip_read(vcpu);
91586a3b 10945 regs->rflags = kvm_get_rflags(vcpu);
01643c51 10946}
b6c7a5dc 10947
01643c51
KH
10948int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10949{
10950 vcpu_load(vcpu);
10951 __get_regs(vcpu, regs);
1fc9b76b 10952 vcpu_put(vcpu);
b6c7a5dc
HB
10953 return 0;
10954}
10955
01643c51 10956static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
b6c7a5dc 10957{
7ae441ea
GN
10958 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
10959 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10960
de3cd117
SC
10961 kvm_rax_write(vcpu, regs->rax);
10962 kvm_rbx_write(vcpu, regs->rbx);
10963 kvm_rcx_write(vcpu, regs->rcx);
10964 kvm_rdx_write(vcpu, regs->rdx);
10965 kvm_rsi_write(vcpu, regs->rsi);
10966 kvm_rdi_write(vcpu, regs->rdi);
e9c16c78 10967 kvm_rsp_write(vcpu, regs->rsp);
de3cd117 10968 kvm_rbp_write(vcpu, regs->rbp);
b6c7a5dc 10969#ifdef CONFIG_X86_64
de3cd117
SC
10970 kvm_r8_write(vcpu, regs->r8);
10971 kvm_r9_write(vcpu, regs->r9);
10972 kvm_r10_write(vcpu, regs->r10);
10973 kvm_r11_write(vcpu, regs->r11);
10974 kvm_r12_write(vcpu, regs->r12);
10975 kvm_r13_write(vcpu, regs->r13);
10976 kvm_r14_write(vcpu, regs->r14);
10977 kvm_r15_write(vcpu, regs->r15);
b6c7a5dc
HB
10978#endif
10979
5fdbf976 10980 kvm_rip_write(vcpu, regs->rip);
d73235d1 10981 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
b6c7a5dc 10982
b4f14abd 10983 vcpu->arch.exception.pending = false;
7709aba8 10984 vcpu->arch.exception_vmexit.pending = false;
b4f14abd 10985
3842d135 10986 kvm_make_request(KVM_REQ_EVENT, vcpu);
01643c51 10987}
3842d135 10988
01643c51
KH
10989int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10990{
10991 vcpu_load(vcpu);
10992 __set_regs(vcpu, regs);
875656fe 10993 vcpu_put(vcpu);
b6c7a5dc
HB
10994 return 0;
10995}
10996
6dba9403 10997static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
b6c7a5dc 10998{
89a27f4d 10999 struct desc_ptr dt;
b6c7a5dc 11000
5265713a
TL
11001 if (vcpu->arch.guest_state_protected)
11002 goto skip_protected_regs;
11003
3e6e0aab
GT
11004 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11005 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11006 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11007 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11008 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11009 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 11010
3e6e0aab
GT
11011 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11012 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 11013
b3646477 11014 static_call(kvm_x86_get_idt)(vcpu, &dt);
89a27f4d
GN
11015 sregs->idt.limit = dt.size;
11016 sregs->idt.base = dt.address;
b3646477 11017 static_call(kvm_x86_get_gdt)(vcpu, &dt);
89a27f4d
GN
11018 sregs->gdt.limit = dt.size;
11019 sregs->gdt.base = dt.address;
b6c7a5dc 11020
ad312c7c 11021 sregs->cr2 = vcpu->arch.cr2;
9f8fe504 11022 sregs->cr3 = kvm_read_cr3(vcpu);
5265713a
TL
11023
11024skip_protected_regs:
11025 sregs->cr0 = kvm_read_cr0(vcpu);
fc78f519 11026 sregs->cr4 = kvm_read_cr4(vcpu);
2d3ad1f4 11027 sregs->cr8 = kvm_get_cr8(vcpu);
f6801dff 11028 sregs->efer = vcpu->arch.efer;
b6c7a5dc 11029 sregs->apic_base = kvm_get_apic_base(vcpu);
6dba9403 11030}
b6c7a5dc 11031
6dba9403
ML
11032static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11033{
11034 __get_sregs_common(vcpu, sregs);
11035
11036 if (vcpu->arch.guest_state_protected)
11037 return;
b6c7a5dc 11038
04140b41 11039 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
14d0bc1f
GN
11040 set_bit(vcpu->arch.interrupt.nr,
11041 (unsigned long *)sregs->interrupt_bitmap);
01643c51 11042}
16d7a191 11043
6dba9403
ML
11044static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11045{
11046 int i;
11047
11048 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11049
11050 if (vcpu->arch.guest_state_protected)
11051 return;
11052
11053 if (is_pae_paging(vcpu)) {
11054 for (i = 0 ; i < 4 ; i++)
11055 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11056 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11057 }
11058}
11059
01643c51
KH
11060int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11061 struct kvm_sregs *sregs)
11062{
11063 vcpu_load(vcpu);
11064 __get_sregs(vcpu, sregs);
bcdec41c 11065 vcpu_put(vcpu);
b6c7a5dc
HB
11066 return 0;
11067}
11068
62d9f0db
MT
11069int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11070 struct kvm_mp_state *mp_state)
11071{
4fe09bcf
JM
11072 int r;
11073
fd232561 11074 vcpu_load(vcpu);
f958bd23
SC
11075 if (kvm_mpx_supported())
11076 kvm_load_guest_fpu(vcpu);
fd232561 11077
4fe09bcf
JM
11078 r = kvm_apic_accept_events(vcpu);
11079 if (r < 0)
11080 goto out;
11081 r = 0;
11082
647daca2
TL
11083 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11084 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11085 vcpu->arch.pv.pv_unhalted)
6aef266c
SV
11086 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11087 else
11088 mp_state->mp_state = vcpu->arch.mp_state;
11089
4fe09bcf 11090out:
f958bd23
SC
11091 if (kvm_mpx_supported())
11092 kvm_put_guest_fpu(vcpu);
fd232561 11093 vcpu_put(vcpu);
4fe09bcf 11094 return r;
62d9f0db
MT
11095}
11096
11097int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11098 struct kvm_mp_state *mp_state)
11099{
e83dff5e
CD
11100 int ret = -EINVAL;
11101
11102 vcpu_load(vcpu);
11103
22c6a0ef
PB
11104 switch (mp_state->mp_state) {
11105 case KVM_MP_STATE_UNINITIALIZED:
11106 case KVM_MP_STATE_HALTED:
11107 case KVM_MP_STATE_AP_RESET_HOLD:
11108 case KVM_MP_STATE_INIT_RECEIVED:
11109 case KVM_MP_STATE_SIPI_RECEIVED:
11110 if (!lapic_in_kernel(vcpu))
11111 goto out;
11112 break;
11113
11114 case KVM_MP_STATE_RUNNABLE:
11115 break;
11116
11117 default:
e83dff5e 11118 goto out;
22c6a0ef 11119 }
66450a21 11120
27cbe7d6 11121 /*
1b7a1b78
SC
11122 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11123 * forcing the guest into INIT/SIPI if those events are supposed to be
11124 * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11125 * if an SMI is pending as well.
27cbe7d6 11126 */
1b7a1b78 11127 if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
28bf2888
DH
11128 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11129 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
e83dff5e 11130 goto out;
28bf2888 11131
66450a21
JK
11132 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11133 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
11134 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11135 } else
11136 vcpu->arch.mp_state = mp_state->mp_state;
3842d135 11137 kvm_make_request(KVM_REQ_EVENT, vcpu);
e83dff5e
CD
11138
11139 ret = 0;
11140out:
11141 vcpu_put(vcpu);
11142 return ret;
62d9f0db
MT
11143}
11144
7f3d35fd
KW
11145int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11146 int reason, bool has_error_code, u32 error_code)
b6c7a5dc 11147{
c9b8b07c 11148 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8ec4722d 11149 int ret;
e01c2426 11150
8ec4722d 11151 init_emulate_ctxt(vcpu);
c697518a 11152
7f3d35fd 11153 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9d74191a 11154 has_error_code, error_code);
1051778f
SC
11155 if (ret) {
11156 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11157 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11158 vcpu->run->internal.ndata = 0;
60fc3d02 11159 return 0;
1051778f 11160 }
37817f29 11161
9d74191a
TY
11162 kvm_rip_write(vcpu, ctxt->eip);
11163 kvm_set_rflags(vcpu, ctxt->eflags);
60fc3d02 11164 return 1;
37817f29
IE
11165}
11166EXPORT_SYMBOL_GPL(kvm_task_switch);
11167
ee69c92b 11168static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
f2981033 11169{
37b95951 11170 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
f2981033
LT
11171 /*
11172 * When EFER.LME and CR0.PG are set, the processor is in
11173 * 64-bit mode (though maybe in a 32-bit code segment).
11174 * CR4.PAE and EFER.LMA must be set.
11175 */
ee69c92b
SC
11176 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11177 return false;
ca29e145 11178 if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
c1c35cf7 11179 return false;
f2981033
LT
11180 } else {
11181 /*
11182 * Not in 64-bit mode: EFER.LMA is clear and the code
11183 * segment cannot be 64-bit.
11184 */
11185 if (sregs->efer & EFER_LMA || sregs->cs.l)
ee69c92b 11186 return false;
f2981033
LT
11187 }
11188
ee69c92b 11189 return kvm_is_valid_cr4(vcpu, sregs->cr4);
f2981033
LT
11190}
11191
6dba9403
ML
11192static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11193 int *mmu_reset_needed, bool update_pdptrs)
b6c7a5dc 11194{
58cb628d 11195 struct msr_data apic_base_msr;
6dba9403 11196 int idx;
89a27f4d 11197 struct desc_ptr dt;
b4ef9d4e 11198
ee69c92b 11199 if (!kvm_is_valid_sregs(vcpu, sregs))
6dba9403 11200 return -EINVAL;
f2981033 11201
d3802286
JM
11202 apic_base_msr.data = sregs->apic_base;
11203 apic_base_msr.host_initiated = true;
11204 if (kvm_set_apic_base(vcpu, &apic_base_msr))
6dba9403 11205 return -EINVAL;
6d1068b3 11206
5265713a 11207 if (vcpu->arch.guest_state_protected)
6dba9403 11208 return 0;
5265713a 11209
89a27f4d
GN
11210 dt.size = sregs->idt.limit;
11211 dt.address = sregs->idt.base;
b3646477 11212 static_call(kvm_x86_set_idt)(vcpu, &dt);
89a27f4d
GN
11213 dt.size = sregs->gdt.limit;
11214 dt.address = sregs->gdt.base;
b3646477 11215 static_call(kvm_x86_set_gdt)(vcpu, &dt);
b6c7a5dc 11216
ad312c7c 11217 vcpu->arch.cr2 = sregs->cr2;
6dba9403 11218 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
dc7e795e 11219 vcpu->arch.cr3 = sregs->cr3;
3883bc9d 11220 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
405329fc 11221 static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
b6c7a5dc 11222
2d3ad1f4 11223 kvm_set_cr8(vcpu, sregs->cr8);
b6c7a5dc 11224
6dba9403 11225 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
b3646477 11226 static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
b6c7a5dc 11227
6dba9403 11228 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
b3646477 11229 static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
d7306163 11230 vcpu->arch.cr0 = sregs->cr0;
b6c7a5dc 11231
6dba9403 11232 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
b3646477 11233 static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
63f42e02 11234
6dba9403
ML
11235 if (update_pdptrs) {
11236 idx = srcu_read_lock(&vcpu->kvm->srcu);
11237 if (is_pae_paging(vcpu)) {
2df4a5eb 11238 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
6dba9403
ML
11239 *mmu_reset_needed = 1;
11240 }
11241 srcu_read_unlock(&vcpu->kvm->srcu, idx);
7c93be44 11242 }
b6c7a5dc 11243
3e6e0aab
GT
11244 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11245 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11246 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11247 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11248 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11249 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dc 11250
3e6e0aab
GT
11251 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11252 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dc 11253
5f0269f5
ME
11254 update_cr8_intercept(vcpu);
11255
9c3e4aab 11256 /* Older userspace won't unhalt the vcpu on reset. */
c5af89b6 11257 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9c3e4aab 11258 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3eeb3288 11259 !is_protmode(vcpu))
9c3e4aab
MT
11260 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11261
6dba9403
ML
11262 return 0;
11263}
11264
11265static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11266{
11267 int pending_vec, max_bits;
11268 int mmu_reset_needed = 0;
11269 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
11270
11271 if (ret)
11272 return ret;
11273
11274 if (mmu_reset_needed)
11275 kvm_mmu_reset_context(vcpu);
11276
5265713a
TL
11277 max_bits = KVM_NR_INTERRUPTS;
11278 pending_vec = find_first_bit(
11279 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6dba9403 11280
5265713a
TL
11281 if (pending_vec < max_bits) {
11282 kvm_queue_interrupt(vcpu, pending_vec, false);
11283 pr_debug("Set back pending irq %d\n", pending_vec);
6dba9403 11284 kvm_make_request(KVM_REQ_EVENT, vcpu);
5265713a 11285 }
6dba9403
ML
11286 return 0;
11287}
5265713a 11288
6dba9403
ML
11289static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11290{
11291 int mmu_reset_needed = 0;
11292 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
11293 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
11294 !(sregs2->efer & EFER_LMA);
11295 int i, ret;
3842d135 11296
6dba9403
ML
11297 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
11298 return -EINVAL;
11299
11300 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
11301 return -EINVAL;
11302
11303 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
11304 &mmu_reset_needed, !valid_pdptrs);
11305 if (ret)
11306 return ret;
11307
11308 if (valid_pdptrs) {
11309 for (i = 0; i < 4 ; i++)
11310 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
11311
11312 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
11313 mmu_reset_needed = 1;
158a48ec 11314 vcpu->arch.pdptrs_from_userspace = true;
6dba9403
ML
11315 }
11316 if (mmu_reset_needed)
11317 kvm_mmu_reset_context(vcpu);
11318 return 0;
01643c51
KH
11319}
11320
11321int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
11322 struct kvm_sregs *sregs)
11323{
11324 int ret;
11325
11326 vcpu_load(vcpu);
11327 ret = __set_sregs(vcpu, sregs);
b4ef9d4e
CD
11328 vcpu_put(vcpu);
11329 return ret;
b6c7a5dc
HB
11330}
11331
cae72dcc
ML
11332static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
11333{
320af55a 11334 bool set = false;
cae72dcc 11335 struct kvm_vcpu *vcpu;
46808a4c 11336 unsigned long i;
cae72dcc 11337
0047fb33
SC
11338 if (!enable_apicv)
11339 return;
11340
cae72dcc
ML
11341 down_write(&kvm->arch.apicv_update_lock);
11342
11343 kvm_for_each_vcpu(i, vcpu, kvm) {
11344 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
320af55a 11345 set = true;
cae72dcc
ML
11346 break;
11347 }
11348 }
320af55a 11349 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
cae72dcc
ML
11350 up_write(&kvm->arch.apicv_update_lock);
11351}
11352
d0bfb940
JK
11353int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
11354 struct kvm_guest_debug *dbg)
b6c7a5dc 11355{
355be0b9 11356 unsigned long rflags;
ae675ef0 11357 int i, r;
b6c7a5dc 11358
8d4846b9
TL
11359 if (vcpu->arch.guest_state_protected)
11360 return -EINVAL;
11361
66b56562
CD
11362 vcpu_load(vcpu);
11363
4f926bf2
JK
11364 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
11365 r = -EBUSY;
7709aba8 11366 if (kvm_is_exception_pending(vcpu))
2122ff5e 11367 goto out;
4f926bf2
JK
11368 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
11369 kvm_queue_exception(vcpu, DB_VECTOR);
11370 else
11371 kvm_queue_exception(vcpu, BP_VECTOR);
11372 }
11373
91586a3b
JK
11374 /*
11375 * Read rflags as long as potentially injected trace flags are still
11376 * filtered out.
11377 */
11378 rflags = kvm_get_rflags(vcpu);
355be0b9
JK
11379
11380 vcpu->guest_debug = dbg->control;
11381 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
11382 vcpu->guest_debug = 0;
11383
11384 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
ae675ef0
JK
11385 for (i = 0; i < KVM_NR_DB_REGS; ++i)
11386 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
c8639010 11387 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
ae675ef0
JK
11388 } else {
11389 for (i = 0; i < KVM_NR_DB_REGS; i++)
11390 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
ae675ef0 11391 }
c8639010 11392 kvm_update_dr7(vcpu);
ae675ef0 11393
f92653ee 11394 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
e87e46d5 11395 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
94fe45da 11396
91586a3b
JK
11397 /*
11398 * Trigger an rflags update that will inject or remove the trace
11399 * flags.
11400 */
11401 kvm_set_rflags(vcpu, rflags);
b6c7a5dc 11402
b3646477 11403 static_call(kvm_x86_update_exception_bitmap)(vcpu);
b6c7a5dc 11404
cae72dcc
ML
11405 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
11406
4f926bf2 11407 r = 0;
d0bfb940 11408
2122ff5e 11409out:
66b56562 11410 vcpu_put(vcpu);
b6c7a5dc
HB
11411 return r;
11412}
11413
8b006791
ZX
11414/*
11415 * Translate a guest virtual address to a guest physical address.
11416 */
11417int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
11418 struct kvm_translation *tr)
11419{
11420 unsigned long vaddr = tr->linear_address;
11421 gpa_t gpa;
f656ce01 11422 int idx;
8b006791 11423
1da5b61d
CD
11424 vcpu_load(vcpu);
11425
f656ce01 11426 idx = srcu_read_lock(&vcpu->kvm->srcu);
1871c602 11427 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
f656ce01 11428 srcu_read_unlock(&vcpu->kvm->srcu, idx);
8b006791 11429 tr->physical_address = gpa;
6e1d2a3f 11430 tr->valid = gpa != INVALID_GPA;
8b006791
ZX
11431 tr->writeable = 1;
11432 tr->usermode = 0;
8b006791 11433
1da5b61d 11434 vcpu_put(vcpu);
8b006791
ZX
11435 return 0;
11436}
11437
d0752060
HB
11438int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11439{
1393123e 11440 struct fxregs_state *fxsave;
d0752060 11441
d69c1382 11442 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
ed02b213
TL
11443 return 0;
11444
1393123e 11445 vcpu_load(vcpu);
d0752060 11446
d69c1382 11447 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
d0752060
HB
11448 memcpy(fpu->fpr, fxsave->st_space, 128);
11449 fpu->fcw = fxsave->cwd;
11450 fpu->fsw = fxsave->swd;
11451 fpu->ftwx = fxsave->twd;
11452 fpu->last_opcode = fxsave->fop;
11453 fpu->last_ip = fxsave->rip;
11454 fpu->last_dp = fxsave->rdp;
0e96f31e 11455 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
d0752060 11456
1393123e 11457 vcpu_put(vcpu);
d0752060
HB
11458 return 0;
11459}
11460
11461int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11462{
6a96bc7f
CD
11463 struct fxregs_state *fxsave;
11464
d69c1382 11465 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
ed02b213
TL
11466 return 0;
11467
6a96bc7f
CD
11468 vcpu_load(vcpu);
11469
d69c1382 11470 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
d0752060 11471
d0752060
HB
11472 memcpy(fxsave->st_space, fpu->fpr, 128);
11473 fxsave->cwd = fpu->fcw;
11474 fxsave->swd = fpu->fsw;
11475 fxsave->twd = fpu->ftwx;
11476 fxsave->fop = fpu->last_opcode;
11477 fxsave->rip = fpu->last_ip;
11478 fxsave->rdp = fpu->last_dp;
0e96f31e 11479 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
d0752060 11480
6a96bc7f 11481 vcpu_put(vcpu);
d0752060
HB
11482 return 0;
11483}
11484
01643c51
KH
11485static void store_regs(struct kvm_vcpu *vcpu)
11486{
11487 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
11488
11489 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
11490 __get_regs(vcpu, &vcpu->run->s.regs.regs);
11491
11492 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
11493 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
11494
11495 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
11496 kvm_vcpu_ioctl_x86_get_vcpu_events(
11497 vcpu, &vcpu->run->s.regs.events);
11498}
11499
11500static int sync_regs(struct kvm_vcpu *vcpu)
11501{
01643c51
KH
11502 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
11503 __set_regs(vcpu, &vcpu->run->s.regs.regs);
11504 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
11505 }
11506 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
11507 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
11508 return -EINVAL;
11509 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
11510 }
11511 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
11512 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
11513 vcpu, &vcpu->run->s.regs.events))
11514 return -EINVAL;
11515 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
11516 }
11517
11518 return 0;
11519}
11520
897cc38e 11521int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
e9b11c17 11522{
1d5e740d 11523 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
897cc38e
SC
11524 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
11525 "guest TSC will not be reliable\n");
7f1ea208 11526
35875316
ZG
11527 if (!kvm->arch.max_vcpu_ids)
11528 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
11529
11530 if (id >= kvm->arch.max_vcpu_ids)
11531 return -EINVAL;
11532
d588bb9b 11533 return static_call(kvm_x86_vcpu_precreate)(kvm);
e9b11c17
ZX
11534}
11535
e529ef66 11536int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
e9b11c17 11537{
95a0d01e
SC
11538 struct page *page;
11539 int r;
c447e76b 11540
63f5a190 11541 vcpu->arch.last_vmentry_cpu = -1;
7117003f
SC
11542 vcpu->arch.regs_avail = ~0;
11543 vcpu->arch.regs_dirty = ~0;
63f5a190 11544
52491a38
ML
11545 kvm_gpc_init(&vcpu->arch.pv_time);
11546
95a0d01e
SC
11547 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
11548 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11549 else
11550 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
c447e76b 11551
95a0d01e
SC
11552 r = kvm_mmu_create(vcpu);
11553 if (r < 0)
11554 return r;
11555
11556 if (irqchip_in_kernel(vcpu->kvm)) {
95a0d01e
SC
11557 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
11558 if (r < 0)
11559 goto fail_mmu_destroy;
423ecfea
SC
11560
11561 /*
11562 * Defer evaluating inhibits until the vCPU is first run, as
11563 * this vCPU will not get notified of any changes until this
11564 * vCPU is visible to other vCPUs (marked online and added to
11565 * the set of vCPUs). Opportunistically mark APICv active as
11566 * VMX in particularly is highly unlikely to have inhibits.
11567 * Ignore the current per-VM APICv state so that vCPU creation
11568 * is guaranteed to run with a deterministic value, the request
11569 * will ensure the vCPU gets the correct state before VM-Entry.
11570 */
11571 if (enable_apicv) {
ce0a58f4 11572 vcpu->arch.apic->apicv_active = true;
423ecfea
SC
11573 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
11574 }
95a0d01e 11575 } else
6e4e3b4d 11576 static_branch_inc(&kvm_has_noapic_vcpu);
95a0d01e
SC
11577
11578 r = -ENOMEM;
11579
93bb59ca 11580 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
95a0d01e
SC
11581 if (!page)
11582 goto fail_free_lapic;
11583 vcpu->arch.pio_data = page_address(page);
11584
087acc4e 11585 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
95a0d01e 11586 GFP_KERNEL_ACCOUNT);
281b5278
JW
11587 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
11588 GFP_KERNEL_ACCOUNT);
11589 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
3c0ba05c 11590 goto fail_free_mce_banks;
95a0d01e
SC
11591 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
11592
11593 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
11594 GFP_KERNEL_ACCOUNT))
11595 goto fail_free_mce_banks;
11596
c9b8b07c
SC
11597 if (!alloc_emulate_ctxt(vcpu))
11598 goto free_wbinvd_dirty_mask;
11599
d69c1382 11600 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
95a0d01e 11601 pr_err("kvm: failed to allocate vcpu's fpu\n");
c9b8b07c 11602 goto free_emulate_ctxt;
95a0d01e
SC
11603 }
11604
95a0d01e 11605 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
a8ac864a 11606 vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
95a0d01e
SC
11607
11608 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
11609
11610 kvm_async_pf_hash_reset(vcpu);
6c6f82be
SC
11611
11612 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
95a0d01e
SC
11613 kvm_pmu_init(vcpu);
11614
11615 vcpu->arch.pending_external_vector = -1;
11616 vcpu->arch.preempted_in_kernel = false;
11617
3c86c0d3
VP
11618#if IS_ENABLED(CONFIG_HYPERV)
11619 vcpu->arch.hv_root_tdp = INVALID_PAGE;
11620#endif
11621
b3646477 11622 r = static_call(kvm_x86_vcpu_create)(vcpu);
95a0d01e
SC
11623 if (r)
11624 goto free_guest_fpu;
e9b11c17 11625
0cf9135b 11626 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
e53d88af 11627 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
942c2490 11628 kvm_xen_init_vcpu(vcpu);
19efffa2 11629 kvm_vcpu_mtrr_init(vcpu);
ec7660cc 11630 vcpu_load(vcpu);
ffbb61d0 11631 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
d28bc9dd 11632 kvm_vcpu_reset(vcpu, false);
c9060662 11633 kvm_init_mmu(vcpu);
e9b11c17 11634 vcpu_put(vcpu);
ec7660cc 11635 return 0;
95a0d01e
SC
11636
11637free_guest_fpu:
d69c1382 11638 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
c9b8b07c
SC
11639free_emulate_ctxt:
11640 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
95a0d01e
SC
11641free_wbinvd_dirty_mask:
11642 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11643fail_free_mce_banks:
11644 kfree(vcpu->arch.mce_banks);
281b5278 11645 kfree(vcpu->arch.mci_ctl2_banks);
95a0d01e
SC
11646 free_page((unsigned long)vcpu->arch.pio_data);
11647fail_free_lapic:
11648 kvm_free_lapic(vcpu);
11649fail_mmu_destroy:
11650 kvm_mmu_destroy(vcpu);
11651 return r;
e9b11c17
ZX
11652}
11653
31928aa5 11654void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
42897d86 11655{
332967a3 11656 struct kvm *kvm = vcpu->kvm;
42897d86 11657
ec7660cc 11658 if (mutex_lock_killable(&vcpu->mutex))
31928aa5 11659 return;
ec7660cc 11660 vcpu_load(vcpu);
0c899c25 11661 kvm_synchronize_tsc(vcpu, 0);
42897d86 11662 vcpu_put(vcpu);
2d5ba19b
MT
11663
11664 /* poll control enabled by default */
11665 vcpu->arch.msr_kvm_poll_control = 1;
11666
ec7660cc 11667 mutex_unlock(&vcpu->mutex);
42897d86 11668
b34de572
WL
11669 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
11670 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
11671 KVMCLOCK_SYNC_PERIOD);
42897d86
MT
11672}
11673
d40ccc62 11674void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
e9b11c17 11675{
95a0d01e 11676 int idx;
344d9588 11677
50b143e1 11678 kvmclock_reset(vcpu);
e9b11c17 11679
b3646477 11680 static_call(kvm_x86_vcpu_free)(vcpu);
50b143e1 11681
c9b8b07c 11682 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
50b143e1 11683 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
d69c1382 11684 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
95a0d01e 11685
a795cd43 11686 kvm_xen_destroy_vcpu(vcpu);
95a0d01e
SC
11687 kvm_hv_vcpu_uninit(vcpu);
11688 kvm_pmu_destroy(vcpu);
11689 kfree(vcpu->arch.mce_banks);
281b5278 11690 kfree(vcpu->arch.mci_ctl2_banks);
95a0d01e
SC
11691 kvm_free_lapic(vcpu);
11692 idx = srcu_read_lock(&vcpu->kvm->srcu);
11693 kvm_mmu_destroy(vcpu);
11694 srcu_read_unlock(&vcpu->kvm->srcu, idx);
11695 free_page((unsigned long)vcpu->arch.pio_data);
255cbecf 11696 kvfree(vcpu->arch.cpuid_entries);
95a0d01e 11697 if (!lapic_in_kernel(vcpu))
6e4e3b4d 11698 static_branch_dec(&kvm_has_noapic_vcpu);
e9b11c17
ZX
11699}
11700
d28bc9dd 11701void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
e9b11c17 11702{
25b97845 11703 struct kvm_cpuid_entry2 *cpuid_0x1;
0aa18375 11704 unsigned long old_cr0 = kvm_read_cr0(vcpu);
4c72ab5a 11705 unsigned long new_cr0;
0aa18375 11706
62dd57dd
SC
11707 /*
11708 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
11709 * to handle side effects. RESET emulation hits those flows and relies
11710 * on emulated/virtualized registers, including those that are loaded
11711 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
11712 * to detect improper or missing initialization.
11713 */
11714 WARN_ON_ONCE(!init_event &&
11715 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
0aa18375 11716
ed129ec9
ML
11717 /*
11718 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
11719 * possible to INIT the vCPU while L2 is active. Force the vCPU back
11720 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
11721 * bits), i.e. virtualization is disabled.
11722 */
11723 if (is_guest_mode(vcpu))
11724 kvm_leave_nested(vcpu);
11725
b7e31be3
RK
11726 kvm_lapic_reset(vcpu, init_event);
11727
ed129ec9 11728 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
e69fab5d
PB
11729 vcpu->arch.hflags = 0;
11730
c43203ca 11731 vcpu->arch.smi_pending = 0;
52797bf9 11732 vcpu->arch.smi_count = 0;
7460fb4a
AK
11733 atomic_set(&vcpu->arch.nmi_queued, 0);
11734 vcpu->arch.nmi_pending = 0;
448fa4a9 11735 vcpu->arch.nmi_injected = false;
5f7552d4
NA
11736 kvm_clear_interrupt_queue(vcpu);
11737 kvm_clear_exception_queue(vcpu);
448fa4a9 11738
42dbaa5a 11739 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
ae561ede 11740 kvm_update_dr0123(vcpu);
9a3ecd5e 11741 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
42dbaa5a 11742 vcpu->arch.dr7 = DR7_FIXED_1;
c8639010 11743 kvm_update_dr7(vcpu);
42dbaa5a 11744
1119022c
NA
11745 vcpu->arch.cr2 = 0;
11746
3842d135 11747 kvm_make_request(KVM_REQ_EVENT, vcpu);
2635b5c4
VK
11748 vcpu->arch.apf.msr_en_val = 0;
11749 vcpu->arch.apf.msr_int_val = 0;
c9aaa895 11750 vcpu->arch.st.msr_val = 0;
3842d135 11751
12f9a48f
GC
11752 kvmclock_reset(vcpu);
11753
af585b92
GN
11754 kvm_clear_async_pf_completion_queue(vcpu);
11755 kvm_async_pf_hash_reset(vcpu);
11756 vcpu->arch.apf.halted = false;
3842d135 11757
d69c1382
TG
11758 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
11759 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
a554d207
WL
11760
11761 /*
a61353ac
SC
11762 * All paths that lead to INIT are required to load the guest's
11763 * FPU state (because most paths are buried in KVM_RUN).
a554d207 11764 */
f775b13e
RR
11765 if (init_event)
11766 kvm_put_guest_fpu(vcpu);
087df48c
TG
11767
11768 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
11769 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
11770
f775b13e
RR
11771 if (init_event)
11772 kvm_load_guest_fpu(vcpu);
a554d207
WL
11773 }
11774
64d60670 11775 if (!init_event) {
d28bc9dd 11776 kvm_pmu_reset(vcpu);
64d60670 11777 vcpu->arch.smbase = 0x30000;
db2336a8 11778
db2336a8 11779 vcpu->arch.msr_misc_features_enables = 0;
9fc22296
SC
11780 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
11781 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
a554d207 11782
05a9e065
LX
11783 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
11784 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
64d60670 11785 }
f5132b01 11786
ff8828c8 11787 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
66f7b72e 11788 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
ff8828c8 11789 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
66f7b72e 11790
49d8665c
SC
11791 /*
11792 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
11793 * if no CPUID match is found. Note, it's impossible to get a match at
11794 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
25b97845
SC
11795 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
11796 * on RESET. But, go through the motions in case that's ever remedied.
49d8665c 11797 */
277ad7d5 11798 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
25b97845 11799 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
49d8665c 11800
b3646477 11801 static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
0aa18375 11802
f39e805e
SC
11803 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
11804 kvm_rip_write(vcpu, 0xfff0);
11805
03a6e840
SC
11806 vcpu->arch.cr3 = 0;
11807 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11808
4c72ab5a
SC
11809 /*
11810 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
11811 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
11812 * (or qualify) that with a footnote stating that CD/NW are preserved.
11813 */
11814 new_cr0 = X86_CR0_ET;
11815 if (init_event)
11816 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
11817 else
11818 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
11819
11820 static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
f39e805e
SC
11821 static_call(kvm_x86_set_cr4)(vcpu, 0);
11822 static_call(kvm_x86_set_efer)(vcpu, 0);
11823 static_call(kvm_x86_update_exception_bitmap)(vcpu);
11824
0aa18375 11825 /*
b5f61c03
PB
11826 * On the standard CR0/CR4/EFER modification paths, there are several
11827 * complex conditions determining whether the MMU has to be reset and/or
11828 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
11829 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
11830 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
11831 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
0aa18375 11832 */
b5f61c03
PB
11833 if (old_cr0 & X86_CR0_PG) {
11834 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
0aa18375 11835 kvm_mmu_reset_context(vcpu);
b5f61c03 11836 }
df37ed38
SC
11837
11838 /*
11839 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
11840 * APM states the TLBs are untouched by INIT, but it also states that
11841 * the TLBs are flushed on "External initialization of the processor."
11842 * Flush the guest TLB regardless of vendor, there is no meaningful
11843 * benefit in relying on the guest to flush the TLB immediately after
11844 * INIT. A spurious TLB flush is benign and likely negligible from a
11845 * performance perspective.
11846 */
11847 if (init_event)
11848 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
e9b11c17 11849}
265e4353 11850EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
e9b11c17 11851
2b4a273b 11852void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
66450a21
JK
11853{
11854 struct kvm_segment cs;
11855
11856 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
11857 cs.selector = vector << 8;
11858 cs.base = vector << 12;
11859 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
11860 kvm_rip_write(vcpu, 0);
e9b11c17 11861}
647daca2 11862EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
e9b11c17 11863
13a34e06 11864int kvm_arch_hardware_enable(void)
e9b11c17 11865{
ca84d1a2
ZA
11866 struct kvm *kvm;
11867 struct kvm_vcpu *vcpu;
46808a4c 11868 unsigned long i;
0dd6a6ed
ZA
11869 int ret;
11870 u64 local_tsc;
11871 u64 max_tsc = 0;
11872 bool stable, backwards_tsc = false;
18863bdd 11873
7e34fbd0 11874 kvm_user_return_msr_cpu_online();
b3646477 11875 ret = static_call(kvm_x86_hardware_enable)();
0dd6a6ed
ZA
11876 if (ret != 0)
11877 return ret;
11878
4ea1636b 11879 local_tsc = rdtsc();
b0c39dc6 11880 stable = !kvm_check_tsc_unstable();
0dd6a6ed
ZA
11881 list_for_each_entry(kvm, &vm_list, vm_list) {
11882 kvm_for_each_vcpu(i, vcpu, kvm) {
11883 if (!stable && vcpu->cpu == smp_processor_id())
105b21bb 11884 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
11885 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
11886 backwards_tsc = true;
11887 if (vcpu->arch.last_host_tsc > max_tsc)
11888 max_tsc = vcpu->arch.last_host_tsc;
11889 }
11890 }
11891 }
11892
11893 /*
11894 * Sometimes, even reliable TSCs go backwards. This happens on
11895 * platforms that reset TSC during suspend or hibernate actions, but
11896 * maintain synchronization. We must compensate. Fortunately, we can
11897 * detect that condition here, which happens early in CPU bringup,
11898 * before any KVM threads can be running. Unfortunately, we can't
11899 * bring the TSCs fully up to date with real time, as we aren't yet far
11900 * enough into CPU bringup that we know how much real time has actually
9285ec4c 11901 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
0dd6a6ed
ZA
11902 * variables that haven't been updated yet.
11903 *
11904 * So we simply find the maximum observed TSC above, then record the
11905 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
11906 * the adjustment will be applied. Note that we accumulate
11907 * adjustments, in case multiple suspend cycles happen before some VCPU
11908 * gets a chance to run again. In the event that no KVM threads get a
11909 * chance to run, we will miss the entire elapsed period, as we'll have
11910 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
11911 * loose cycle time. This isn't too big a deal, since the loss will be
11912 * uniform across all VCPUs (not to mention the scenario is extremely
11913 * unlikely). It is possible that a second hibernate recovery happens
11914 * much faster than a first, causing the observed TSC here to be
11915 * smaller; this would require additional padding adjustment, which is
11916 * why we set last_host_tsc to the local tsc observed here.
11917 *
11918 * N.B. - this code below runs only on platforms with reliable TSC,
11919 * as that is the only way backwards_tsc is set above. Also note
11920 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
11921 * have the same delta_cyc adjustment applied if backwards_tsc
11922 * is detected. Note further, this adjustment is only done once,
11923 * as we reset last_host_tsc on all VCPUs to stop this from being
11924 * called multiple times (one for each physical CPU bringup).
11925 *
4a969980 11926 * Platforms with unreliable TSCs don't have to deal with this, they
0dd6a6ed
ZA
11927 * will be compensated by the logic in vcpu_load, which sets the TSC to
11928 * catchup mode. This will catchup all VCPUs to real time, but cannot
11929 * guarantee that they stay in perfect synchronization.
11930 */
11931 if (backwards_tsc) {
11932 u64 delta_cyc = max_tsc - local_tsc;
11933 list_for_each_entry(kvm, &vm_list, vm_list) {
a826faf1 11934 kvm->arch.backwards_tsc_observed = true;
0dd6a6ed
ZA
11935 kvm_for_each_vcpu(i, vcpu, kvm) {
11936 vcpu->arch.tsc_offset_adjustment += delta_cyc;
11937 vcpu->arch.last_host_tsc = local_tsc;
105b21bb 11938 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
0dd6a6ed
ZA
11939 }
11940
11941 /*
11942 * We have to disable TSC offset matching.. if you were
11943 * booting a VM while issuing an S4 host suspend....
11944 * you may have some problem. Solving this issue is
11945 * left as an exercise to the reader.
11946 */
11947 kvm->arch.last_tsc_nsec = 0;
11948 kvm->arch.last_tsc_write = 0;
11949 }
11950
11951 }
11952 return 0;
e9b11c17
ZX
11953}
11954
13a34e06 11955void kvm_arch_hardware_disable(void)
e9b11c17 11956{
b3646477 11957 static_call(kvm_x86_hardware_disable)();
13a34e06 11958 drop_user_return_notifiers();
e9b11c17
ZX
11959}
11960
fdc298da
LX
11961static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
11962{
11963 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
11964
11965#define __KVM_X86_OP(func) \
11966 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
11967#define KVM_X86_OP(func) \
11968 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
11969#define KVM_X86_OP_OPTIONAL __KVM_X86_OP
11970#define KVM_X86_OP_OPTIONAL_RET0(func) \
11971 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
11972 (void *)__static_call_return0);
11973#include <asm/kvm-x86-ops.h>
11974#undef __KVM_X86_OP
8f969c0c 11975
34886e79 11976 kvm_pmu_ops_update(ops->pmu_ops);
fdc298da
LX
11977}
11978
b9904085 11979int kvm_arch_hardware_setup(void *opaque)
e9b11c17 11980{
d008dfdb 11981 struct kvm_x86_init_ops *ops = opaque;
9e9c3fe4
NA
11982 int r;
11983
91661989
SC
11984 rdmsrl_safe(MSR_EFER, &host_efer);
11985
408e9a31
PB
11986 if (boot_cpu_has(X86_FEATURE_XSAVES))
11987 rdmsrl(MSR_IA32_XSS, host_xss);
11988
968635ab
LX
11989 kvm_init_pmu_capability();
11990
d008dfdb 11991 r = ops->hardware_setup();
9e9c3fe4
NA
11992 if (r != 0)
11993 return r;
11994
fdc298da 11995 kvm_ops_update(ops);
69c6f69a 11996
33271a9e 11997 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
5c7df80e 11998
408e9a31 11999 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
938c8745 12000 kvm_caps.supported_xss = 0;
408e9a31 12001
139f7425
PB
12002#define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
12003 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
12004#undef __kvm_cpu_cap_has
b11306b5 12005
938c8745 12006 if (kvm_caps.has_tsc_control) {
35181e86
HZ
12007 /*
12008 * Make sure the user can only configure tsc_khz values that
12009 * fit into a signed integer.
273ba457 12010 * A min value is not calculated because it will always
35181e86
HZ
12011 * be 1 on all machines.
12012 */
12013 u64 max = min(0x7fffffffULL,
938c8745
SC
12014 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
12015 kvm_caps.max_guest_tsc_khz = max;
35181e86 12016 }
938c8745 12017 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9e9c3fe4
NA
12018 kvm_init_msr_list();
12019 return 0;
e9b11c17
ZX
12020}
12021
12022void kvm_arch_hardware_unsetup(void)
12023{
e1bfc245 12024 kvm_unregister_perf_callbacks();
5c7df80e 12025
b3646477 12026 static_call(kvm_x86_hardware_unsetup)();
e9b11c17
ZX
12027}
12028
b9904085 12029int kvm_arch_check_processor_compat(void *opaque)
e9b11c17 12030{
f1cdecf5 12031 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
d008dfdb 12032 struct kvm_x86_init_ops *ops = opaque;
f1cdecf5
SC
12033
12034 WARN_ON(!irqs_disabled());
12035
139f7425
PB
12036 if (__cr4_reserved_bits(cpu_has, c) !=
12037 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
f1cdecf5
SC
12038 return -EIO;
12039
d008dfdb 12040 return ops->check_processor_compatibility();
d71ba788
PB
12041}
12042
12043bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12044{
12045 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12046}
12047EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
12048
12049bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12050{
12051 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
e9b11c17
ZX
12052}
12053
6e4e3b4d
CL
12054__read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
12055EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
54e9818f 12056
e790d9ef
RK
12057void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
12058{
b35e5548
LX
12059 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
12060
c595ceee 12061 vcpu->arch.l1tf_flush_l1d = true;
b35e5548
LX
12062 if (pmu->version && unlikely(pmu->event_count)) {
12063 pmu->need_cleanup = true;
12064 kvm_make_request(KVM_REQ_PMU, vcpu);
12065 }
b3646477 12066 static_call(kvm_x86_sched_in)(vcpu, cpu);
e790d9ef
RK
12067}
12068
562b6b08
SC
12069void kvm_arch_free_vm(struct kvm *kvm)
12070{
05f04ae4 12071 kfree(to_kvm_hv(kvm)->hv_pa_pg);
78b497f2 12072 __kvm_arch_free_vm(kvm);
e790d9ef
RK
12073}
12074
562b6b08 12075
e08b9637 12076int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
d19a9cd2 12077{
eb7511bf 12078 int ret;
869b4421 12079 unsigned long flags;
eb7511bf 12080
e08b9637
CO
12081 if (type)
12082 return -EINVAL;
12083
eb7511bf
HZ
12084 ret = kvm_page_track_init(kvm);
12085 if (ret)
a1a39128
PB
12086 goto out;
12087
12088 ret = kvm_mmu_init_vm(kvm);
12089 if (ret)
12090 goto out_page_track;
eb7511bf 12091
b24ede22
JS
12092 ret = static_call(kvm_x86_vm_init)(kvm);
12093 if (ret)
12094 goto out_uninit_mmu;
12095
6ef768fa 12096 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
4d5c5d0f 12097 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
e0f0bbc5 12098 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
d19a9cd2 12099
5550af4d
SY
12100 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12101 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7a84428a
AW
12102 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12103 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12104 &kvm->arch.irq_sources_bitmap);
5550af4d 12105
038f8c11 12106 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
1e08ec4a 12107 mutex_init(&kvm->arch.apic_map_lock);
869b4421 12108 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
8171cd68 12109 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
869b4421
PB
12110
12111 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
d828199e 12112 pvclock_update_vm_gtod_copy(kvm);
869b4421 12113 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
53f658b3 12114
741e511b 12115 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
6fbbde9a 12116 kvm->arch.guest_can_read_msr_platform_info = true;
ba7bb663 12117 kvm->arch.enable_pmu = enable_pmu;
6fbbde9a 12118
3c86c0d3
VP
12119#if IS_ENABLED(CONFIG_HYPERV)
12120 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12121 kvm->arch.hv_root_tdp = INVALID_PAGE;
12122#endif
12123
7e44e449 12124 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
332967a3 12125 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7e44e449 12126
4651fc56 12127 kvm_apicv_init(kvm);
cbc0236a 12128 kvm_hv_init_vm(kvm);
319afe68 12129 kvm_xen_init_vm(kvm);
0eb05bf2 12130
b24ede22 12131 return 0;
a1a39128 12132
b24ede22
JS
12133out_uninit_mmu:
12134 kvm_mmu_uninit_vm(kvm);
a1a39128
PB
12135out_page_track:
12136 kvm_page_track_cleanup(kvm);
12137out:
12138 return ret;
d19a9cd2
ZX
12139}
12140
1aa9b957
JS
12141int kvm_arch_post_init_vm(struct kvm *kvm)
12142{
12143 return kvm_mmu_post_init_vm(kvm);
12144}
12145
d19a9cd2
ZX
12146static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
12147{
ec7660cc 12148 vcpu_load(vcpu);
d19a9cd2
ZX
12149 kvm_mmu_unload(vcpu);
12150 vcpu_put(vcpu);
12151}
12152
6fcee03d 12153static void kvm_unload_vcpu_mmus(struct kvm *kvm)
d19a9cd2 12154{
46808a4c 12155 unsigned long i;
988a2cae 12156 struct kvm_vcpu *vcpu;
d19a9cd2 12157
af585b92
GN
12158 kvm_for_each_vcpu(i, vcpu, kvm) {
12159 kvm_clear_async_pf_completion_queue(vcpu);
988a2cae 12160 kvm_unload_vcpu_mmu(vcpu);
af585b92 12161 }
d19a9cd2
ZX
12162}
12163
ad8ba2cd
SY
12164void kvm_arch_sync_events(struct kvm *kvm)
12165{
332967a3 12166 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7e44e449 12167 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
aea924f6 12168 kvm_free_pit(kvm);
ad8ba2cd
SY
12169}
12170
ff5a983c
PX
12171/**
12172 * __x86_set_memory_region: Setup KVM internal memory slot
12173 *
12174 * @kvm: the kvm pointer to the VM.
12175 * @id: the slot ID to setup.
12176 * @gpa: the GPA to install the slot (unused when @size == 0).
12177 * @size: the size of the slot. Set to zero to uninstall a slot.
12178 *
12179 * This function helps to setup a KVM internal memory slot. Specify
12180 * @size > 0 to install a new slot, while @size == 0 to uninstall a
12181 * slot. The return code can be one of the following:
12182 *
12183 * HVA: on success (uninstall will return a bogus HVA)
12184 * -errno: on error
12185 *
12186 * The caller should always use IS_ERR() to check the return value
12187 * before use. Note, the KVM internal memory slots are guaranteed to
12188 * remain valid and unchanged until the VM is destroyed, i.e., the
12189 * GPA->HVA translation will not change. However, the HVA is a user
12190 * address, i.e. its accessibility is not guaranteed, and must be
12191 * accessed via __copy_{to,from}_user().
12192 */
12193void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12194 u32 size)
9da0e4d5
PB
12195{
12196 int i, r;
3f649ab7 12197 unsigned long hva, old_npages;
f0d648bd 12198 struct kvm_memslots *slots = kvm_memslots(kvm);
0577d1ab 12199 struct kvm_memory_slot *slot;
9da0e4d5
PB
12200
12201 /* Called with kvm->slots_lock held. */
1d8007bd 12202 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
ff5a983c 12203 return ERR_PTR_USR(-EINVAL);
9da0e4d5 12204
f0d648bd
PB
12205 slot = id_to_memslot(slots, id);
12206 if (size) {
0577d1ab 12207 if (slot && slot->npages)
ff5a983c 12208 return ERR_PTR_USR(-EEXIST);
f0d648bd
PB
12209
12210 /*
12211 * MAP_SHARED to prevent internal slot pages from being moved
12212 * by fork()/COW.
12213 */
12214 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12215 MAP_SHARED | MAP_ANONYMOUS, 0);
12216 if (IS_ERR((void *)hva))
ff5a983c 12217 return (void __user *)hva;
f0d648bd 12218 } else {
0577d1ab 12219 if (!slot || !slot->npages)
46914534 12220 return NULL;
f0d648bd 12221
0577d1ab 12222 old_npages = slot->npages;
b66f9bab 12223 hva = slot->userspace_addr;
f0d648bd
PB
12224 }
12225
9da0e4d5 12226 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1d8007bd 12227 struct kvm_userspace_memory_region m;
9da0e4d5 12228
1d8007bd
PB
12229 m.slot = id | (i << 16);
12230 m.flags = 0;
12231 m.guest_phys_addr = gpa;
f0d648bd 12232 m.userspace_addr = hva;
1d8007bd 12233 m.memory_size = size;
9da0e4d5
PB
12234 r = __kvm_set_memory_region(kvm, &m);
12235 if (r < 0)
ff5a983c 12236 return ERR_PTR_USR(r);
9da0e4d5
PB
12237 }
12238
103c763c 12239 if (!size)
0577d1ab 12240 vm_munmap(hva, old_npages * PAGE_SIZE);
f0d648bd 12241
ff5a983c 12242 return (void __user *)hva;
9da0e4d5
PB
12243}
12244EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12245
1aa9b957
JS
12246void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12247{
12248 kvm_mmu_pre_destroy_vm(kvm);
12249}
12250
d19a9cd2
ZX
12251void kvm_arch_destroy_vm(struct kvm *kvm)
12252{
27469d29
AH
12253 if (current->mm == kvm->mm) {
12254 /*
12255 * Free memory regions allocated on behalf of userspace,
f7081834 12256 * unless the memory map has changed due to process exit
27469d29
AH
12257 * or fd copying.
12258 */
6a3c623b
PX
12259 mutex_lock(&kvm->slots_lock);
12260 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12261 0, 0);
12262 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12263 0, 0);
12264 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12265 mutex_unlock(&kvm->slots_lock);
27469d29 12266 }
6fcee03d 12267 kvm_unload_vcpu_mmus(kvm);
b3646477 12268 static_call_cond(kvm_x86_vm_destroy)(kvm);
b318e8de 12269 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
c761159c
PX
12270 kvm_pic_destroy(kvm);
12271 kvm_ioapic_destroy(kvm);
6fcee03d 12272 kvm_destroy_vcpus(kvm);
af1bae54 12273 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
66bb8a06 12274 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13d268ca 12275 kvm_mmu_uninit_vm(kvm);
2beb6dad 12276 kvm_page_track_cleanup(kvm);
7d6bbebb 12277 kvm_xen_destroy_vm(kvm);
cbc0236a 12278 kvm_hv_destroy_vm(kvm);
d19a9cd2 12279}
0de10343 12280
c9b929b3 12281static void memslot_rmap_free(struct kvm_memory_slot *slot)
db3fe4eb
TY
12282{
12283 int i;
12284
d89cc617 12285 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
e96c81ee
SC
12286 kvfree(slot->arch.rmap[i]);
12287 slot->arch.rmap[i] = NULL;
c9b929b3
BG
12288 }
12289}
e96c81ee 12290
c9b929b3
BG
12291void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12292{
12293 int i;
12294
12295 memslot_rmap_free(slot);
d89cc617 12296
c9b929b3 12297 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
e96c81ee
SC
12298 kvfree(slot->arch.lpage_info[i - 1]);
12299 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb 12300 }
21ebbeda 12301
e96c81ee 12302 kvm_page_track_free_memslot(slot);
db3fe4eb
TY
12303}
12304
1e76a3ce 12305int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
56dd1019
BG
12306{
12307 const int sz = sizeof(*slot->arch.rmap[0]);
12308 int i;
12309
12310 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12311 int level = i + 1;
4139b197 12312 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
56dd1019 12313
fa13843d
PB
12314 if (slot->arch.rmap[i])
12315 continue;
d501f747 12316
37b2a651 12317 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
56dd1019
BG
12318 if (!slot->arch.rmap[i]) {
12319 memslot_rmap_free(slot);
12320 return -ENOMEM;
12321 }
12322 }
12323
12324 return 0;
12325}
12326
a2557408 12327static int kvm_alloc_memslot_metadata(struct kvm *kvm,
9d7d18ee 12328 struct kvm_memory_slot *slot)
db3fe4eb 12329{
9d7d18ee 12330 unsigned long npages = slot->npages;
56dd1019 12331 int i, r;
db3fe4eb 12332
edd4fa37
SC
12333 /*
12334 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
12335 * old arrays will be freed by __kvm_set_memory_region() if installing
12336 * the new memslot is successful.
12337 */
12338 memset(&slot->arch, 0, sizeof(slot->arch));
12339
e2209710 12340 if (kvm_memslots_have_rmaps(kvm)) {
a2557408
BG
12341 r = memslot_rmap_alloc(slot, npages);
12342 if (r)
12343 return r;
12344 }
56dd1019
BG
12345
12346 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
92f94f1e 12347 struct kvm_lpage_info *linfo;
db3fe4eb
TY
12348 unsigned long ugfn;
12349 int lpages;
d89cc617 12350 int level = i + 1;
db3fe4eb 12351
4139b197 12352 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
db3fe4eb 12353
37b2a651 12354 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
92f94f1e 12355 if (!linfo)
db3fe4eb
TY
12356 goto out_free;
12357
92f94f1e
XG
12358 slot->arch.lpage_info[i - 1] = linfo;
12359
db3fe4eb 12360 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 12361 linfo[0].disallow_lpage = 1;
db3fe4eb 12362 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
92f94f1e 12363 linfo[lpages - 1].disallow_lpage = 1;
db3fe4eb
TY
12364 ugfn = slot->userspace_addr >> PAGE_SHIFT;
12365 /*
12366 * If the gfn and userspace address are not aligned wrt each
600087b6 12367 * other, disable large page support for this slot.
db3fe4eb 12368 */
600087b6 12369 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
db3fe4eb
TY
12370 unsigned long j;
12371
12372 for (j = 0; j < lpages; ++j)
92f94f1e 12373 linfo[j].disallow_lpage = 1;
db3fe4eb
TY
12374 }
12375 }
12376
deae4a10 12377 if (kvm_page_track_create_memslot(kvm, slot, npages))
21ebbeda
XG
12378 goto out_free;
12379
db3fe4eb
TY
12380 return 0;
12381
12382out_free:
c9b929b3 12383 memslot_rmap_free(slot);
d89cc617 12384
c9b929b3 12385 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
548ef284 12386 kvfree(slot->arch.lpage_info[i - 1]);
d89cc617 12387 slot->arch.lpage_info[i - 1] = NULL;
db3fe4eb
TY
12388 }
12389 return -ENOMEM;
12390}
12391
15248258 12392void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
e59dbe09 12393{
91724814 12394 struct kvm_vcpu *vcpu;
46808a4c 12395 unsigned long i;
91724814 12396
e6dff7d1
TY
12397 /*
12398 * memslots->generation has been incremented.
12399 * mmio generation may have reached its maximum value.
12400 */
15248258 12401 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
91724814
BO
12402
12403 /* Force re-initialization of steal_time cache */
12404 kvm_for_each_vcpu(i, vcpu, kvm)
12405 kvm_vcpu_kick(vcpu);
e59dbe09
TY
12406}
12407
f7784b8e 12408int kvm_arch_prepare_memory_region(struct kvm *kvm,
537a17b3
SC
12409 const struct kvm_memory_slot *old,
12410 struct kvm_memory_slot *new,
12411 enum kvm_mr_change change)
0de10343 12412{
86931ff7
SC
12413 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
12414 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
12415 return -EINVAL;
12416
9d7d18ee 12417 return kvm_alloc_memslot_metadata(kvm, new);
86931ff7 12418 }
537a17b3
SC
12419
12420 if (change == KVM_MR_FLAGS_ONLY)
12421 memcpy(&new->arch, &old->arch, sizeof(old->arch));
12422 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
12423 return -EIO;
12424
f7784b8e
MT
12425 return 0;
12426}
12427
a85863c2
MS
12428
12429static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
12430{
12431 struct kvm_arch *ka = &kvm->arch;
12432
12433 if (!kvm_x86_ops.cpu_dirty_log_size)
12434 return;
12435
12436 if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
12437 (!enable && --ka->cpu_dirty_logging_count == 0))
12438 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
12439
12440 WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
12441}
12442
88178fd4 12443static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
3741679b 12444 struct kvm_memory_slot *old,
269e9552 12445 const struct kvm_memory_slot *new,
3741679b 12446 enum kvm_mr_change change)
88178fd4 12447{
77aedf26
SC
12448 u32 old_flags = old ? old->flags : 0;
12449 u32 new_flags = new ? new->flags : 0;
12450 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
a85863c2 12451
3741679b 12452 /*
a85863c2
MS
12453 * Update CPU dirty logging if dirty logging is being toggled. This
12454 * applies to all operations.
3741679b 12455 */
77aedf26 12456 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
a85863c2 12457 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
88178fd4
KH
12458
12459 /*
a85863c2 12460 * Nothing more to do for RO slots (which can't be dirtied and can't be
b6e16ae5 12461 * made writable) or CREATE/MOVE/DELETE of a slot.
88178fd4 12462 *
b6e16ae5 12463 * For a memslot with dirty logging disabled:
3741679b
AY
12464 * CREATE: No dirty mappings will already exist.
12465 * MOVE/DELETE: The old mappings will already have been cleaned up by
12466 * kvm_arch_flush_shadow_memslot()
b6e16ae5
SC
12467 *
12468 * For a memslot with dirty logging enabled:
12469 * CREATE: No shadow pages exist, thus nothing to write-protect
12470 * and no dirty bits to clear.
12471 * MOVE/DELETE: The old mappings will already have been cleaned up by
12472 * kvm_arch_flush_shadow_memslot().
3741679b 12473 */
77aedf26 12474 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
88178fd4 12475 return;
3741679b
AY
12476
12477 /*
52f46079
SC
12478 * READONLY and non-flags changes were filtered out above, and the only
12479 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
12480 * logging isn't being toggled on or off.
88178fd4 12481 */
77aedf26 12482 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
52f46079
SC
12483 return;
12484
b6e16ae5
SC
12485 if (!log_dirty_pages) {
12486 /*
12487 * Dirty logging tracks sptes in 4k granularity, meaning that
12488 * large sptes have to be split. If live migration succeeds,
12489 * the guest in the source machine will be destroyed and large
12490 * sptes will be created in the destination. However, if the
12491 * guest continues to run in the source machine (for example if
12492 * live migration fails), small sptes will remain around and
12493 * cause bad performance.
12494 *
12495 * Scan sptes if dirty logging has been stopped, dropping those
12496 * which can be collapsed into a single large-page spte. Later
12497 * page faults will create the large-page sptes.
12498 */
3741679b 12499 kvm_mmu_zap_collapsible_sptes(kvm, new);
b6e16ae5 12500 } else {
89212919
KZ
12501 /*
12502 * Initially-all-set does not require write protecting any page,
12503 * because they're all assumed to be dirty.
12504 */
12505 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
12506 return;
a1419f8b 12507
a3fe5dbd
DM
12508 if (READ_ONCE(eager_page_split))
12509 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
12510
a018eba5 12511 if (kvm_x86_ops.cpu_dirty_log_size) {
89212919
KZ
12512 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
12513 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
12514 } else {
12515 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
3c9bd400 12516 }
b64d740e
JS
12517
12518 /*
12519 * Unconditionally flush the TLBs after enabling dirty logging.
12520 * A flush is almost always going to be necessary (see below),
12521 * and unconditionally flushing allows the helpers to omit
12522 * the subtly complex checks when removing write access.
12523 *
12524 * Do the flush outside of mmu_lock to reduce the amount of
12525 * time mmu_lock is held. Flushing after dropping mmu_lock is
12526 * safe as KVM only needs to guarantee the slot is fully
12527 * write-protected before returning to userspace, i.e. before
12528 * userspace can consume the dirty status.
12529 *
12530 * Flushing outside of mmu_lock requires KVM to be careful when
12531 * making decisions based on writable status of an SPTE, e.g. a
12532 * !writable SPTE doesn't guarantee a CPU can't perform writes.
12533 *
12534 * Specifically, KVM also write-protects guest page tables to
12535 * monitor changes when using shadow paging, and must guarantee
12536 * no CPUs can write to those page before mmu_lock is dropped.
12537 * Because CPUs may have stale TLB entries at this point, a
12538 * !writable SPTE doesn't guarantee CPUs can't perform writes.
12539 *
12540 * KVM also allows making SPTES writable outside of mmu_lock,
12541 * e.g. to allow dirty logging without taking mmu_lock.
12542 *
12543 * To handle these scenarios, KVM uses a separate software-only
12544 * bit (MMU-writable) to track if a SPTE is !writable due to
12545 * a guest page table being write-protected (KVM clears the
12546 * MMU-writable flag when write-protecting for shadow paging).
12547 *
12548 * The use of MMU-writable is also the primary motivation for
12549 * the unconditional flush. Because KVM must guarantee that a
12550 * CPU doesn't contain stale, writable TLB entries for a
12551 * !MMU-writable SPTE, KVM must flush if it encounters any
12552 * MMU-writable SPTE regardless of whether the actual hardware
12553 * writable bit was set. I.e. KVM is almost guaranteed to need
12554 * to flush, while unconditionally flushing allows the "remove
12555 * write access" helpers to ignore MMU-writable entirely.
12556 *
12557 * See is_writable_pte() for more details (the case involving
12558 * access-tracked SPTEs is particularly relevant).
12559 */
12560 kvm_arch_flush_remote_tlbs_memslot(kvm, new);
88178fd4
KH
12561 }
12562}
12563
f7784b8e 12564void kvm_arch_commit_memory_region(struct kvm *kvm,
9d4c197c 12565 struct kvm_memory_slot *old,
f36f3f28 12566 const struct kvm_memory_slot *new,
8482644a 12567 enum kvm_mr_change change)
f7784b8e 12568{
e0c2b633 12569 if (!kvm->arch.n_requested_mmu_pages &&
f5756029
MS
12570 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
12571 unsigned long nr_mmu_pages;
12572
12573 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
12574 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
12575 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
12576 }
1c91cad4 12577
269e9552 12578 kvm_mmu_slot_apply_flags(kvm, old, new, change);
21198846
SC
12579
12580 /* Free the arrays associated with the old memslot. */
12581 if (change == KVM_MR_MOVE)
e96c81ee 12582 kvm_arch_free_memslot(kvm, old);
0de10343 12583}
1d737c8a 12584
2df72e9b 12585void kvm_arch_flush_shadow_all(struct kvm *kvm)
34d4cb8f 12586{
7390de1e 12587 kvm_mmu_zap_all(kvm);
34d4cb8f
MT
12588}
12589
2df72e9b
MT
12590void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12591 struct kvm_memory_slot *slot)
12592{
ae7cd873 12593 kvm_page_track_flush_slot(kvm, slot);
2df72e9b
MT
12594}
12595
e6c67d8c
LA
12596static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
12597{
12598 return (is_guest_mode(vcpu) &&
5be2226f 12599 static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
e6c67d8c
LA
12600}
12601
5d9bc648
PB
12602static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
12603{
12604 if (!list_empty_careful(&vcpu->async_pf.done))
12605 return true;
12606
bf7f9352
PB
12607 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
12608 kvm_apic_init_sipi_allowed(vcpu))
5d9bc648
PB
12609 return true;
12610
12611 if (vcpu->arch.pv.pv_unhalted)
12612 return true;
12613
7709aba8 12614 if (kvm_is_exception_pending(vcpu))
a5f01f8e
WL
12615 return true;
12616
47a66eed
Z
12617 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12618 (vcpu->arch.nmi_pending &&
b3646477 12619 static_call(kvm_x86_nmi_allowed)(vcpu, false)))
5d9bc648
PB
12620 return true;
12621
31e83e21 12622#ifdef CONFIG_KVM_SMM
47a66eed 12623 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
a9fa7cb6 12624 (vcpu->arch.smi_pending &&
b3646477 12625 static_call(kvm_x86_smi_allowed)(vcpu, false)))
73917739 12626 return true;
31e83e21 12627#endif
73917739 12628
5d9bc648 12629 if (kvm_arch_interrupt_allowed(vcpu) &&
e6c67d8c
LA
12630 (kvm_cpu_has_interrupt(vcpu) ||
12631 kvm_guest_apic_has_interrupt(vcpu)))
5d9bc648
PB
12632 return true;
12633
1f4b34f8
AS
12634 if (kvm_hv_has_stimer_pending(vcpu))
12635 return true;
12636
d2060bd4 12637 if (is_guest_mode(vcpu) &&
5b4ac1a1
PB
12638 kvm_x86_ops.nested_ops->has_events &&
12639 kvm_x86_ops.nested_ops->has_events(vcpu))
d2060bd4
SC
12640 return true;
12641
7caf9571
DW
12642 if (kvm_xen_has_pending_events(vcpu))
12643 return true;
12644
5d9bc648
PB
12645 return false;
12646}
12647
1d737c8a
ZX
12648int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
12649{
5d9bc648 12650 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
1d737c8a 12651}
5736199a 12652
10dbdf98 12653bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
17e433b5 12654{
ae801e13
SC
12655 if (kvm_vcpu_apicv_active(vcpu) &&
12656 static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
52acd22f
WL
12657 return true;
12658
12659 return false;
12660}
12661
17e433b5
WL
12662bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
12663{
12664 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
12665 return true;
12666
12667 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
cf7316d0 12668#ifdef CONFIG_KVM_SMM
17e433b5 12669 kvm_test_request(KVM_REQ_SMI, vcpu) ||
cf7316d0 12670#endif
17e433b5
WL
12671 kvm_test_request(KVM_REQ_EVENT, vcpu))
12672 return true;
12673
10dbdf98 12674 return kvm_arch_dy_has_pending_interrupt(vcpu);
17e433b5
WL
12675}
12676
199b5763
LM
12677bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
12678{
b86bb11e
WL
12679 if (vcpu->arch.guest_state_protected)
12680 return true;
12681
de63ad4c 12682 return vcpu->arch.preempted_in_kernel;
199b5763
LM
12683}
12684
e1bfc245
SC
12685unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
12686{
12687 return kvm_rip_read(vcpu);
12688}
12689
b6d33834 12690int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
5736199a 12691{
b6d33834 12692 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
5736199a 12693}
78646121
GN
12694
12695int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
12696{
b3646477 12697 return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
78646121 12698}
229456fc 12699
82b32774 12700unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
f92653ee 12701{
7ed9abfe
TL
12702 /* Can't read the RIP when guest state is protected, just return 0 */
12703 if (vcpu->arch.guest_state_protected)
12704 return 0;
12705
82b32774
NA
12706 if (is_64_bit_mode(vcpu))
12707 return kvm_rip_read(vcpu);
12708 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
12709 kvm_rip_read(vcpu));
12710}
12711EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
f92653ee 12712
82b32774
NA
12713bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
12714{
12715 return kvm_get_linear_rip(vcpu) == linear_rip;
f92653ee
JK
12716}
12717EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
12718
94fe45da
JK
12719unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
12720{
12721 unsigned long rflags;
12722
b3646477 12723 rflags = static_call(kvm_x86_get_rflags)(vcpu);
94fe45da 12724 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
c310bac5 12725 rflags &= ~X86_EFLAGS_TF;
94fe45da
JK
12726 return rflags;
12727}
12728EXPORT_SYMBOL_GPL(kvm_get_rflags);
12729
6addfc42 12730static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
94fe45da
JK
12731{
12732 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
f92653ee 12733 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
c310bac5 12734 rflags |= X86_EFLAGS_TF;
b3646477 12735 static_call(kvm_x86_set_rflags)(vcpu, rflags);
6addfc42
PB
12736}
12737
12738void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12739{
12740 __kvm_set_rflags(vcpu, rflags);
3842d135 12741 kvm_make_request(KVM_REQ_EVENT, vcpu);
94fe45da
JK
12742}
12743EXPORT_SYMBOL_GPL(kvm_set_rflags);
12744
af585b92
GN
12745static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
12746{
dd03bcaa
PX
12747 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
12748
af585b92
GN
12749 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
12750}
12751
12752static inline u32 kvm_async_pf_next_probe(u32 key)
12753{
dd03bcaa 12754 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
af585b92
GN
12755}
12756
12757static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12758{
12759 u32 key = kvm_async_pf_hash_fn(gfn);
12760
12761 while (vcpu->arch.apf.gfns[key] != ~0)
12762 key = kvm_async_pf_next_probe(key);
12763
12764 vcpu->arch.apf.gfns[key] = gfn;
12765}
12766
12767static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
12768{
12769 int i;
12770 u32 key = kvm_async_pf_hash_fn(gfn);
12771
dd03bcaa 12772 for (i = 0; i < ASYNC_PF_PER_VCPU &&
c7d28c24
XG
12773 (vcpu->arch.apf.gfns[key] != gfn &&
12774 vcpu->arch.apf.gfns[key] != ~0); i++)
af585b92
GN
12775 key = kvm_async_pf_next_probe(key);
12776
12777 return key;
12778}
12779
12780bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12781{
12782 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
12783}
12784
12785static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12786{
12787 u32 i, j, k;
12788
12789 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
0fd46044
PX
12790
12791 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
12792 return;
12793
af585b92
GN
12794 while (true) {
12795 vcpu->arch.apf.gfns[i] = ~0;
12796 do {
12797 j = kvm_async_pf_next_probe(j);
12798 if (vcpu->arch.apf.gfns[j] == ~0)
12799 return;
12800 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
12801 /*
12802 * k lies cyclically in ]i,j]
12803 * | i.k.j |
12804 * |....j i.k.| or |.k..j i...|
12805 */
12806 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
12807 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
12808 i = j;
12809 }
12810}
12811
68fd66f1 12812static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
7c90705b 12813{
68fd66f1
VK
12814 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
12815
12816 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
12817 sizeof(reason));
12818}
12819
12820static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
12821{
2635b5c4 12822 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
4e335d9e 12823
2635b5c4
VK
12824 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12825 &token, offset, sizeof(token));
12826}
12827
12828static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
12829{
12830 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12831 u32 val;
12832
12833 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12834 &val, offset, sizeof(val)))
12835 return false;
12836
12837 return !val;
7c90705b
GN
12838}
12839
1dfdb45e
PB
12840static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
12841{
57cb3bb0
PB
12842
12843 if (!kvm_pv_async_pf_enabled(vcpu))
1dfdb45e
PB
12844 return false;
12845
57cb3bb0
PB
12846 if (vcpu->arch.apf.send_user_only &&
12847 static_call(kvm_x86_get_cpl)(vcpu) == 0)
1dfdb45e
PB
12848 return false;
12849
57cb3bb0
PB
12850 if (is_guest_mode(vcpu)) {
12851 /*
12852 * L1 needs to opt into the special #PF vmexits that are
12853 * used to deliver async page faults.
12854 */
12855 return vcpu->arch.apf.delivery_as_pf_vmexit;
12856 } else {
12857 /*
12858 * Play it safe in case the guest temporarily disables paging.
12859 * The real mode IDT in particular is unlikely to have a #PF
12860 * exception setup.
12861 */
12862 return is_paging(vcpu);
12863 }
1dfdb45e
PB
12864}
12865
12866bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
12867{
12868 if (unlikely(!lapic_in_kernel(vcpu) ||
12869 kvm_event_needs_reinjection(vcpu) ||
7709aba8 12870 kvm_is_exception_pending(vcpu)))
1dfdb45e
PB
12871 return false;
12872
12873 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
12874 return false;
12875
12876 /*
12877 * If interrupts are off we cannot even use an artificial
12878 * halt state.
12879 */
c300ab9f 12880 return kvm_arch_interrupt_allowed(vcpu);
1dfdb45e
PB
12881}
12882
2a18b7e7 12883bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
af585b92
GN
12884 struct kvm_async_pf *work)
12885{
6389ee94
AK
12886 struct x86_exception fault;
12887
736c291c 12888 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
af585b92 12889 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7c90705b 12890
1dfdb45e 12891 if (kvm_can_deliver_async_pf(vcpu) &&
68fd66f1 12892 !apf_put_user_notpresent(vcpu)) {
6389ee94
AK
12893 fault.vector = PF_VECTOR;
12894 fault.error_code_valid = true;
12895 fault.error_code = 0;
12896 fault.nested_page_fault = false;
12897 fault.address = work->arch.token;
adfe20fb 12898 fault.async_page_fault = true;
6389ee94 12899 kvm_inject_page_fault(vcpu, &fault);
2a18b7e7 12900 return true;
1dfdb45e
PB
12901 } else {
12902 /*
12903 * It is not possible to deliver a paravirtualized asynchronous
12904 * page fault, but putting the guest in an artificial halt state
12905 * can be beneficial nevertheless: if an interrupt arrives, we
12906 * can deliver it timely and perhaps the guest will schedule
12907 * another process. When the instruction that triggered a page
12908 * fault is retried, hopefully the page will be ready in the host.
12909 */
12910 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
2a18b7e7 12911 return false;
7c90705b 12912 }
af585b92
GN
12913}
12914
12915void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
12916 struct kvm_async_pf *work)
12917{
2635b5c4
VK
12918 struct kvm_lapic_irq irq = {
12919 .delivery_mode = APIC_DM_FIXED,
12920 .vector = vcpu->arch.apf.vec
12921 };
6389ee94 12922
f2e10669 12923 if (work->wakeup_all)
7c90705b
GN
12924 work->arch.token = ~0; /* broadcast wakeup */
12925 else
12926 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
736c291c 12927 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
7c90705b 12928
2a18b7e7
VK
12929 if ((work->wakeup_all || work->notpresent_injected) &&
12930 kvm_pv_async_pf_enabled(vcpu) &&
557a961a
VK
12931 !apf_put_user_ready(vcpu, work->arch.token)) {
12932 vcpu->arch.apf.pageready_pending = true;
2635b5c4 12933 kvm_apic_set_irq(vcpu, &irq, NULL);
557a961a 12934 }
2635b5c4 12935
e6d53e3b 12936 vcpu->arch.apf.halted = false;
a4fa1635 12937 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7c90705b
GN
12938}
12939
557a961a
VK
12940void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
12941{
12942 kvm_make_request(KVM_REQ_APF_READY, vcpu);
12943 if (!vcpu->arch.apf.pageready_pending)
12944 kvm_vcpu_kick(vcpu);
12945}
12946
7c0ade6c 12947bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
7c90705b 12948{
2635b5c4 12949 if (!kvm_pv_async_pf_enabled(vcpu))
7c90705b
GN
12950 return true;
12951 else
2f15d027 12952 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
af585b92
GN
12953}
12954
5544eb9b
PB
12955void kvm_arch_start_assignment(struct kvm *kvm)
12956{
57ab8794 12957 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
e27bc044 12958 static_call_cond(kvm_x86_pi_start_assignment)(kvm);
5544eb9b
PB
12959}
12960EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
12961
12962void kvm_arch_end_assignment(struct kvm *kvm)
12963{
12964 atomic_dec(&kvm->arch.assigned_device_count);
12965}
12966EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
12967
742ab6df 12968bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
5544eb9b 12969{
742ab6df 12970 return arch_atomic_read(&kvm->arch.assigned_device_count);
5544eb9b
PB
12971}
12972EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
12973
e0f0bbc5
AW
12974void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
12975{
12976 atomic_inc(&kvm->arch.noncoherent_dma_count);
12977}
12978EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
12979
12980void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
12981{
12982 atomic_dec(&kvm->arch.noncoherent_dma_count);
12983}
12984EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
12985
12986bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
12987{
12988 return atomic_read(&kvm->arch.noncoherent_dma_count);
12989}
12990EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
12991
14717e20
AW
12992bool kvm_arch_has_irq_bypass(void)
12993{
92735b1b 12994 return true;
14717e20
AW
12995}
12996
87276880
FW
12997int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
12998 struct irq_bypass_producer *prod)
12999{
13000 struct kvm_kernel_irqfd *irqfd =
13001 container_of(cons, struct kvm_kernel_irqfd, consumer);
2edd9cb7 13002 int ret;
87276880 13003
14717e20 13004 irqfd->producer = prod;
2edd9cb7 13005 kvm_arch_start_assignment(irqfd->kvm);
e27bc044 13006 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
2edd9cb7
ZL
13007 prod->irq, irqfd->gsi, 1);
13008
13009 if (ret)
13010 kvm_arch_end_assignment(irqfd->kvm);
87276880 13011
2edd9cb7 13012 return ret;
87276880
FW
13013}
13014
13015void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13016 struct irq_bypass_producer *prod)
13017{
13018 int ret;
13019 struct kvm_kernel_irqfd *irqfd =
13020 container_of(cons, struct kvm_kernel_irqfd, consumer);
13021
87276880
FW
13022 WARN_ON(irqfd->producer != prod);
13023 irqfd->producer = NULL;
13024
13025 /*
13026 * When producer of consumer is unregistered, we change back to
13027 * remapped mode, so we can re-use the current implementation
bb3541f1 13028 * when the irq is masked/disabled or the consumer side (KVM
87276880
FW
13029 * int this case doesn't want to receive the interrupts.
13030 */
e27bc044 13031 ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
87276880
FW
13032 if (ret)
13033 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13034 " fails: %d\n", irqfd->consumer.token, ret);
2edd9cb7
ZL
13035
13036 kvm_arch_end_assignment(irqfd->kvm);
87276880
FW
13037}
13038
13039int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13040 uint32_t guest_irq, bool set)
13041{
e27bc044 13042 return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
87276880
FW
13043}
13044
515a0c79
LM
13045bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13046 struct kvm_kernel_irq_routing_entry *new)
13047{
13048 if (new->type != KVM_IRQ_ROUTING_MSI)
13049 return true;
13050
13051 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13052}
13053
52004014
FW
13054bool kvm_vector_hashing_enabled(void)
13055{
13056 return vector_hashing;
13057}
52004014 13058
2d5ba19b
MT
13059bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13060{
13061 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13062}
13063EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13064
841c2be0
ML
13065
13066int kvm_spec_ctrl_test_value(u64 value)
6441fa61 13067{
841c2be0
ML
13068 /*
13069 * test that setting IA32_SPEC_CTRL to given value
13070 * is allowed by the host processor
13071 */
6441fa61 13072
841c2be0
ML
13073 u64 saved_value;
13074 unsigned long flags;
13075 int ret = 0;
6441fa61 13076
841c2be0 13077 local_irq_save(flags);
6441fa61 13078
841c2be0
ML
13079 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13080 ret = 1;
13081 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
13082 ret = 1;
13083 else
13084 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
6441fa61 13085
841c2be0 13086 local_irq_restore(flags);
6441fa61 13087
841c2be0 13088 return ret;
6441fa61 13089}
841c2be0 13090EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
2d5ba19b 13091
89786147
MG
13092void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13093{
1f5a21ee 13094 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
89786147 13095 struct x86_exception fault;
5b22bbe7 13096 u64 access = error_code &
19cf4b7e 13097 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
89786147
MG
13098
13099 if (!(error_code & PFERR_PRESENT_MASK) ||
6e1d2a3f 13100 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
89786147
MG
13101 /*
13102 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13103 * tables probably do not match the TLB. Just proceed
13104 * with the error code that the processor gave.
13105 */
13106 fault.vector = PF_VECTOR;
13107 fault.error_code_valid = true;
13108 fault.error_code = error_code;
13109 fault.nested_page_fault = false;
13110 fault.address = gva;
2bc685e6 13111 fault.async_page_fault = false;
89786147
MG
13112 }
13113 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
6441fa61 13114}
89786147 13115EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
2d5ba19b 13116
3f3393b3
BM
13117/*
13118 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13119 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13120 * indicates whether exit to userspace is needed.
13121 */
13122int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13123 struct x86_exception *e)
13124{
13125 if (r == X86EMUL_PROPAGATE_FAULT) {
13126 kvm_inject_emulated_page_fault(vcpu, e);
13127 return 1;
13128 }
13129
13130 /*
13131 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13132 * while handling a VMX instruction KVM could've handled the request
13133 * correctly by exiting to userspace and performing I/O but there
13134 * doesn't seem to be a real use-case behind such requests, just return
13135 * KVM_EXIT_INTERNAL_ERROR for now.
13136 */
e615e355 13137 kvm_prepare_emulation_failure_exit(vcpu);
3f3393b3
BM
13138
13139 return 0;
13140}
13141EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13142
9715092f
BM
13143int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13144{
13145 bool pcid_enabled;
13146 struct x86_exception e;
9715092f
BM
13147 struct {
13148 u64 pcid;
13149 u64 gla;
13150 } operand;
13151 int r;
13152
13153 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13154 if (r != X86EMUL_CONTINUE)
13155 return kvm_handle_memory_failure(vcpu, r, &e);
13156
13157 if (operand.pcid >> 12 != 0) {
13158 kvm_inject_gp(vcpu, 0);
13159 return 1;
13160 }
13161
13162 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
13163
13164 switch (type) {
13165 case INVPCID_TYPE_INDIV_ADDR:
13166 if ((!pcid_enabled && (operand.pcid != 0)) ||
13167 is_noncanonical_address(operand.gla, vcpu)) {
13168 kvm_inject_gp(vcpu, 0);
13169 return 1;
13170 }
13171 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13172 return kvm_skip_emulated_instruction(vcpu);
13173
13174 case INVPCID_TYPE_SINGLE_CTXT:
13175 if (!pcid_enabled && (operand.pcid != 0)) {
13176 kvm_inject_gp(vcpu, 0);
13177 return 1;
13178 }
13179
21823fbd 13180 kvm_invalidate_pcid(vcpu, operand.pcid);
9715092f
BM
13181 return kvm_skip_emulated_instruction(vcpu);
13182
13183 case INVPCID_TYPE_ALL_NON_GLOBAL:
13184 /*
13185 * Currently, KVM doesn't mark global entries in the shadow
13186 * page tables, so a non-global flush just degenerates to a
13187 * global flush. If needed, we could optimize this later by
13188 * keeping track of global entries in shadow page tables.
13189 */
13190
13191 fallthrough;
13192 case INVPCID_TYPE_ALL_INCL_GLOBAL:
28f28d45 13193 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
9715092f
BM
13194 return kvm_skip_emulated_instruction(vcpu);
13195
13196 default:
796c83c5
VS
13197 kvm_inject_gp(vcpu, 0);
13198 return 1;
9715092f
BM
13199 }
13200}
13201EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13202
8f423a80
TL
13203static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13204{
13205 struct kvm_run *run = vcpu->run;
13206 struct kvm_mmio_fragment *frag;
13207 unsigned int len;
13208
13209 BUG_ON(!vcpu->mmio_needed);
13210
13211 /* Complete previous fragment */
13212 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13213 len = min(8u, frag->len);
13214 if (!vcpu->mmio_is_write)
13215 memcpy(frag->data, run->mmio.data, len);
13216
13217 if (frag->len <= 8) {
13218 /* Switch to the next fragment. */
13219 frag++;
13220 vcpu->mmio_cur_fragment++;
13221 } else {
13222 /* Go forward to the next mmio piece. */
13223 frag->data += len;
13224 frag->gpa += len;
13225 frag->len -= len;
13226 }
13227
13228 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13229 vcpu->mmio_needed = 0;
13230
13231 // VMG change, at this point, we're always done
13232 // RIP has already been advanced
13233 return 1;
13234 }
13235
13236 // More MMIO is needed
13237 run->mmio.phys_addr = frag->gpa;
13238 run->mmio.len = min(8u, frag->len);
13239 run->mmio.is_write = vcpu->mmio_is_write;
13240 if (run->mmio.is_write)
13241 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13242 run->exit_reason = KVM_EXIT_MMIO;
13243
13244 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13245
13246 return 0;
13247}
13248
13249int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13250 void *data)
13251{
13252 int handled;
13253 struct kvm_mmio_fragment *frag;
13254
13255 if (!data)
13256 return -EINVAL;
13257
13258 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13259 if (handled == bytes)
13260 return 1;
13261
13262 bytes -= handled;
13263 gpa += handled;
13264 data += handled;
13265
13266 /*TODO: Check if need to increment number of frags */
13267 frag = vcpu->mmio_fragments;
13268 vcpu->mmio_nr_fragments = 1;
13269 frag->len = bytes;
13270 frag->gpa = gpa;
13271 frag->data = data;
13272
13273 vcpu->mmio_needed = 1;
13274 vcpu->mmio_cur_fragment = 0;
13275
13276 vcpu->run->mmio.phys_addr = gpa;
13277 vcpu->run->mmio.len = min(8u, frag->len);
13278 vcpu->run->mmio.is_write = 1;
13279 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13280 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13281
13282 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13283
13284 return 0;
13285}
13286EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13287
13288int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13289 void *data)
13290{
13291 int handled;
13292 struct kvm_mmio_fragment *frag;
13293
13294 if (!data)
13295 return -EINVAL;
13296
13297 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13298 if (handled == bytes)
13299 return 1;
13300
13301 bytes -= handled;
13302 gpa += handled;
13303 data += handled;
13304
13305 /*TODO: Check if need to increment number of frags */
13306 frag = vcpu->mmio_fragments;
13307 vcpu->mmio_nr_fragments = 1;
13308 frag->len = bytes;
13309 frag->gpa = gpa;
13310 frag->data = data;
13311
13312 vcpu->mmio_needed = 1;
13313 vcpu->mmio_cur_fragment = 0;
13314
13315 vcpu->run->mmio.phys_addr = gpa;
13316 vcpu->run->mmio.len = min(8u, frag->len);
13317 vcpu->run->mmio.is_write = 0;
13318 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13319
13320 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13321
13322 return 0;
13323}
13324EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13325
db209369
PB
13326static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13327{
13328 vcpu->arch.sev_pio_count -= count;
13329 vcpu->arch.sev_pio_data += count * size;
13330}
13331
7ed9abfe 13332static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
95e16b47
PB
13333 unsigned int port);
13334
13335static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
7ed9abfe 13336{
95e16b47
PB
13337 int size = vcpu->arch.pio.size;
13338 int port = vcpu->arch.pio.port;
13339
13340 vcpu->arch.pio.count = 0;
13341 if (vcpu->arch.sev_pio_count)
13342 return kvm_sev_es_outs(vcpu, size, port);
13343 return 1;
13344}
13345
13346static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13347 unsigned int port)
13348{
13349 for (;;) {
13350 unsigned int count =
13351 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
13352 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
13353
13354 /* memcpy done already by emulator_pio_out. */
db209369 13355 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
13356 if (!ret)
13357 break;
7ed9abfe 13358
ea724ea4 13359 /* Emulation done by the kernel. */
95e16b47
PB
13360 if (!vcpu->arch.sev_pio_count)
13361 return 1;
ea724ea4 13362 }
7ed9abfe 13363
95e16b47 13364 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
7ed9abfe
TL
13365 return 0;
13366}
13367
95e16b47
PB
13368static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
13369 unsigned int port);
13370
4fa4b38d
PB
13371static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
13372{
0c05e10b 13373 unsigned count = vcpu->arch.pio.count;
95e16b47
PB
13374 int size = vcpu->arch.pio.size;
13375 int port = vcpu->arch.pio.port;
4fa4b38d 13376
0c05e10b 13377 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
db209369 13378 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
13379 if (vcpu->arch.sev_pio_count)
13380 return kvm_sev_es_ins(vcpu, size, port);
4fa4b38d
PB
13381 return 1;
13382}
13383
7ed9abfe 13384static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
95e16b47 13385 unsigned int port)
7ed9abfe 13386{
95e16b47
PB
13387 for (;;) {
13388 unsigned int count =
13389 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
f35cee4a 13390 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
95e16b47 13391 break;
7ed9abfe 13392
ea724ea4 13393 /* Emulation done by the kernel. */
db209369 13394 advance_sev_es_emulated_pio(vcpu, count, size);
95e16b47
PB
13395 if (!vcpu->arch.sev_pio_count)
13396 return 1;
7ed9abfe
TL
13397 }
13398
ea724ea4 13399 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
7ed9abfe
TL
13400 return 0;
13401}
13402
13403int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
13404 unsigned int port, void *data, unsigned int count,
13405 int in)
13406{
ea724ea4 13407 vcpu->arch.sev_pio_data = data;
95e16b47
PB
13408 vcpu->arch.sev_pio_count = count;
13409 return in ? kvm_sev_es_ins(vcpu, size, port)
13410 : kvm_sev_es_outs(vcpu, size, port);
7ed9abfe
TL
13411}
13412EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
13413
d95df951 13414EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
229456fc 13415EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
931c33b1 13416EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
229456fc
MT
13417EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
13418EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
13419EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
13420EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
89e54ec5 13421EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
d8cabddf 13422EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
17897f36 13423EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
236649de 13424EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
5497b955 13425EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
ec1ff790 13426EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
532a46b9 13427EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
2e554e8d 13428EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
489223ed 13429EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
4f75bcc3 13430EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
843e4330 13431EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
efc64404 13432EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
18f40c53
SS
13433EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
13434EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
ab56f8e6 13435EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
9f084f7c 13436EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
39b6b8c3 13437EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
8e819d75 13438EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
d523ab6b
TL
13439EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
13440EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
59e38b58
TL
13441EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
13442EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
1d0e8480
SC
13443
13444static int __init kvm_x86_init(void)
13445{
13446 kvm_mmu_x86_module_init();
13447 return 0;
13448}
13449module_init(kvm_x86_init);
13450
13451static void __exit kvm_x86_exit(void)
13452{
13453 /*
13454 * If module_init() is implemented, module_exit() must also be
13455 * implemented to allow module unload.
13456 */
13457}
13458module_exit(kvm_x86_exit);