blob: 23d7c563e012b358d661efb3e74415365718703b [file] [log] [blame]
David Brazdil0f672f62019-12-10 10:32:29 +00001// SPDX-License-Identifier: GPL-2.0-only
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * derived from drivers/kvm/kvm_main.c
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 *
12 * Authors:
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000017 */
18
19#include <linux/kvm_host.h>
20#include "irq.h"
Olivier Deprez157378f2022-04-04 15:47:50 +020021#include "ioapic.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000022#include "mmu.h"
23#include "i8254.h"
24#include "tss.h"
25#include "kvm_cache_regs.h"
Olivier Deprez157378f2022-04-04 15:47:50 +020026#include "kvm_emulate.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000027#include "x86.h"
28#include "cpuid.h"
29#include "pmu.h"
30#include "hyperv.h"
Olivier Deprez157378f2022-04-04 15:47:50 +020031#include "lapic.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000032
33#include <linux/clocksource.h>
34#include <linux/interrupt.h>
35#include <linux/kvm.h>
36#include <linux/fs.h>
37#include <linux/vmalloc.h>
38#include <linux/export.h>
39#include <linux/moduleparam.h>
40#include <linux/mman.h>
41#include <linux/highmem.h>
42#include <linux/iommu.h>
43#include <linux/intel-iommu.h>
44#include <linux/cpufreq.h>
45#include <linux/user-return-notifier.h>
46#include <linux/srcu.h>
47#include <linux/slab.h>
48#include <linux/perf_event.h>
49#include <linux/uaccess.h>
50#include <linux/hash.h>
51#include <linux/pci.h>
52#include <linux/timekeeper_internal.h>
53#include <linux/pvclock_gtod.h>
54#include <linux/kvm_irqfd.h>
55#include <linux/irqbypass.h>
56#include <linux/sched/stat.h>
David Brazdil0f672f62019-12-10 10:32:29 +000057#include <linux/sched/isolation.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000058#include <linux/mem_encrypt.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020059#include <linux/entry-kvm.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000060
61#include <trace/events/kvm.h>
62
63#include <asm/debugreg.h>
64#include <asm/msr.h>
65#include <asm/desc.h>
66#include <asm/mce.h>
67#include <linux/kernel_stat.h>
68#include <asm/fpu/internal.h> /* Ugh! */
69#include <asm/pvclock.h>
70#include <asm/div64.h>
71#include <asm/irq_remapping.h>
72#include <asm/mshyperv.h>
73#include <asm/hypervisor.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020074#include <asm/tlbflush.h>
David Brazdil0f672f62019-12-10 10:32:29 +000075#include <asm/intel_pt.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020076#include <asm/emulate_prefix.h>
David Brazdil0f672f62019-12-10 10:32:29 +000077#include <clocksource/hyperv_timer.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000078
79#define CREATE_TRACE_POINTS
80#include "trace.h"
81
82#define MAX_IO_MSRS 256
83#define KVM_MAX_MCE_BANKS 32
84u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
85EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
86
87#define emul_to_vcpu(ctxt) \
Olivier Deprez157378f2022-04-04 15:47:50 +020088 ((struct kvm_vcpu *)(ctxt)->vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000089
90/* EFER defaults:
91 * - enable syscall per default because its emulated by KVM
92 * - enable LME and LMA per default on 64 bit KVM
93 */
94#ifdef CONFIG_X86_64
95static
96u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
97#else
98static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
99#endif
100
Olivier Deprez0e641232021-09-23 10:07:05 +0200101static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
102
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000103#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
104 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
105
106static void update_cr8_intercept(struct kvm_vcpu *vcpu);
107static void process_nmi(struct kvm_vcpu *vcpu);
Olivier Deprez0e641232021-09-23 10:07:05 +0200108static void process_smi(struct kvm_vcpu *vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000109static void enter_smm(struct kvm_vcpu *vcpu);
110static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
111static void store_regs(struct kvm_vcpu *vcpu);
112static int sync_regs(struct kvm_vcpu *vcpu);
113
Olivier Deprez157378f2022-04-04 15:47:50 +0200114struct kvm_x86_ops kvm_x86_ops __read_mostly;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000115EXPORT_SYMBOL_GPL(kvm_x86_ops);
116
117static bool __read_mostly ignore_msrs = 0;
118module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
119
120static bool __read_mostly report_ignored_msrs = true;
121module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
122
123unsigned int min_timer_period_us = 200;
124module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
125
126static bool __read_mostly kvmclock_periodic_sync = true;
127module_param(kvmclock_periodic_sync, bool, S_IRUGO);
128
129bool __read_mostly kvm_has_tsc_control;
130EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
131u32 __read_mostly kvm_max_guest_tsc_khz;
132EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
133u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
134EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
135u64 __read_mostly kvm_max_tsc_scaling_ratio;
136EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
137u64 __read_mostly kvm_default_tsc_scaling_ratio;
138EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
139
140/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
141static u32 __read_mostly tsc_tolerance_ppm = 250;
142module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
143
David Brazdil0f672f62019-12-10 10:32:29 +0000144/*
145 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
146 * adaptive tuning starting from default advancment of 1000ns. '0' disables
147 * advancement entirely. Any other value is used as-is and disables adaptive
148 * tuning, i.e. allows priveleged userspace to set an exact advancement time.
149 */
150static int __read_mostly lapic_timer_advance_ns = -1;
151module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000152
153static bool __read_mostly vector_hashing = true;
154module_param(vector_hashing, bool, S_IRUGO);
155
156bool __read_mostly enable_vmware_backdoor = false;
157module_param(enable_vmware_backdoor, bool, S_IRUGO);
158EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
159
160static bool __read_mostly force_emulation_prefix = false;
161module_param(force_emulation_prefix, bool, S_IRUGO);
162
David Brazdil0f672f62019-12-10 10:32:29 +0000163int __read_mostly pi_inject_timer = -1;
164module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
165
Olivier Deprez157378f2022-04-04 15:47:50 +0200166/*
167 * Restoring the host value for MSRs that are only consumed when running in
168 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
169 * returns to userspace, i.e. the kernel can run with the guest's value.
170 */
171#define KVM_MAX_NR_USER_RETURN_MSRS 16
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000172
Olivier Deprez157378f2022-04-04 15:47:50 +0200173struct kvm_user_return_msrs_global {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000174 int nr;
Olivier Deprez157378f2022-04-04 15:47:50 +0200175 u32 msrs[KVM_MAX_NR_USER_RETURN_MSRS];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000176};
177
Olivier Deprez157378f2022-04-04 15:47:50 +0200178struct kvm_user_return_msrs {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000179 struct user_return_notifier urn;
180 bool registered;
Olivier Deprez157378f2022-04-04 15:47:50 +0200181 struct kvm_user_return_msr_values {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000182 u64 host;
183 u64 curr;
Olivier Deprez157378f2022-04-04 15:47:50 +0200184 } values[KVM_MAX_NR_USER_RETURN_MSRS];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000185};
186
Olivier Deprez157378f2022-04-04 15:47:50 +0200187static struct kvm_user_return_msrs_global __read_mostly user_return_msrs_global;
188static struct kvm_user_return_msrs __percpu *user_return_msrs;
189
190#define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
191 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
192 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
193 | XFEATURE_MASK_PKRU)
194
195u64 __read_mostly host_efer;
196EXPORT_SYMBOL_GPL(host_efer);
197
198bool __read_mostly allow_smaller_maxphyaddr = 0;
199EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
200
201static u64 __read_mostly host_xss;
202u64 __read_mostly supported_xss;
203EXPORT_SYMBOL_GPL(supported_xss);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000204
205struct kvm_stats_debugfs_item debugfs_entries[] = {
Olivier Deprez157378f2022-04-04 15:47:50 +0200206 VCPU_STAT("pf_fixed", pf_fixed),
207 VCPU_STAT("pf_guest", pf_guest),
208 VCPU_STAT("tlb_flush", tlb_flush),
209 VCPU_STAT("invlpg", invlpg),
210 VCPU_STAT("exits", exits),
211 VCPU_STAT("io_exits", io_exits),
212 VCPU_STAT("mmio_exits", mmio_exits),
213 VCPU_STAT("signal_exits", signal_exits),
214 VCPU_STAT("irq_window", irq_window_exits),
215 VCPU_STAT("nmi_window", nmi_window_exits),
216 VCPU_STAT("halt_exits", halt_exits),
217 VCPU_STAT("halt_successful_poll", halt_successful_poll),
218 VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
219 VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
220 VCPU_STAT("halt_wakeup", halt_wakeup),
221 VCPU_STAT("hypercalls", hypercalls),
222 VCPU_STAT("request_irq", request_irq_exits),
223 VCPU_STAT("irq_exits", irq_exits),
224 VCPU_STAT("host_state_reload", host_state_reload),
225 VCPU_STAT("fpu_reload", fpu_reload),
226 VCPU_STAT("insn_emulation", insn_emulation),
227 VCPU_STAT("insn_emulation_fail", insn_emulation_fail),
228 VCPU_STAT("irq_injections", irq_injections),
229 VCPU_STAT("nmi_injections", nmi_injections),
230 VCPU_STAT("req_event", req_event),
231 VCPU_STAT("l1d_flush", l1d_flush),
232 VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
233 VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
234 VM_STAT("mmu_shadow_zapped", mmu_shadow_zapped),
235 VM_STAT("mmu_pte_write", mmu_pte_write),
236 VM_STAT("mmu_pde_zapped", mmu_pde_zapped),
237 VM_STAT("mmu_flooded", mmu_flooded),
238 VM_STAT("mmu_recycled", mmu_recycled),
239 VM_STAT("mmu_cache_miss", mmu_cache_miss),
240 VM_STAT("mmu_unsync", mmu_unsync),
241 VM_STAT("remote_tlb_flush", remote_tlb_flush),
242 VM_STAT("largepages", lpages, .mode = 0444),
243 VM_STAT("nx_largepages_splitted", nx_lpage_splits, .mode = 0444),
244 VM_STAT("max_mmu_page_hash_collisions", max_mmu_page_hash_collisions),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000245 { NULL }
246};
247
248u64 __read_mostly host_xcr0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200249u64 __read_mostly supported_xcr0;
250EXPORT_SYMBOL_GPL(supported_xcr0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000251
Olivier Deprez157378f2022-04-04 15:47:50 +0200252static struct kmem_cache *x86_fpu_cache;
253
254static struct kmem_cache *x86_emulator_cache;
255
256/*
257 * When called, it means the previous get/set msr reached an invalid msr.
258 * Return true if we want to ignore/silent this failed msr access.
259 */
260static bool kvm_msr_ignored_check(struct kvm_vcpu *vcpu, u32 msr,
261 u64 data, bool write)
262{
263 const char *op = write ? "wrmsr" : "rdmsr";
264
265 if (ignore_msrs) {
266 if (report_ignored_msrs)
267 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
268 op, msr, data);
269 /* Mask the error */
270 return true;
271 } else {
272 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
273 op, msr, data);
274 return false;
275 }
276}
277
278static struct kmem_cache *kvm_alloc_emulator_cache(void)
279{
280 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
281 unsigned int size = sizeof(struct x86_emulate_ctxt);
282
283 return kmem_cache_create_usercopy("x86_emulator", size,
284 __alignof__(struct x86_emulate_ctxt),
285 SLAB_ACCOUNT, useroffset,
286 size - useroffset, NULL);
287}
David Brazdil0f672f62019-12-10 10:32:29 +0000288
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000289static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
290
291static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
292{
293 int i;
Olivier Deprez157378f2022-04-04 15:47:50 +0200294 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000295 vcpu->arch.apf.gfns[i] = ~0;
296}
297
298static void kvm_on_user_return(struct user_return_notifier *urn)
299{
300 unsigned slot;
Olivier Deprez157378f2022-04-04 15:47:50 +0200301 struct kvm_user_return_msrs *msrs
302 = container_of(urn, struct kvm_user_return_msrs, urn);
303 struct kvm_user_return_msr_values *values;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000304 unsigned long flags;
305
306 /*
307 * Disabling irqs at this point since the following code could be
308 * interrupted and executed through kvm_arch_hardware_disable()
309 */
310 local_irq_save(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +0200311 if (msrs->registered) {
312 msrs->registered = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000313 user_return_notifier_unregister(urn);
314 }
315 local_irq_restore(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +0200316 for (slot = 0; slot < user_return_msrs_global.nr; ++slot) {
317 values = &msrs->values[slot];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000318 if (values->host != values->curr) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200319 wrmsrl(user_return_msrs_global.msrs[slot], values->host);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000320 values->curr = values->host;
321 }
322 }
323}
324
Olivier Deprez157378f2022-04-04 15:47:50 +0200325int kvm_probe_user_return_msr(u32 msr)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000326{
Olivier Deprez157378f2022-04-04 15:47:50 +0200327 u64 val;
328 int ret;
329
330 preempt_disable();
331 ret = rdmsrl_safe(msr, &val);
332 if (ret)
333 goto out;
334 ret = wrmsrl_safe(msr, val);
335out:
336 preempt_enable();
337 return ret;
338}
339EXPORT_SYMBOL_GPL(kvm_probe_user_return_msr);
340
341void kvm_define_user_return_msr(unsigned slot, u32 msr)
342{
343 BUG_ON(slot >= KVM_MAX_NR_USER_RETURN_MSRS);
344 user_return_msrs_global.msrs[slot] = msr;
345 if (slot >= user_return_msrs_global.nr)
346 user_return_msrs_global.nr = slot + 1;
347}
348EXPORT_SYMBOL_GPL(kvm_define_user_return_msr);
349
350static void kvm_user_return_msr_cpu_online(void)
351{
352 unsigned int cpu = smp_processor_id();
353 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000354 u64 value;
Olivier Deprez157378f2022-04-04 15:47:50 +0200355 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000356
Olivier Deprez157378f2022-04-04 15:47:50 +0200357 for (i = 0; i < user_return_msrs_global.nr; ++i) {
358 rdmsrl_safe(user_return_msrs_global.msrs[i], &value);
359 msrs->values[i].host = value;
360 msrs->values[i].curr = value;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000361 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000362}
363
Olivier Deprez157378f2022-04-04 15:47:50 +0200364int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000365{
366 unsigned int cpu = smp_processor_id();
Olivier Deprez157378f2022-04-04 15:47:50 +0200367 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000368 int err;
369
Olivier Deprez157378f2022-04-04 15:47:50 +0200370 value = (value & mask) | (msrs->values[slot].host & ~mask);
371 if (value == msrs->values[slot].curr)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000372 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200373 err = wrmsrl_safe(user_return_msrs_global.msrs[slot], value);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000374 if (err)
375 return 1;
376
Olivier Deprez157378f2022-04-04 15:47:50 +0200377 msrs->values[slot].curr = value;
378 if (!msrs->registered) {
379 msrs->urn.on_user_return = kvm_on_user_return;
380 user_return_notifier_register(&msrs->urn);
381 msrs->registered = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000382 }
383 return 0;
384}
Olivier Deprez157378f2022-04-04 15:47:50 +0200385EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000386
387static void drop_user_return_notifiers(void)
388{
389 unsigned int cpu = smp_processor_id();
Olivier Deprez157378f2022-04-04 15:47:50 +0200390 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000391
Olivier Deprez157378f2022-04-04 15:47:50 +0200392 if (msrs->registered)
393 kvm_on_user_return(&msrs->urn);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000394}
395
396u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
397{
398 return vcpu->arch.apic_base;
399}
400EXPORT_SYMBOL_GPL(kvm_get_apic_base);
401
402enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
403{
404 return kvm_apic_mode(kvm_get_apic_base(vcpu));
405}
406EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
407
408int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
409{
410 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
411 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
412 u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
413 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
414
415 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
416 return 1;
417 if (!msr_info->host_initiated) {
418 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
419 return 1;
420 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
421 return 1;
422 }
423
424 kvm_lapic_set_base(vcpu, msr_info->data);
Olivier Deprez157378f2022-04-04 15:47:50 +0200425 kvm_recalculate_apic_map(vcpu->kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000426 return 0;
427}
428EXPORT_SYMBOL_GPL(kvm_set_apic_base);
429
Olivier Deprez157378f2022-04-04 15:47:50 +0200430asmlinkage __visible noinstr void kvm_spurious_fault(void)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000431{
432 /* Fault while not rebooting. We want the trace. */
David Brazdil0f672f62019-12-10 10:32:29 +0000433 BUG_ON(!kvm_rebooting);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000434}
435EXPORT_SYMBOL_GPL(kvm_spurious_fault);
436
437#define EXCPT_BENIGN 0
438#define EXCPT_CONTRIBUTORY 1
439#define EXCPT_PF 2
440
441static int exception_class(int vector)
442{
443 switch (vector) {
444 case PF_VECTOR:
445 return EXCPT_PF;
446 case DE_VECTOR:
447 case TS_VECTOR:
448 case NP_VECTOR:
449 case SS_VECTOR:
450 case GP_VECTOR:
451 return EXCPT_CONTRIBUTORY;
452 default:
453 break;
454 }
455 return EXCPT_BENIGN;
456}
457
458#define EXCPT_FAULT 0
459#define EXCPT_TRAP 1
460#define EXCPT_ABORT 2
461#define EXCPT_INTERRUPT 3
Olivier Deprez92d4c212022-12-06 15:05:30 +0100462#define EXCPT_DB 4
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000463
464static int exception_type(int vector)
465{
466 unsigned int mask;
467
468 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
469 return EXCPT_INTERRUPT;
470
471 mask = 1 << vector;
472
Olivier Deprez92d4c212022-12-06 15:05:30 +0100473 /*
474 * #DBs can be trap-like or fault-like, the caller must check other CPU
475 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
476 */
477 if (mask & (1 << DB_VECTOR))
478 return EXCPT_DB;
479
480 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000481 return EXCPT_TRAP;
482
483 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
484 return EXCPT_ABORT;
485
486 /* Reserved exceptions will result in fault */
487 return EXCPT_FAULT;
488}
489
David Brazdil0f672f62019-12-10 10:32:29 +0000490void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
491{
492 unsigned nr = vcpu->arch.exception.nr;
493 bool has_payload = vcpu->arch.exception.has_payload;
494 unsigned long payload = vcpu->arch.exception.payload;
495
496 if (!has_payload)
497 return;
498
499 switch (nr) {
500 case DB_VECTOR:
501 /*
502 * "Certain debug exceptions may clear bit 0-3. The
503 * remaining contents of the DR6 register are never
504 * cleared by the processor".
505 */
506 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
507 /*
508 * DR6.RTM is set by all #DB exceptions that don't clear it.
509 */
510 vcpu->arch.dr6 |= DR6_RTM;
511 vcpu->arch.dr6 |= payload;
512 /*
513 * Bit 16 should be set in the payload whenever the #DB
514 * exception should clear DR6.RTM. This makes the payload
515 * compatible with the pending debug exceptions under VMX.
516 * Though not currently documented in the SDM, this also
517 * makes the payload compatible with the exit qualification
518 * for #DB exceptions under VMX.
519 */
520 vcpu->arch.dr6 ^= payload & DR6_RTM;
Olivier Deprez0e641232021-09-23 10:07:05 +0200521
522 /*
523 * The #DB payload is defined as compatible with the 'pending
524 * debug exceptions' field under VMX, not DR6. While bit 12 is
525 * defined in the 'pending debug exceptions' field (enabled
526 * breakpoint), it is reserved and must be zero in DR6.
527 */
528 vcpu->arch.dr6 &= ~BIT(12);
David Brazdil0f672f62019-12-10 10:32:29 +0000529 break;
530 case PF_VECTOR:
531 vcpu->arch.cr2 = payload;
532 break;
533 }
534
535 vcpu->arch.exception.has_payload = false;
536 vcpu->arch.exception.payload = 0;
537}
538EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
539
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000540static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
541 unsigned nr, bool has_error, u32 error_code,
David Brazdil0f672f62019-12-10 10:32:29 +0000542 bool has_payload, unsigned long payload, bool reinject)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000543{
544 u32 prev_nr;
545 int class1, class2;
546
547 kvm_make_request(KVM_REQ_EVENT, vcpu);
548
549 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
550 queue:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000551 if (reinject) {
552 /*
553 * On vmentry, vcpu->arch.exception.pending is only
554 * true if an event injection was blocked by
555 * nested_run_pending. In that case, however,
556 * vcpu_enter_guest requests an immediate exit,
557 * and the guest shouldn't proceed far enough to
558 * need reinjection.
559 */
560 WARN_ON_ONCE(vcpu->arch.exception.pending);
561 vcpu->arch.exception.injected = true;
David Brazdil0f672f62019-12-10 10:32:29 +0000562 if (WARN_ON_ONCE(has_payload)) {
563 /*
564 * A reinjected event has already
565 * delivered its payload.
566 */
567 has_payload = false;
568 payload = 0;
569 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000570 } else {
571 vcpu->arch.exception.pending = true;
572 vcpu->arch.exception.injected = false;
573 }
574 vcpu->arch.exception.has_error_code = has_error;
575 vcpu->arch.exception.nr = nr;
576 vcpu->arch.exception.error_code = error_code;
David Brazdil0f672f62019-12-10 10:32:29 +0000577 vcpu->arch.exception.has_payload = has_payload;
578 vcpu->arch.exception.payload = payload;
Olivier Deprez157378f2022-04-04 15:47:50 +0200579 if (!is_guest_mode(vcpu))
David Brazdil0f672f62019-12-10 10:32:29 +0000580 kvm_deliver_exception_payload(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000581 return;
582 }
583
584 /* to check exception */
585 prev_nr = vcpu->arch.exception.nr;
586 if (prev_nr == DF_VECTOR) {
587 /* triple fault -> shutdown */
588 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
589 return;
590 }
591 class1 = exception_class(prev_nr);
592 class2 = exception_class(nr);
593 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
594 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
595 /*
596 * Generate double fault per SDM Table 5-5. Set
597 * exception.pending = true so that the double fault
598 * can trigger a nested vmexit.
599 */
600 vcpu->arch.exception.pending = true;
601 vcpu->arch.exception.injected = false;
602 vcpu->arch.exception.has_error_code = true;
603 vcpu->arch.exception.nr = DF_VECTOR;
604 vcpu->arch.exception.error_code = 0;
David Brazdil0f672f62019-12-10 10:32:29 +0000605 vcpu->arch.exception.has_payload = false;
606 vcpu->arch.exception.payload = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000607 } else
608 /* replace previous exception with a new one in a hope
609 that instruction re-execution will regenerate lost
610 exception */
611 goto queue;
612}
613
614void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
615{
David Brazdil0f672f62019-12-10 10:32:29 +0000616 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000617}
618EXPORT_SYMBOL_GPL(kvm_queue_exception);
619
620void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
621{
David Brazdil0f672f62019-12-10 10:32:29 +0000622 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000623}
624EXPORT_SYMBOL_GPL(kvm_requeue_exception);
625
Olivier Deprez157378f2022-04-04 15:47:50 +0200626void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
627 unsigned long payload)
David Brazdil0f672f62019-12-10 10:32:29 +0000628{
629 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
630}
Olivier Deprez157378f2022-04-04 15:47:50 +0200631EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
David Brazdil0f672f62019-12-10 10:32:29 +0000632
633static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
634 u32 error_code, unsigned long payload)
635{
636 kvm_multiple_exception(vcpu, nr, true, error_code,
637 true, payload, false);
638}
639
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000640int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
641{
642 if (err)
643 kvm_inject_gp(vcpu, 0);
644 else
645 return kvm_skip_emulated_instruction(vcpu);
646
647 return 1;
648}
649EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
650
651void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
652{
653 ++vcpu->stat.pf_guest;
654 vcpu->arch.exception.nested_apf =
655 is_guest_mode(vcpu) && fault->async_page_fault;
David Brazdil0f672f62019-12-10 10:32:29 +0000656 if (vcpu->arch.exception.nested_apf) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000657 vcpu->arch.apf.nested_apf_token = fault->address;
David Brazdil0f672f62019-12-10 10:32:29 +0000658 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
659 } else {
660 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
661 fault->address);
662 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000663}
664EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
665
Olivier Deprez157378f2022-04-04 15:47:50 +0200666bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
667 struct x86_exception *fault)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000668{
Olivier Deprez157378f2022-04-04 15:47:50 +0200669 struct kvm_mmu *fault_mmu;
670 WARN_ON_ONCE(fault->vector != PF_VECTOR);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000671
Olivier Deprez157378f2022-04-04 15:47:50 +0200672 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
673 vcpu->arch.walk_mmu;
674
675 /*
676 * Invalidate the TLB entry for the faulting address, if it exists,
677 * else the access will fault indefinitely (and to emulate hardware).
678 */
679 if ((fault->error_code & PFERR_PRESENT_MASK) &&
680 !(fault->error_code & PFERR_RSVD_MASK))
681 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
682 fault_mmu->root_hpa);
683
684 fault_mmu->inject_page_fault(vcpu, fault);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000685 return fault->nested_page_fault;
686}
Olivier Deprez157378f2022-04-04 15:47:50 +0200687EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000688
689void kvm_inject_nmi(struct kvm_vcpu *vcpu)
690{
691 atomic_inc(&vcpu->arch.nmi_queued);
692 kvm_make_request(KVM_REQ_NMI, vcpu);
693}
694EXPORT_SYMBOL_GPL(kvm_inject_nmi);
695
696void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
697{
David Brazdil0f672f62019-12-10 10:32:29 +0000698 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000699}
700EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
701
702void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
703{
David Brazdil0f672f62019-12-10 10:32:29 +0000704 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000705}
706EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
707
708/*
709 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
710 * a #GP and return false.
711 */
712bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
713{
Olivier Deprez157378f2022-04-04 15:47:50 +0200714 if (kvm_x86_ops.get_cpl(vcpu) <= required_cpl)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000715 return true;
716 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
717 return false;
718}
719EXPORT_SYMBOL_GPL(kvm_require_cpl);
720
721bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
722{
723 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
724 return true;
725
726 kvm_queue_exception(vcpu, UD_VECTOR);
727 return false;
728}
729EXPORT_SYMBOL_GPL(kvm_require_dr);
730
731/*
732 * This function will be used to read from the physical memory of the currently
733 * running guest. The difference to kvm_vcpu_read_guest_page is that this function
734 * can read from guest physical or from the guest's guest physical memory.
735 */
736int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
737 gfn_t ngfn, void *data, int offset, int len,
738 u32 access)
739{
740 struct x86_exception exception;
741 gfn_t real_gfn;
742 gpa_t ngpa;
743
744 ngpa = gfn_to_gpa(ngfn);
745 real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
746 if (real_gfn == UNMAPPED_GVA)
747 return -EFAULT;
748
749 real_gfn = gpa_to_gfn(real_gfn);
750
751 return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
752}
753EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
754
755static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
756 void *data, int offset, int len, u32 access)
757{
758 return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
759 data, offset, len, access);
760}
761
David Brazdil0f672f62019-12-10 10:32:29 +0000762static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
763{
764 return rsvd_bits(cpuid_maxphyaddr(vcpu), 63) | rsvd_bits(5, 8) |
765 rsvd_bits(1, 2);
766}
767
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000768/*
David Brazdil0f672f62019-12-10 10:32:29 +0000769 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000770 */
771int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
772{
773 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
774 unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
775 int i;
776 int ret;
777 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
778
779 ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
780 offset * sizeof(u64), sizeof(pdpte),
781 PFERR_USER_MASK|PFERR_WRITE_MASK);
782 if (ret < 0) {
783 ret = 0;
784 goto out;
785 }
786 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
787 if ((pdpte[i] & PT_PRESENT_MASK) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000788 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000789 ret = 0;
790 goto out;
791 }
792 }
793 ret = 1;
794
795 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
Olivier Deprez157378f2022-04-04 15:47:50 +0200796 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
797
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000798out:
799
800 return ret;
801}
802EXPORT_SYMBOL_GPL(load_pdptrs);
803
804bool pdptrs_changed(struct kvm_vcpu *vcpu)
805{
806 u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000807 int offset;
808 gfn_t gfn;
809 int r;
810
David Brazdil0f672f62019-12-10 10:32:29 +0000811 if (!is_pae_paging(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000812 return false;
813
Olivier Deprez157378f2022-04-04 15:47:50 +0200814 if (!kvm_register_is_available(vcpu, VCPU_EXREG_PDPTR))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000815 return true;
816
817 gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
818 offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
819 r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
820 PFERR_USER_MASK | PFERR_WRITE_MASK);
821 if (r < 0)
Olivier Deprez157378f2022-04-04 15:47:50 +0200822 return true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000823
Olivier Deprez157378f2022-04-04 15:47:50 +0200824 return memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000825}
826EXPORT_SYMBOL_GPL(pdptrs_changed);
827
828int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
829{
830 unsigned long old_cr0 = kvm_read_cr0(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +0200831 unsigned long pdptr_bits = X86_CR0_CD | X86_CR0_NW | X86_CR0_PG;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000832 unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
833
834 cr0 |= X86_CR0_ET;
835
836#ifdef CONFIG_X86_64
837 if (cr0 & 0xffffffff00000000UL)
838 return 1;
839#endif
840
841 cr0 &= ~CR0_RESERVED_BITS;
842
843 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
844 return 1;
845
846 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
847 return 1;
848
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000849#ifdef CONFIG_X86_64
Olivier Deprez157378f2022-04-04 15:47:50 +0200850 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
851 (cr0 & X86_CR0_PG)) {
852 int cs_db, cs_l;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000853
Olivier Deprez157378f2022-04-04 15:47:50 +0200854 if (!is_pae(vcpu))
855 return 1;
856 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
857 if (cs_l)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000858 return 1;
859 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200860#endif
861 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
862 is_pae(vcpu) && ((cr0 ^ old_cr0) & pdptr_bits) &&
863 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)))
864 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000865
866 if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
867 return 1;
868
Olivier Deprez157378f2022-04-04 15:47:50 +0200869 kvm_x86_ops.set_cr0(vcpu, cr0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000870
871 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
872 kvm_clear_async_pf_completion_queue(vcpu);
873 kvm_async_pf_hash_reset(vcpu);
874 }
875
876 if ((cr0 ^ old_cr0) & update_bits)
877 kvm_mmu_reset_context(vcpu);
878
879 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
880 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
881 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
882 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
883
884 return 0;
885}
886EXPORT_SYMBOL_GPL(kvm_set_cr0);
887
888void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
889{
890 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
891}
892EXPORT_SYMBOL_GPL(kvm_lmsw);
893
Olivier Deprez157378f2022-04-04 15:47:50 +0200894void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000895{
Olivier Deprez157378f2022-04-04 15:47:50 +0200896 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
897
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000898 if (vcpu->arch.xcr0 != host_xcr0)
899 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
Olivier Deprez157378f2022-04-04 15:47:50 +0200900
901 if (vcpu->arch.xsaves_enabled &&
902 vcpu->arch.ia32_xss != host_xss)
903 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000904 }
Olivier Deprez0e641232021-09-23 10:07:05 +0200905
906 if (static_cpu_has(X86_FEATURE_PKU) &&
907 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
908 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
909 vcpu->arch.pkru != vcpu->arch.host_pkru)
910 __write_pkru(vcpu->arch.pkru);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000911}
Olivier Deprez157378f2022-04-04 15:47:50 +0200912EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000913
Olivier Deprez157378f2022-04-04 15:47:50 +0200914void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000915{
Olivier Deprez0e641232021-09-23 10:07:05 +0200916 if (static_cpu_has(X86_FEATURE_PKU) &&
917 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
918 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
919 vcpu->arch.pkru = rdpkru();
920 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
921 __write_pkru(vcpu->arch.host_pkru);
922 }
923
Olivier Deprez157378f2022-04-04 15:47:50 +0200924 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
925
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000926 if (vcpu->arch.xcr0 != host_xcr0)
927 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
Olivier Deprez157378f2022-04-04 15:47:50 +0200928
929 if (vcpu->arch.xsaves_enabled &&
930 vcpu->arch.ia32_xss != host_xss)
931 wrmsrl(MSR_IA32_XSS, host_xss);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000932 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200933
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000934}
Olivier Deprez157378f2022-04-04 15:47:50 +0200935EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000936
937static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
938{
939 u64 xcr0 = xcr;
940 u64 old_xcr0 = vcpu->arch.xcr0;
941 u64 valid_bits;
942
943 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
944 if (index != XCR_XFEATURE_ENABLED_MASK)
945 return 1;
946 if (!(xcr0 & XFEATURE_MASK_FP))
947 return 1;
948 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
949 return 1;
950
951 /*
952 * Do not allow the guest to set bits that we do not support
953 * saving. However, xcr0 bit 0 is always set, even if the
954 * emulated CPU does not support XSAVE (see fx_init).
955 */
956 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
957 if (xcr0 & ~valid_bits)
958 return 1;
959
960 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
961 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
962 return 1;
963
964 if (xcr0 & XFEATURE_MASK_AVX512) {
965 if (!(xcr0 & XFEATURE_MASK_YMM))
966 return 1;
967 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
968 return 1;
969 }
970 vcpu->arch.xcr0 = xcr0;
971
972 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
Olivier Deprez157378f2022-04-04 15:47:50 +0200973 kvm_update_cpuid_runtime(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000974 return 0;
975}
976
977int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
978{
Olivier Deprez157378f2022-04-04 15:47:50 +0200979 if (kvm_x86_ops.get_cpl(vcpu) != 0 ||
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000980 __kvm_set_xcr(vcpu, index, xcr)) {
981 kvm_inject_gp(vcpu, 0);
982 return 1;
983 }
984 return 0;
985}
986EXPORT_SYMBOL_GPL(kvm_set_xcr);
987
Olivier Deprez157378f2022-04-04 15:47:50 +0200988int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
David Brazdil0f672f62019-12-10 10:32:29 +0000989{
Olivier Deprez0e641232021-09-23 10:07:05 +0200990 if (cr4 & cr4_reserved_bits)
David Brazdil0f672f62019-12-10 10:32:29 +0000991 return -EINVAL;
992
Olivier Deprez157378f2022-04-04 15:47:50 +0200993 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
David Brazdil0f672f62019-12-10 10:32:29 +0000994 return -EINVAL;
995
Olivier Deprez92d4c212022-12-06 15:05:30 +0100996 if (!kvm_x86_ops.is_valid_cr4(vcpu, cr4))
997 return -EINVAL;
998
David Brazdil0f672f62019-12-10 10:32:29 +0000999 return 0;
1000}
Olivier Deprez157378f2022-04-04 15:47:50 +02001001EXPORT_SYMBOL_GPL(kvm_valid_cr4);
David Brazdil0f672f62019-12-10 10:32:29 +00001002
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001003int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1004{
1005 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1006 unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
Olivier Deprez0e641232021-09-23 10:07:05 +02001007 X86_CR4_SMEP;
1008 unsigned long mmu_role_bits = pdptr_bits | X86_CR4_SMAP | X86_CR4_PKE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001009
David Brazdil0f672f62019-12-10 10:32:29 +00001010 if (kvm_valid_cr4(vcpu, cr4))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001011 return 1;
1012
1013 if (is_long_mode(vcpu)) {
1014 if (!(cr4 & X86_CR4_PAE))
1015 return 1;
Olivier Deprez0e641232021-09-23 10:07:05 +02001016 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1017 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001018 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1019 && ((cr4 ^ old_cr4) & pdptr_bits)
1020 && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
1021 kvm_read_cr3(vcpu)))
1022 return 1;
1023
1024 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1025 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
1026 return 1;
1027
1028 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1029 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1030 return 1;
1031 }
1032
Olivier Deprez92d4c212022-12-06 15:05:30 +01001033 kvm_x86_ops.set_cr4(vcpu, cr4);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001034
Olivier Deprez0e641232021-09-23 10:07:05 +02001035 if (((cr4 ^ old_cr4) & mmu_role_bits) ||
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001036 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1037 kvm_mmu_reset_context(vcpu);
1038
1039 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
Olivier Deprez157378f2022-04-04 15:47:50 +02001040 kvm_update_cpuid_runtime(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001041
1042 return 0;
1043}
1044EXPORT_SYMBOL_GPL(kvm_set_cr4);
1045
1046int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1047{
1048 bool skip_tlb_flush = false;
1049#ifdef CONFIG_X86_64
1050 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1051
1052 if (pcid_enabled) {
1053 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1054 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1055 }
1056#endif
1057
1058 if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
1059 if (!skip_tlb_flush) {
1060 kvm_mmu_sync_roots(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02001061 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001062 }
1063 return 0;
1064 }
1065
1066 if (is_long_mode(vcpu) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02001067 (cr3 & vcpu->arch.cr3_lm_rsvd_bits))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001068 return 1;
David Brazdil0f672f62019-12-10 10:32:29 +00001069 else if (is_pae_paging(vcpu) &&
1070 !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001071 return 1;
1072
Olivier Deprez157378f2022-04-04 15:47:50 +02001073 kvm_mmu_new_pgd(vcpu, cr3, skip_tlb_flush, skip_tlb_flush);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001074 vcpu->arch.cr3 = cr3;
Olivier Deprez157378f2022-04-04 15:47:50 +02001075 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001076
1077 return 0;
1078}
1079EXPORT_SYMBOL_GPL(kvm_set_cr3);
1080
1081int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1082{
1083 if (cr8 & CR8_RESERVED_BITS)
1084 return 1;
1085 if (lapic_in_kernel(vcpu))
1086 kvm_lapic_set_tpr(vcpu, cr8);
1087 else
1088 vcpu->arch.cr8 = cr8;
1089 return 0;
1090}
1091EXPORT_SYMBOL_GPL(kvm_set_cr8);
1092
1093unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1094{
1095 if (lapic_in_kernel(vcpu))
1096 return kvm_lapic_get_cr8(vcpu);
1097 else
1098 return vcpu->arch.cr8;
1099}
1100EXPORT_SYMBOL_GPL(kvm_get_cr8);
1101
1102static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1103{
1104 int i;
1105
1106 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1107 for (i = 0; i < KVM_NR_DB_REGS; i++)
1108 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1109 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
1110 }
1111}
1112
Olivier Deprez157378f2022-04-04 15:47:50 +02001113void kvm_update_dr7(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001114{
1115 unsigned long dr7;
1116
1117 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1118 dr7 = vcpu->arch.guest_debug_dr7;
1119 else
1120 dr7 = vcpu->arch.dr7;
Olivier Deprez157378f2022-04-04 15:47:50 +02001121 kvm_x86_ops.set_dr7(vcpu, dr7);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001122 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1123 if (dr7 & DR7_BP_EN_MASK)
1124 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1125}
Olivier Deprez157378f2022-04-04 15:47:50 +02001126EXPORT_SYMBOL_GPL(kvm_update_dr7);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001127
1128static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1129{
1130 u64 fixed = DR6_FIXED_1;
1131
1132 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
1133 fixed |= DR6_RTM;
1134 return fixed;
1135}
1136
1137static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1138{
Olivier Deprez0e641232021-09-23 10:07:05 +02001139 size_t size = ARRAY_SIZE(vcpu->arch.db);
1140
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001141 switch (dr) {
1142 case 0 ... 3:
Olivier Deprez0e641232021-09-23 10:07:05 +02001143 vcpu->arch.db[array_index_nospec(dr, size)] = val;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001144 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1145 vcpu->arch.eff_db[dr] = val;
1146 break;
1147 case 4:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001148 case 6:
Olivier Deprez157378f2022-04-04 15:47:50 +02001149 if (!kvm_dr6_valid(val))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001150 return -1; /* #GP */
1151 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001152 break;
1153 case 5:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001154 default: /* 7 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001155 if (!kvm_dr7_valid(val))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001156 return -1; /* #GP */
1157 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1158 kvm_update_dr7(vcpu);
1159 break;
1160 }
1161
1162 return 0;
1163}
1164
1165int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1166{
1167 if (__kvm_set_dr(vcpu, dr, val)) {
1168 kvm_inject_gp(vcpu, 0);
1169 return 1;
1170 }
1171 return 0;
1172}
1173EXPORT_SYMBOL_GPL(kvm_set_dr);
1174
1175int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
1176{
Olivier Deprez0e641232021-09-23 10:07:05 +02001177 size_t size = ARRAY_SIZE(vcpu->arch.db);
1178
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001179 switch (dr) {
1180 case 0 ... 3:
Olivier Deprez0e641232021-09-23 10:07:05 +02001181 *val = vcpu->arch.db[array_index_nospec(dr, size)];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001182 break;
1183 case 4:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001184 case 6:
Olivier Deprez157378f2022-04-04 15:47:50 +02001185 *val = vcpu->arch.dr6;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001186 break;
1187 case 5:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001188 default: /* 7 */
1189 *val = vcpu->arch.dr7;
1190 break;
1191 }
1192 return 0;
1193}
1194EXPORT_SYMBOL_GPL(kvm_get_dr);
1195
1196bool kvm_rdpmc(struct kvm_vcpu *vcpu)
1197{
David Brazdil0f672f62019-12-10 10:32:29 +00001198 u32 ecx = kvm_rcx_read(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001199 u64 data;
1200 int err;
1201
1202 err = kvm_pmu_rdpmc(vcpu, ecx, &data);
1203 if (err)
1204 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00001205 kvm_rax_write(vcpu, (u32)data);
1206 kvm_rdx_write(vcpu, data >> 32);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001207 return err;
1208}
1209EXPORT_SYMBOL_GPL(kvm_rdpmc);
1210
1211/*
1212 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1213 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1214 *
David Brazdil0f672f62019-12-10 10:32:29 +00001215 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1216 * extract the supported MSRs from the related const lists.
1217 * msrs_to_save is selected from the msrs_to_save_all to reflect the
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001218 * capabilities of the host cpu. This capabilities test skips MSRs that are
David Brazdil0f672f62019-12-10 10:32:29 +00001219 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001220 * may depend on host virtualization features rather than host cpu features.
1221 */
1222
David Brazdil0f672f62019-12-10 10:32:29 +00001223static const u32 msrs_to_save_all[] = {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001224 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1225 MSR_STAR,
1226#ifdef CONFIG_X86_64
1227 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1228#endif
1229 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
Olivier Deprez157378f2022-04-04 15:47:50 +02001230 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
David Brazdil0f672f62019-12-10 10:32:29 +00001231 MSR_IA32_SPEC_CTRL,
1232 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1233 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1234 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1235 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1236 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1237 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
1238 MSR_IA32_UMWAIT_CONTROL,
1239
1240 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
Olivier Deprez157378f2022-04-04 15:47:50 +02001241 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
David Brazdil0f672f62019-12-10 10:32:29 +00001242 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1243 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1244 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1245 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1246 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1247 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1248 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1249 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1250 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1251 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1252 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
1253 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1254 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1255 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1256 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1257 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1258 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1259 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1260 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1261 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
Olivier Deprez157378f2022-04-04 15:47:50 +02001262
1263 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1264 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
1265 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1266 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1267 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1268 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001269};
1270
David Brazdil0f672f62019-12-10 10:32:29 +00001271static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001272static unsigned num_msrs_to_save;
1273
David Brazdil0f672f62019-12-10 10:32:29 +00001274static const u32 emulated_msrs_all[] = {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001275 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1276 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1277 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1278 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1279 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1280 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1281 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1282 HV_X64_MSR_RESET,
1283 HV_X64_MSR_VP_INDEX,
1284 HV_X64_MSR_VP_RUNTIME,
1285 HV_X64_MSR_SCONTROL,
1286 HV_X64_MSR_STIMER0_CONFIG,
1287 HV_X64_MSR_VP_ASSIST_PAGE,
1288 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1289 HV_X64_MSR_TSC_EMULATION_STATUS,
Olivier Deprez157378f2022-04-04 15:47:50 +02001290 HV_X64_MSR_SYNDBG_OPTIONS,
1291 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1292 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1293 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001294
1295 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
Olivier Deprez157378f2022-04-04 15:47:50 +02001296 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001297
1298 MSR_IA32_TSC_ADJUST,
1299 MSR_IA32_TSCDEADLINE,
David Brazdil0f672f62019-12-10 10:32:29 +00001300 MSR_IA32_ARCH_CAPABILITIES,
Olivier Deprez157378f2022-04-04 15:47:50 +02001301 MSR_IA32_PERF_CAPABILITIES,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001302 MSR_IA32_MISC_ENABLE,
1303 MSR_IA32_MCG_STATUS,
1304 MSR_IA32_MCG_CTL,
1305 MSR_IA32_MCG_EXT_CTL,
1306 MSR_IA32_SMBASE,
1307 MSR_SMI_COUNT,
1308 MSR_PLATFORM_INFO,
1309 MSR_MISC_FEATURES_ENABLES,
1310 MSR_AMD64_VIRT_SPEC_CTRL,
David Brazdil0f672f62019-12-10 10:32:29 +00001311 MSR_IA32_POWER_CTL,
Olivier Deprez157378f2022-04-04 15:47:50 +02001312 MSR_IA32_UCODE_REV,
David Brazdil0f672f62019-12-10 10:32:29 +00001313
1314 /*
1315 * The following list leaves out MSRs whose values are determined
1316 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1317 * We always support the "true" VMX control MSRs, even if the host
1318 * processor does not, so I am putting these registers here rather
1319 * than in msrs_to_save_all.
1320 */
1321 MSR_IA32_VMX_BASIC,
1322 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1323 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1324 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1325 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1326 MSR_IA32_VMX_MISC,
1327 MSR_IA32_VMX_CR0_FIXED0,
1328 MSR_IA32_VMX_CR4_FIXED0,
1329 MSR_IA32_VMX_VMCS_ENUM,
1330 MSR_IA32_VMX_PROCBASED_CTLS2,
1331 MSR_IA32_VMX_EPT_VPID_CAP,
1332 MSR_IA32_VMX_VMFUNC,
1333
1334 MSR_K7_HWCR,
1335 MSR_KVM_POLL_CONTROL,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001336};
1337
David Brazdil0f672f62019-12-10 10:32:29 +00001338static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001339static unsigned num_emulated_msrs;
1340
1341/*
1342 * List of msr numbers which are used to expose MSR-based features that
1343 * can be used by a hypervisor to validate requested CPU features.
1344 */
David Brazdil0f672f62019-12-10 10:32:29 +00001345static const u32 msr_based_features_all[] = {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001346 MSR_IA32_VMX_BASIC,
1347 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1348 MSR_IA32_VMX_PINBASED_CTLS,
1349 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1350 MSR_IA32_VMX_PROCBASED_CTLS,
1351 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1352 MSR_IA32_VMX_EXIT_CTLS,
1353 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1354 MSR_IA32_VMX_ENTRY_CTLS,
1355 MSR_IA32_VMX_MISC,
1356 MSR_IA32_VMX_CR0_FIXED0,
1357 MSR_IA32_VMX_CR0_FIXED1,
1358 MSR_IA32_VMX_CR4_FIXED0,
1359 MSR_IA32_VMX_CR4_FIXED1,
1360 MSR_IA32_VMX_VMCS_ENUM,
1361 MSR_IA32_VMX_PROCBASED_CTLS2,
1362 MSR_IA32_VMX_EPT_VPID_CAP,
1363 MSR_IA32_VMX_VMFUNC,
1364
Olivier Deprez92d4c212022-12-06 15:05:30 +01001365 MSR_AMD64_DE_CFG,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001366 MSR_IA32_UCODE_REV,
1367 MSR_IA32_ARCH_CAPABILITIES,
Olivier Deprez157378f2022-04-04 15:47:50 +02001368 MSR_IA32_PERF_CAPABILITIES,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001369};
1370
David Brazdil0f672f62019-12-10 10:32:29 +00001371static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001372static unsigned int num_msr_based_features;
1373
Olivier Deprez92d4c212022-12-06 15:05:30 +01001374/*
1375 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1376 * does not yet virtualize. These include:
1377 * 10 - MISC_PACKAGE_CTRLS
1378 * 11 - ENERGY_FILTERING_CTL
1379 * 12 - DOITM
1380 * 18 - FB_CLEAR_CTRL
1381 * 21 - XAPIC_DISABLE_STATUS
1382 * 23 - OVERCLOCKING_STATUS
1383 */
1384
1385#define KVM_SUPPORTED_ARCH_CAP \
1386 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1387 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1388 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1389 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1390 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO)
1391
David Brazdil0f672f62019-12-10 10:32:29 +00001392static u64 kvm_get_arch_capabilities(void)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001393{
David Brazdil0f672f62019-12-10 10:32:29 +00001394 u64 data = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001395
Olivier Deprez92d4c212022-12-06 15:05:30 +01001396 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001397 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
Olivier Deprez92d4c212022-12-06 15:05:30 +01001398 data &= KVM_SUPPORTED_ARCH_CAP;
1399 }
David Brazdil0f672f62019-12-10 10:32:29 +00001400
1401 /*
1402 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1403 * the nested hypervisor runs with NX huge pages. If it is not,
1404 * L1 is anyway vulnerable to ITLB_MULTIHIT explots from other
1405 * L1 guests, so it need not worry about its own (L2) guests.
1406 */
1407 data |= ARCH_CAP_PSCHANGE_MC_NO;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001408
1409 /*
1410 * If we're doing cache flushes (either "always" or "cond")
1411 * we will do one whenever the guest does a vmlaunch/vmresume.
1412 * If an outer hypervisor is doing the cache flush for us
1413 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1414 * capability to the guest too, and if EPT is disabled we're not
1415 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1416 * require a nested hypervisor to do a flush of its own.
1417 */
1418 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1419 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1420
David Brazdil0f672f62019-12-10 10:32:29 +00001421 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1422 data |= ARCH_CAP_RDCL_NO;
1423 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1424 data |= ARCH_CAP_SSB_NO;
1425 if (!boot_cpu_has_bug(X86_BUG_MDS))
1426 data |= ARCH_CAP_MDS_NO;
1427
Olivier Deprez157378f2022-04-04 15:47:50 +02001428 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1429 /*
1430 * If RTM=0 because the kernel has disabled TSX, the host might
1431 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1432 * and therefore knows that there cannot be TAA) but keep
1433 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1434 * and we want to allow migrating those guests to tsx=off hosts.
1435 */
Olivier Deprez0e641232021-09-23 10:07:05 +02001436 data &= ~ARCH_CAP_TAA_NO;
Olivier Deprez157378f2022-04-04 15:47:50 +02001437 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
Olivier Deprez0e641232021-09-23 10:07:05 +02001438 data |= ARCH_CAP_TAA_NO;
Olivier Deprez157378f2022-04-04 15:47:50 +02001439 } else {
1440 /*
1441 * Nothing to do here; we emulate TSX_CTRL if present on the
1442 * host so the guest can choose between disabling TSX or
1443 * using VERW to clear CPU buffers.
1444 */
1445 }
David Brazdil0f672f62019-12-10 10:32:29 +00001446
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001447 return data;
1448}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001449
1450static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1451{
1452 switch (msr->index) {
1453 case MSR_IA32_ARCH_CAPABILITIES:
1454 msr->data = kvm_get_arch_capabilities();
1455 break;
1456 case MSR_IA32_UCODE_REV:
1457 rdmsrl_safe(msr->index, &msr->data);
1458 break;
1459 default:
Olivier Deprez157378f2022-04-04 15:47:50 +02001460 return kvm_x86_ops.get_msr_feature(msr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001461 }
1462 return 0;
1463}
1464
1465static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1466{
1467 struct kvm_msr_entry msr;
1468 int r;
1469
1470 msr.index = index;
1471 r = kvm_get_msr_feature(&msr);
Olivier Deprez157378f2022-04-04 15:47:50 +02001472
1473 if (r == KVM_MSR_RET_INVALID) {
1474 /* Unconditionally clear the output for simplicity */
1475 *data = 0;
1476 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1477 r = 0;
1478 }
1479
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001480 if (r)
1481 return r;
1482
1483 *data = msr.data;
1484
1485 return 0;
1486}
1487
David Brazdil0f672f62019-12-10 10:32:29 +00001488static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1489{
1490 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1491 return false;
1492
1493 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1494 return false;
1495
1496 if (efer & (EFER_LME | EFER_LMA) &&
1497 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1498 return false;
1499
1500 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1501 return false;
1502
1503 return true;
1504
1505}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001506bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1507{
1508 if (efer & efer_reserved_bits)
1509 return false;
1510
David Brazdil0f672f62019-12-10 10:32:29 +00001511 return __kvm_valid_efer(vcpu, efer);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001512}
1513EXPORT_SYMBOL_GPL(kvm_valid_efer);
1514
David Brazdil0f672f62019-12-10 10:32:29 +00001515static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001516{
1517 u64 old_efer = vcpu->arch.efer;
David Brazdil0f672f62019-12-10 10:32:29 +00001518 u64 efer = msr_info->data;
Olivier Deprez157378f2022-04-04 15:47:50 +02001519 int r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001520
David Brazdil0f672f62019-12-10 10:32:29 +00001521 if (efer & efer_reserved_bits)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001522 return 1;
1523
David Brazdil0f672f62019-12-10 10:32:29 +00001524 if (!msr_info->host_initiated) {
1525 if (!__kvm_valid_efer(vcpu, efer))
1526 return 1;
1527
1528 if (is_paging(vcpu) &&
1529 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1530 return 1;
1531 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001532
1533 efer &= ~EFER_LMA;
1534 efer |= vcpu->arch.efer & EFER_LMA;
1535
Olivier Deprez157378f2022-04-04 15:47:50 +02001536 r = kvm_x86_ops.set_efer(vcpu, efer);
1537 if (r) {
1538 WARN_ON(r > 0);
1539 return r;
1540 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001541
1542 /* Update reserved bits */
1543 if ((efer ^ old_efer) & EFER_NX)
1544 kvm_mmu_reset_context(vcpu);
1545
1546 return 0;
1547}
1548
1549void kvm_enable_efer_bits(u64 mask)
1550{
1551 efer_reserved_bits &= ~mask;
1552}
1553EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1554
Olivier Deprez157378f2022-04-04 15:47:50 +02001555bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1556{
1557 struct kvm_x86_msr_filter *msr_filter;
1558 struct msr_bitmap_range *ranges;
1559 struct kvm *kvm = vcpu->kvm;
1560 bool allowed;
1561 int idx;
1562 u32 i;
1563
1564 /* x2APIC MSRs do not support filtering. */
1565 if (index >= 0x800 && index <= 0x8ff)
1566 return true;
1567
1568 idx = srcu_read_lock(&kvm->srcu);
1569
1570 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1571 if (!msr_filter) {
1572 allowed = true;
1573 goto out;
1574 }
1575
1576 allowed = msr_filter->default_allow;
1577 ranges = msr_filter->ranges;
1578
1579 for (i = 0; i < msr_filter->count; i++) {
1580 u32 start = ranges[i].base;
1581 u32 end = start + ranges[i].nmsrs;
1582 u32 flags = ranges[i].flags;
1583 unsigned long *bitmap = ranges[i].bitmap;
1584
1585 if ((index >= start) && (index < end) && (flags & type)) {
1586 allowed = !!test_bit(index - start, bitmap);
1587 break;
1588 }
1589 }
1590
1591out:
1592 srcu_read_unlock(&kvm->srcu, idx);
1593
1594 return allowed;
1595}
1596EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1597
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001598/*
David Brazdil0f672f62019-12-10 10:32:29 +00001599 * Write @data into the MSR specified by @index. Select MSR specific fault
1600 * checks are bypassed if @host_initiated is %true.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001601 * Returns 0 on success, non-0 otherwise.
1602 * Assumes vcpu_load() was already called.
1603 */
David Brazdil0f672f62019-12-10 10:32:29 +00001604static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1605 bool host_initiated)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001606{
David Brazdil0f672f62019-12-10 10:32:29 +00001607 struct msr_data msr;
1608
Olivier Deprez157378f2022-04-04 15:47:50 +02001609 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1610 return KVM_MSR_RET_FILTERED;
1611
David Brazdil0f672f62019-12-10 10:32:29 +00001612 switch (index) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001613 case MSR_FS_BASE:
1614 case MSR_GS_BASE:
1615 case MSR_KERNEL_GS_BASE:
1616 case MSR_CSTAR:
1617 case MSR_LSTAR:
David Brazdil0f672f62019-12-10 10:32:29 +00001618 if (is_noncanonical_address(data, vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001619 return 1;
1620 break;
1621 case MSR_IA32_SYSENTER_EIP:
1622 case MSR_IA32_SYSENTER_ESP:
1623 /*
1624 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1625 * non-canonical address is written on Intel but not on
1626 * AMD (which ignores the top 32-bits, because it does
1627 * not implement 64-bit SYSENTER).
1628 *
1629 * 64-bit code should hence be able to write a non-canonical
1630 * value on AMD. Making the address canonical ensures that
1631 * vmentry does not fail on Intel after writing a non-canonical
1632 * value, and that something deterministic happens if the guest
1633 * invokes 64-bit SYSENTER.
1634 */
David Brazdil0f672f62019-12-10 10:32:29 +00001635 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001636 }
David Brazdil0f672f62019-12-10 10:32:29 +00001637
1638 msr.data = data;
1639 msr.index = index;
1640 msr.host_initiated = host_initiated;
1641
Olivier Deprez157378f2022-04-04 15:47:50 +02001642 return kvm_x86_ops.set_msr(vcpu, &msr);
1643}
1644
1645static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1646 u32 index, u64 data, bool host_initiated)
1647{
1648 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1649
1650 if (ret == KVM_MSR_RET_INVALID)
1651 if (kvm_msr_ignored_check(vcpu, index, data, true))
1652 ret = 0;
1653
1654 return ret;
David Brazdil0f672f62019-12-10 10:32:29 +00001655}
1656
1657/*
1658 * Read the MSR specified by @index into @data. Select MSR specific fault
1659 * checks are bypassed if @host_initiated is %true.
1660 * Returns 0 on success, non-0 otherwise.
1661 * Assumes vcpu_load() was already called.
1662 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001663int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1664 bool host_initiated)
David Brazdil0f672f62019-12-10 10:32:29 +00001665{
1666 struct msr_data msr;
1667 int ret;
1668
Olivier Deprez157378f2022-04-04 15:47:50 +02001669 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1670 return KVM_MSR_RET_FILTERED;
1671
David Brazdil0f672f62019-12-10 10:32:29 +00001672 msr.index = index;
1673 msr.host_initiated = host_initiated;
1674
Olivier Deprez157378f2022-04-04 15:47:50 +02001675 ret = kvm_x86_ops.get_msr(vcpu, &msr);
David Brazdil0f672f62019-12-10 10:32:29 +00001676 if (!ret)
1677 *data = msr.data;
1678 return ret;
1679}
1680
Olivier Deprez157378f2022-04-04 15:47:50 +02001681static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1682 u32 index, u64 *data, bool host_initiated)
1683{
1684 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1685
1686 if (ret == KVM_MSR_RET_INVALID) {
1687 /* Unconditionally clear *data for simplicity */
1688 *data = 0;
1689 if (kvm_msr_ignored_check(vcpu, index, 0, false))
1690 ret = 0;
1691 }
1692
1693 return ret;
1694}
1695
David Brazdil0f672f62019-12-10 10:32:29 +00001696int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1697{
Olivier Deprez157378f2022-04-04 15:47:50 +02001698 return kvm_get_msr_ignored_check(vcpu, index, data, false);
David Brazdil0f672f62019-12-10 10:32:29 +00001699}
1700EXPORT_SYMBOL_GPL(kvm_get_msr);
1701
1702int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1703{
Olivier Deprez157378f2022-04-04 15:47:50 +02001704 return kvm_set_msr_ignored_check(vcpu, index, data, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001705}
1706EXPORT_SYMBOL_GPL(kvm_set_msr);
1707
Olivier Deprez157378f2022-04-04 15:47:50 +02001708static int complete_emulated_msr(struct kvm_vcpu *vcpu, bool is_read)
1709{
1710 if (vcpu->run->msr.error) {
1711 kvm_inject_gp(vcpu, 0);
1712 return 1;
1713 } else if (is_read) {
1714 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1715 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1716 }
1717
1718 return kvm_skip_emulated_instruction(vcpu);
1719}
1720
1721static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1722{
1723 return complete_emulated_msr(vcpu, true);
1724}
1725
1726static int complete_emulated_wrmsr(struct kvm_vcpu *vcpu)
1727{
1728 return complete_emulated_msr(vcpu, false);
1729}
1730
1731static u64 kvm_msr_reason(int r)
1732{
1733 switch (r) {
1734 case KVM_MSR_RET_INVALID:
1735 return KVM_MSR_EXIT_REASON_UNKNOWN;
1736 case KVM_MSR_RET_FILTERED:
1737 return KVM_MSR_EXIT_REASON_FILTER;
1738 default:
1739 return KVM_MSR_EXIT_REASON_INVAL;
1740 }
1741}
1742
1743static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1744 u32 exit_reason, u64 data,
1745 int (*completion)(struct kvm_vcpu *vcpu),
1746 int r)
1747{
1748 u64 msr_reason = kvm_msr_reason(r);
1749
1750 /* Check if the user wanted to know about this MSR fault */
1751 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1752 return 0;
1753
1754 vcpu->run->exit_reason = exit_reason;
1755 vcpu->run->msr.error = 0;
1756 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1757 vcpu->run->msr.reason = msr_reason;
1758 vcpu->run->msr.index = index;
1759 vcpu->run->msr.data = data;
1760 vcpu->arch.complete_userspace_io = completion;
1761
1762 return 1;
1763}
1764
1765static int kvm_get_msr_user_space(struct kvm_vcpu *vcpu, u32 index, int r)
1766{
1767 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_RDMSR, 0,
1768 complete_emulated_rdmsr, r);
1769}
1770
1771static int kvm_set_msr_user_space(struct kvm_vcpu *vcpu, u32 index, u64 data, int r)
1772{
1773 return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_WRMSR, data,
1774 complete_emulated_wrmsr, r);
1775}
1776
David Brazdil0f672f62019-12-10 10:32:29 +00001777int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1778{
1779 u32 ecx = kvm_rcx_read(vcpu);
1780 u64 data;
Olivier Deprez157378f2022-04-04 15:47:50 +02001781 int r;
David Brazdil0f672f62019-12-10 10:32:29 +00001782
Olivier Deprez157378f2022-04-04 15:47:50 +02001783 r = kvm_get_msr(vcpu, ecx, &data);
1784
1785 /* MSR read failed? See if we should ask user space */
1786 if (r && kvm_get_msr_user_space(vcpu, ecx, r)) {
1787 /* Bounce to user space */
1788 return 0;
1789 }
1790
1791 /* MSR read failed? Inject a #GP */
1792 if (r) {
David Brazdil0f672f62019-12-10 10:32:29 +00001793 trace_kvm_msr_read_ex(ecx);
1794 kvm_inject_gp(vcpu, 0);
1795 return 1;
1796 }
1797
1798 trace_kvm_msr_read(ecx, data);
1799
1800 kvm_rax_write(vcpu, data & -1u);
1801 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1802 return kvm_skip_emulated_instruction(vcpu);
1803}
1804EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1805
1806int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1807{
1808 u32 ecx = kvm_rcx_read(vcpu);
1809 u64 data = kvm_read_edx_eax(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02001810 int r;
David Brazdil0f672f62019-12-10 10:32:29 +00001811
Olivier Deprez157378f2022-04-04 15:47:50 +02001812 r = kvm_set_msr(vcpu, ecx, data);
1813
1814 /* MSR write failed? See if we should ask user space */
1815 if (r && kvm_set_msr_user_space(vcpu, ecx, data, r))
1816 /* Bounce to user space */
1817 return 0;
1818
1819 /* Signal all other negative errors to userspace */
1820 if (r < 0)
1821 return r;
1822
1823 /* MSR write failed? Inject a #GP */
1824 if (r > 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00001825 trace_kvm_msr_write_ex(ecx, data);
1826 kvm_inject_gp(vcpu, 0);
1827 return 1;
1828 }
1829
1830 trace_kvm_msr_write(ecx, data);
1831 return kvm_skip_emulated_instruction(vcpu);
1832}
1833EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1834
Olivier Deprez157378f2022-04-04 15:47:50 +02001835bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
1836{
1837 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
1838 xfer_to_guest_mode_work_pending();
1839}
1840EXPORT_SYMBOL_GPL(kvm_vcpu_exit_request);
1841
1842/*
1843 * The fast path for frequent and performance sensitive wrmsr emulation,
1844 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
1845 * the latency of virtual IPI by avoiding the expensive bits of transitioning
1846 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
1847 * other cases which must be called after interrupts are enabled on the host.
1848 */
1849static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
1850{
1851 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
1852 return 1;
1853
1854 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
1855 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
1856 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
1857 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
1858
1859 data &= ~(1 << 12);
1860 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
1861 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
1862 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
1863 trace_kvm_apic_write(APIC_ICR, (u32)data);
1864 return 0;
1865 }
1866
1867 return 1;
1868}
1869
1870static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
1871{
1872 if (!kvm_can_use_hv_timer(vcpu))
1873 return 1;
1874
1875 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1876 return 0;
1877}
1878
1879fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
1880{
1881 u32 msr = kvm_rcx_read(vcpu);
1882 u64 data;
1883 fastpath_t ret = EXIT_FASTPATH_NONE;
1884
1885 switch (msr) {
1886 case APIC_BASE_MSR + (APIC_ICR >> 4):
1887 data = kvm_read_edx_eax(vcpu);
1888 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
1889 kvm_skip_emulated_instruction(vcpu);
1890 ret = EXIT_FASTPATH_EXIT_HANDLED;
1891 }
1892 break;
1893 case MSR_IA32_TSCDEADLINE:
1894 data = kvm_read_edx_eax(vcpu);
1895 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
1896 kvm_skip_emulated_instruction(vcpu);
1897 ret = EXIT_FASTPATH_REENTER_GUEST;
1898 }
1899 break;
1900 default:
1901 break;
1902 }
1903
1904 if (ret != EXIT_FASTPATH_NONE)
1905 trace_kvm_msr_write(msr, data);
1906
1907 return ret;
1908}
1909EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
1910
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001911/*
1912 * Adapt set_msr() to msr_io()'s calling convention
1913 */
1914static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1915{
Olivier Deprez157378f2022-04-04 15:47:50 +02001916 return kvm_get_msr_ignored_check(vcpu, index, data, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001917}
1918
1919static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1920{
Olivier Deprez157378f2022-04-04 15:47:50 +02001921 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001922}
1923
1924#ifdef CONFIG_X86_64
Olivier Deprez157378f2022-04-04 15:47:50 +02001925struct pvclock_clock {
1926 int vclock_mode;
1927 u64 cycle_last;
1928 u64 mask;
1929 u32 mult;
1930 u32 shift;
1931 u64 base_cycles;
1932 u64 offset;
1933};
1934
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001935struct pvclock_gtod_data {
1936 seqcount_t seq;
1937
Olivier Deprez157378f2022-04-04 15:47:50 +02001938 struct pvclock_clock clock; /* extract of a clocksource struct */
1939 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001940
Olivier Deprez157378f2022-04-04 15:47:50 +02001941 ktime_t offs_boot;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001942 u64 wall_time_sec;
1943};
1944
1945static struct pvclock_gtod_data pvclock_gtod_data;
1946
1947static void update_pvclock_gtod(struct timekeeper *tk)
1948{
1949 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001950
1951 write_seqcount_begin(&vdata->seq);
1952
1953 /* copy pvclock gtod data */
Olivier Deprez157378f2022-04-04 15:47:50 +02001954 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001955 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
1956 vdata->clock.mask = tk->tkr_mono.mask;
1957 vdata->clock.mult = tk->tkr_mono.mult;
1958 vdata->clock.shift = tk->tkr_mono.shift;
Olivier Deprez157378f2022-04-04 15:47:50 +02001959 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
1960 vdata->clock.offset = tk->tkr_mono.base;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001961
Olivier Deprez157378f2022-04-04 15:47:50 +02001962 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
1963 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
1964 vdata->raw_clock.mask = tk->tkr_raw.mask;
1965 vdata->raw_clock.mult = tk->tkr_raw.mult;
1966 vdata->raw_clock.shift = tk->tkr_raw.shift;
1967 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
1968 vdata->raw_clock.offset = tk->tkr_raw.base;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001969
1970 vdata->wall_time_sec = tk->xtime_sec;
1971
Olivier Deprez157378f2022-04-04 15:47:50 +02001972 vdata->offs_boot = tk->offs_boot;
1973
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001974 write_seqcount_end(&vdata->seq);
1975}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001976
Olivier Deprez157378f2022-04-04 15:47:50 +02001977static s64 get_kvmclock_base_ns(void)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001978{
Olivier Deprez157378f2022-04-04 15:47:50 +02001979 /* Count up from boot time, but with the frequency of the raw clock. */
1980 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001981}
Olivier Deprez157378f2022-04-04 15:47:50 +02001982#else
1983static s64 get_kvmclock_base_ns(void)
1984{
1985 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
1986 return ktime_get_boottime_ns();
1987}
1988#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001989
1990static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1991{
1992 int version;
1993 int r;
1994 struct pvclock_wall_clock wc;
Olivier Deprez157378f2022-04-04 15:47:50 +02001995 u64 wall_nsec;
1996
1997 kvm->arch.wall_clock = wall_clock;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001998
1999 if (!wall_clock)
2000 return;
2001
2002 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2003 if (r)
2004 return;
2005
2006 if (version & 1)
2007 ++version; /* first time write, random junk */
2008
2009 ++version;
2010
2011 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2012 return;
2013
2014 /*
2015 * The guest calculates current wall clock time by adding
2016 * system time (updated by kvm_guest_time_update below) to the
Olivier Deprez157378f2022-04-04 15:47:50 +02002017 * wall clock specified here. We do the reverse here.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002018 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002019 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002020
Olivier Deprez157378f2022-04-04 15:47:50 +02002021 wc.nsec = do_div(wall_nsec, 1000000000);
2022 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002023 wc.version = version;
2024
2025 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2026
2027 version++;
2028 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2029}
2030
Olivier Deprez157378f2022-04-04 15:47:50 +02002031static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2032 bool old_msr, bool host_initiated)
2033{
2034 struct kvm_arch *ka = &vcpu->kvm->arch;
2035
2036 if (vcpu->vcpu_id == 0 && !host_initiated) {
2037 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2038 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2039
2040 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2041 }
2042
2043 vcpu->arch.time = system_time;
2044 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2045
2046 /* we verify if the enable bit is set... */
2047 vcpu->arch.pv_time_enabled = false;
2048 if (!(system_time & 1))
2049 return;
2050
2051 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2052 &vcpu->arch.pv_time, system_time & ~1ULL,
2053 sizeof(struct pvclock_vcpu_time_info)))
2054 vcpu->arch.pv_time_enabled = true;
2055
2056 return;
2057}
2058
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002059static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2060{
2061 do_shl32_div32(dividend, divisor);
2062 return dividend;
2063}
2064
2065static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2066 s8 *pshift, u32 *pmultiplier)
2067{
2068 uint64_t scaled64;
2069 int32_t shift = 0;
2070 uint64_t tps64;
2071 uint32_t tps32;
2072
2073 tps64 = base_hz;
2074 scaled64 = scaled_hz;
2075 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2076 tps64 >>= 1;
2077 shift--;
2078 }
2079
2080 tps32 = (uint32_t)tps64;
2081 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2082 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2083 scaled64 >>= 1;
2084 else
2085 tps32 <<= 1;
2086 shift++;
2087 }
2088
2089 *pshift = shift;
2090 *pmultiplier = div_frac(scaled64, tps32);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002091}
2092
2093#ifdef CONFIG_X86_64
2094static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2095#endif
2096
2097static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2098static unsigned long max_tsc_khz;
2099
2100static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2101{
2102 u64 v = (u64)khz * (1000000 + ppm);
2103 do_div(v, 1000000);
2104 return v;
2105}
2106
2107static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2108{
2109 u64 ratio;
2110
2111 /* Guest TSC same frequency as host TSC? */
2112 if (!scale) {
2113 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2114 return 0;
2115 }
2116
2117 /* TSC scaling supported? */
2118 if (!kvm_has_tsc_control) {
2119 if (user_tsc_khz > tsc_khz) {
2120 vcpu->arch.tsc_catchup = 1;
2121 vcpu->arch.tsc_always_catchup = 1;
2122 return 0;
2123 } else {
David Brazdil0f672f62019-12-10 10:32:29 +00002124 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002125 return -1;
2126 }
2127 }
2128
2129 /* TSC scaling required - calculate ratio */
2130 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2131 user_tsc_khz, tsc_khz);
2132
2133 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
David Brazdil0f672f62019-12-10 10:32:29 +00002134 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2135 user_tsc_khz);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002136 return -1;
2137 }
2138
2139 vcpu->arch.tsc_scaling_ratio = ratio;
2140 return 0;
2141}
2142
2143static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2144{
2145 u32 thresh_lo, thresh_hi;
2146 int use_scaling = 0;
2147
2148 /* tsc_khz can be zero if TSC calibration fails */
2149 if (user_tsc_khz == 0) {
2150 /* set tsc_scaling_ratio to a safe value */
2151 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
2152 return -1;
2153 }
2154
2155 /* Compute a scale to convert nanoseconds in TSC cycles */
2156 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2157 &vcpu->arch.virtual_tsc_shift,
2158 &vcpu->arch.virtual_tsc_mult);
2159 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2160
2161 /*
2162 * Compute the variation in TSC rate which is acceptable
2163 * within the range of tolerance and decide if the
2164 * rate being applied is within that bounds of the hardware
2165 * rate. If so, no scaling or compensation need be done.
2166 */
2167 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2168 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2169 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2170 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
2171 use_scaling = 1;
2172 }
2173 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2174}
2175
2176static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2177{
2178 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2179 vcpu->arch.virtual_tsc_mult,
2180 vcpu->arch.virtual_tsc_shift);
2181 tsc += vcpu->arch.this_tsc_write;
2182 return tsc;
2183}
2184
2185static inline int gtod_is_based_on_tsc(int mode)
2186{
Olivier Deprez157378f2022-04-04 15:47:50 +02002187 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002188}
2189
2190static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
2191{
2192#ifdef CONFIG_X86_64
2193 bool vcpus_matched;
2194 struct kvm_arch *ka = &vcpu->kvm->arch;
2195 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2196
2197 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2198 atomic_read(&vcpu->kvm->online_vcpus));
2199
2200 /*
2201 * Once the masterclock is enabled, always perform request in
2202 * order to update it.
2203 *
2204 * In order to enable masterclock, the host clocksource must be TSC
2205 * and the vcpus need to have matched TSCs. When that happens,
2206 * perform request to enable masterclock.
2207 */
2208 if (ka->use_master_clock ||
2209 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
2210 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2211
2212 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2213 atomic_read(&vcpu->kvm->online_vcpus),
2214 ka->use_master_clock, gtod->clock.vclock_mode);
2215#endif
2216}
2217
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002218/*
2219 * Multiply tsc by a fixed point number represented by ratio.
2220 *
2221 * The most significant 64-N bits (mult) of ratio represent the
2222 * integral part of the fixed point number; the remaining N bits
2223 * (frac) represent the fractional part, ie. ratio represents a fixed
2224 * point number (mult + frac * 2^(-N)).
2225 *
2226 * N equals to kvm_tsc_scaling_ratio_frac_bits.
2227 */
2228static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2229{
2230 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2231}
2232
2233u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
2234{
2235 u64 _tsc = tsc;
2236 u64 ratio = vcpu->arch.tsc_scaling_ratio;
2237
2238 if (ratio != kvm_default_tsc_scaling_ratio)
2239 _tsc = __scale_tsc(ratio, tsc);
2240
2241 return _tsc;
2242}
2243EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2244
2245static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2246{
2247 u64 tsc;
2248
2249 tsc = kvm_scale_tsc(vcpu, rdtsc());
2250
2251 return target_tsc - tsc;
2252}
2253
2254u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2255{
Olivier Deprez157378f2022-04-04 15:47:50 +02002256 return vcpu->arch.l1_tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002257}
2258EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2259
2260static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2261{
Olivier Deprez157378f2022-04-04 15:47:50 +02002262 vcpu->arch.l1_tsc_offset = offset;
2263 vcpu->arch.tsc_offset = kvm_x86_ops.write_l1_tsc_offset(vcpu, offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002264}
2265
2266static inline bool kvm_check_tsc_unstable(void)
2267{
2268#ifdef CONFIG_X86_64
2269 /*
2270 * TSC is marked unstable when we're running on Hyper-V,
2271 * 'TSC page' clocksource is good.
2272 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002273 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002274 return false;
2275#endif
2276 return check_tsc_unstable();
2277}
2278
Olivier Deprez157378f2022-04-04 15:47:50 +02002279static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002280{
2281 struct kvm *kvm = vcpu->kvm;
2282 u64 offset, ns, elapsed;
2283 unsigned long flags;
2284 bool matched;
2285 bool already_matched;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002286 bool synchronizing = false;
2287
2288 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2289 offset = kvm_compute_tsc_offset(vcpu, data);
Olivier Deprez157378f2022-04-04 15:47:50 +02002290 ns = get_kvmclock_base_ns();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002291 elapsed = ns - kvm->arch.last_tsc_nsec;
2292
2293 if (vcpu->arch.virtual_tsc_khz) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002294 if (data == 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002295 /*
2296 * detection of vcpu initialization -- need to sync
2297 * with other vCPUs. This particularly helps to keep
2298 * kvm_clock stable after CPU hotplug
2299 */
2300 synchronizing = true;
2301 } else {
2302 u64 tsc_exp = kvm->arch.last_tsc_write +
2303 nsec_to_cycles(vcpu, elapsed);
2304 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2305 /*
2306 * Special case: TSC write with a small delta (1 second)
2307 * of virtual cycle time against real time is
2308 * interpreted as an attempt to synchronize the CPU.
2309 */
2310 synchronizing = data < tsc_exp + tsc_hz &&
2311 data + tsc_hz > tsc_exp;
2312 }
2313 }
2314
2315 /*
2316 * For a reliable TSC, we can match TSC offsets, and for an unstable
2317 * TSC, we add elapsed time in this computation. We could let the
2318 * compensation code attempt to catch up if we fall behind, but
2319 * it's better to try to match offsets from the beginning.
2320 */
2321 if (synchronizing &&
2322 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2323 if (!kvm_check_tsc_unstable()) {
2324 offset = kvm->arch.cur_tsc_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002325 } else {
2326 u64 delta = nsec_to_cycles(vcpu, elapsed);
2327 data += delta;
2328 offset = kvm_compute_tsc_offset(vcpu, data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002329 }
2330 matched = true;
2331 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
2332 } else {
2333 /*
2334 * We split periods of matched TSC writes into generations.
2335 * For each generation, we track the original measured
2336 * nanosecond time, offset, and write, so if TSCs are in
2337 * sync, we can match exact offset, and if not, we can match
2338 * exact software computation in compute_guest_tsc()
2339 *
2340 * These values are tracked in kvm->arch.cur_xxx variables.
2341 */
2342 kvm->arch.cur_tsc_generation++;
2343 kvm->arch.cur_tsc_nsec = ns;
2344 kvm->arch.cur_tsc_write = data;
2345 kvm->arch.cur_tsc_offset = offset;
2346 matched = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002347 }
2348
2349 /*
2350 * We also track th most recent recorded KHZ, write and time to
2351 * allow the matching interval to be extended at each write.
2352 */
2353 kvm->arch.last_tsc_nsec = ns;
2354 kvm->arch.last_tsc_write = data;
2355 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2356
2357 vcpu->arch.last_guest_tsc = data;
2358
2359 /* Keep track of which generation this VCPU has synchronized to */
2360 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2361 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2362 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2363
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002364 kvm_vcpu_write_tsc_offset(vcpu, offset);
2365 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2366
2367 spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
2368 if (!matched) {
2369 kvm->arch.nr_vcpus_matched_tsc = 0;
2370 } else if (!already_matched) {
2371 kvm->arch.nr_vcpus_matched_tsc++;
2372 }
2373
2374 kvm_track_tsc_matching(vcpu);
2375 spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
2376}
2377
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002378static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2379 s64 adjustment)
2380{
Olivier Deprez157378f2022-04-04 15:47:50 +02002381 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002382 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2383}
2384
2385static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2386{
2387 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
2388 WARN_ON(adjustment < 0);
2389 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
2390 adjust_tsc_offset_guest(vcpu, adjustment);
2391}
2392
2393#ifdef CONFIG_X86_64
2394
2395static u64 read_tsc(void)
2396{
2397 u64 ret = (u64)rdtsc_ordered();
2398 u64 last = pvclock_gtod_data.clock.cycle_last;
2399
2400 if (likely(ret >= last))
2401 return ret;
2402
2403 /*
2404 * GCC likes to generate cmov here, but this branch is extremely
2405 * predictable (it's just a function of time and the likely is
2406 * very likely) and there's a data dependence, so force GCC
2407 * to generate a branch instead. I don't barrier() because
2408 * we don't actually need a barrier, and if this function
2409 * ever gets inlined it will generate worse code.
2410 */
2411 asm volatile ("");
2412 return last;
2413}
2414
Olivier Deprez157378f2022-04-04 15:47:50 +02002415static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2416 int *mode)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002417{
2418 long v;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002419 u64 tsc_pg_val;
2420
Olivier Deprez157378f2022-04-04 15:47:50 +02002421 switch (clock->vclock_mode) {
2422 case VDSO_CLOCKMODE_HVCLOCK:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002423 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2424 tsc_timestamp);
2425 if (tsc_pg_val != U64_MAX) {
2426 /* TSC page valid */
Olivier Deprez157378f2022-04-04 15:47:50 +02002427 *mode = VDSO_CLOCKMODE_HVCLOCK;
2428 v = (tsc_pg_val - clock->cycle_last) &
2429 clock->mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002430 } else {
2431 /* TSC page invalid */
Olivier Deprez157378f2022-04-04 15:47:50 +02002432 *mode = VDSO_CLOCKMODE_NONE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002433 }
2434 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02002435 case VDSO_CLOCKMODE_TSC:
2436 *mode = VDSO_CLOCKMODE_TSC;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002437 *tsc_timestamp = read_tsc();
Olivier Deprez157378f2022-04-04 15:47:50 +02002438 v = (*tsc_timestamp - clock->cycle_last) &
2439 clock->mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002440 break;
2441 default:
Olivier Deprez157378f2022-04-04 15:47:50 +02002442 *mode = VDSO_CLOCKMODE_NONE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002443 }
2444
Olivier Deprez157378f2022-04-04 15:47:50 +02002445 if (*mode == VDSO_CLOCKMODE_NONE)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002446 *tsc_timestamp = v = 0;
2447
Olivier Deprez157378f2022-04-04 15:47:50 +02002448 return v * clock->mult;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002449}
2450
Olivier Deprez157378f2022-04-04 15:47:50 +02002451static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002452{
2453 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2454 unsigned long seq;
2455 int mode;
2456 u64 ns;
2457
2458 do {
2459 seq = read_seqcount_begin(&gtod->seq);
Olivier Deprez157378f2022-04-04 15:47:50 +02002460 ns = gtod->raw_clock.base_cycles;
2461 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2462 ns >>= gtod->raw_clock.shift;
2463 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002464 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2465 *t = ns;
2466
2467 return mode;
2468}
2469
2470static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2471{
2472 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2473 unsigned long seq;
2474 int mode;
2475 u64 ns;
2476
2477 do {
2478 seq = read_seqcount_begin(&gtod->seq);
2479 ts->tv_sec = gtod->wall_time_sec;
Olivier Deprez157378f2022-04-04 15:47:50 +02002480 ns = gtod->clock.base_cycles;
2481 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002482 ns >>= gtod->clock.shift;
2483 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2484
2485 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2486 ts->tv_nsec = ns;
2487
2488 return mode;
2489}
2490
2491/* returns true if host is using TSC based clocksource */
2492static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2493{
2494 /* checked again under seqlock below */
2495 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2496 return false;
2497
Olivier Deprez157378f2022-04-04 15:47:50 +02002498 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002499 tsc_timestamp));
2500}
2501
2502/* returns true if host is using TSC based clocksource */
2503static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2504 u64 *tsc_timestamp)
2505{
2506 /* checked again under seqlock below */
2507 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2508 return false;
2509
2510 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2511}
2512#endif
2513
2514/*
2515 *
2516 * Assuming a stable TSC across physical CPUS, and a stable TSC
2517 * across virtual CPUs, the following condition is possible.
2518 * Each numbered line represents an event visible to both
2519 * CPUs at the next numbered event.
2520 *
2521 * "timespecX" represents host monotonic time. "tscX" represents
2522 * RDTSC value.
2523 *
2524 * VCPU0 on CPU0 | VCPU1 on CPU1
2525 *
2526 * 1. read timespec0,tsc0
2527 * 2. | timespec1 = timespec0 + N
2528 * | tsc1 = tsc0 + M
2529 * 3. transition to guest | transition to guest
2530 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2531 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2532 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2533 *
2534 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2535 *
2536 * - ret0 < ret1
2537 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2538 * ...
2539 * - 0 < N - M => M < N
2540 *
2541 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2542 * always the case (the difference between two distinct xtime instances
2543 * might be smaller then the difference between corresponding TSC reads,
2544 * when updating guest vcpus pvclock areas).
2545 *
2546 * To avoid that problem, do not allow visibility of distinct
2547 * system_timestamp/tsc_timestamp values simultaneously: use a master
2548 * copy of host monotonic time values. Update that master copy
2549 * in lockstep.
2550 *
2551 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
2552 *
2553 */
2554
2555static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2556{
2557#ifdef CONFIG_X86_64
2558 struct kvm_arch *ka = &kvm->arch;
2559 int vclock_mode;
2560 bool host_tsc_clocksource, vcpus_matched;
2561
2562 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2563 atomic_read(&kvm->online_vcpus));
2564
2565 /*
2566 * If the host uses TSC clock, then passthrough TSC as stable
2567 * to the guest.
2568 */
2569 host_tsc_clocksource = kvm_get_time_and_clockread(
2570 &ka->master_kernel_ns,
2571 &ka->master_cycle_now);
2572
2573 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
2574 && !ka->backwards_tsc_observed
2575 && !ka->boot_vcpu_runs_old_kvmclock;
2576
2577 if (ka->use_master_clock)
2578 atomic_set(&kvm_guest_has_master_clock, 1);
2579
2580 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
2581 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2582 vcpus_matched);
2583#endif
2584}
2585
2586void kvm_make_mclock_inprogress_request(struct kvm *kvm)
2587{
2588 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2589}
2590
2591static void kvm_gen_update_masterclock(struct kvm *kvm)
2592{
2593#ifdef CONFIG_X86_64
2594 int i;
2595 struct kvm_vcpu *vcpu;
2596 struct kvm_arch *ka = &kvm->arch;
2597
2598 spin_lock(&ka->pvclock_gtod_sync_lock);
2599 kvm_make_mclock_inprogress_request(kvm);
2600 /* no guest entries from this point */
2601 pvclock_update_vm_gtod_copy(kvm);
2602
2603 kvm_for_each_vcpu(i, vcpu, kvm)
2604 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2605
2606 /* guest entries allowed */
2607 kvm_for_each_vcpu(i, vcpu, kvm)
2608 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
2609
2610 spin_unlock(&ka->pvclock_gtod_sync_lock);
2611#endif
2612}
2613
2614u64 get_kvmclock_ns(struct kvm *kvm)
2615{
2616 struct kvm_arch *ka = &kvm->arch;
2617 struct pvclock_vcpu_time_info hv_clock;
2618 u64 ret;
2619
2620 spin_lock(&ka->pvclock_gtod_sync_lock);
2621 if (!ka->use_master_clock) {
2622 spin_unlock(&ka->pvclock_gtod_sync_lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02002623 return get_kvmclock_base_ns() + ka->kvmclock_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002624 }
2625
2626 hv_clock.tsc_timestamp = ka->master_cycle_now;
2627 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
2628 spin_unlock(&ka->pvclock_gtod_sync_lock);
2629
2630 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2631 get_cpu();
2632
2633 if (__this_cpu_read(cpu_tsc_khz)) {
2634 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2635 &hv_clock.tsc_shift,
2636 &hv_clock.tsc_to_system_mul);
2637 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
2638 } else
Olivier Deprez157378f2022-04-04 15:47:50 +02002639 ret = get_kvmclock_base_ns() + ka->kvmclock_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002640
2641 put_cpu();
2642
2643 return ret;
2644}
2645
2646static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
2647{
2648 struct kvm_vcpu_arch *vcpu = &v->arch;
2649 struct pvclock_vcpu_time_info guest_hv_clock;
2650
2651 if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
2652 &guest_hv_clock, sizeof(guest_hv_clock))))
2653 return;
2654
2655 /* This VCPU is paused, but it's legal for a guest to read another
2656 * VCPU's kvmclock, so we really have to follow the specification where
2657 * it says that version is odd if data is being modified, and even after
2658 * it is consistent.
2659 *
2660 * Version field updates must be kept separate. This is because
2661 * kvm_write_guest_cached might use a "rep movs" instruction, and
2662 * writes within a string instruction are weakly ordered. So there
2663 * are three writes overall.
2664 *
2665 * As a small optimization, only write the version field in the first
2666 * and third write. The vcpu->pv_time cache is still valid, because the
2667 * version field is the first in the struct.
2668 */
2669 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2670
2671 if (guest_hv_clock.version & 1)
2672 ++guest_hv_clock.version; /* first time write, random junk */
2673
2674 vcpu->hv_clock.version = guest_hv_clock.version + 1;
2675 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2676 &vcpu->hv_clock,
2677 sizeof(vcpu->hv_clock.version));
2678
2679 smp_wmb();
2680
2681 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2682 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2683
2684 if (vcpu->pvclock_set_guest_stopped_request) {
2685 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2686 vcpu->pvclock_set_guest_stopped_request = false;
2687 }
2688
2689 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2690
2691 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2692 &vcpu->hv_clock,
2693 sizeof(vcpu->hv_clock));
2694
2695 smp_wmb();
2696
2697 vcpu->hv_clock.version++;
2698 kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
2699 &vcpu->hv_clock,
2700 sizeof(vcpu->hv_clock.version));
2701}
2702
2703static int kvm_guest_time_update(struct kvm_vcpu *v)
2704{
2705 unsigned long flags, tgt_tsc_khz;
2706 struct kvm_vcpu_arch *vcpu = &v->arch;
2707 struct kvm_arch *ka = &v->kvm->arch;
2708 s64 kernel_ns;
2709 u64 tsc_timestamp, host_tsc;
2710 u8 pvclock_flags;
2711 bool use_master_clock;
2712
2713 kernel_ns = 0;
2714 host_tsc = 0;
2715
2716 /*
2717 * If the host uses TSC clock, then passthrough TSC as stable
2718 * to the guest.
2719 */
2720 spin_lock(&ka->pvclock_gtod_sync_lock);
2721 use_master_clock = ka->use_master_clock;
2722 if (use_master_clock) {
2723 host_tsc = ka->master_cycle_now;
2724 kernel_ns = ka->master_kernel_ns;
2725 }
2726 spin_unlock(&ka->pvclock_gtod_sync_lock);
2727
2728 /* Keep irq disabled to prevent changes to the clock */
2729 local_irq_save(flags);
2730 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
2731 if (unlikely(tgt_tsc_khz == 0)) {
2732 local_irq_restore(flags);
2733 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2734 return 1;
2735 }
2736 if (!use_master_clock) {
2737 host_tsc = rdtsc();
Olivier Deprez157378f2022-04-04 15:47:50 +02002738 kernel_ns = get_kvmclock_base_ns();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002739 }
2740
2741 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
2742
2743 /*
2744 * We may have to catch up the TSC to match elapsed wall clock
2745 * time for two reasons, even if kvmclock is used.
2746 * 1) CPU could have been running below the maximum TSC rate
2747 * 2) Broken TSC compensation resets the base at each VCPU
2748 * entry to avoid unknown leaps of TSC even when running
2749 * again on the same CPU. This may cause apparent elapsed
2750 * time to disappear, and the guest to stand still or run
2751 * very slowly.
2752 */
2753 if (vcpu->tsc_catchup) {
2754 u64 tsc = compute_guest_tsc(v, kernel_ns);
2755 if (tsc > tsc_timestamp) {
2756 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
2757 tsc_timestamp = tsc;
2758 }
2759 }
2760
2761 local_irq_restore(flags);
2762
2763 /* With all the info we got, fill in the values */
2764
2765 if (kvm_has_tsc_control)
2766 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
2767
2768 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
2769 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
2770 &vcpu->hv_clock.tsc_shift,
2771 &vcpu->hv_clock.tsc_to_system_mul);
2772 vcpu->hw_tsc_khz = tgt_tsc_khz;
2773 }
2774
2775 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
2776 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
2777 vcpu->last_guest_tsc = tsc_timestamp;
2778
2779 /* If the host uses TSC clocksource, then it is stable */
2780 pvclock_flags = 0;
2781 if (use_master_clock)
2782 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
2783
2784 vcpu->hv_clock.flags = pvclock_flags;
2785
2786 if (vcpu->pv_time_enabled)
2787 kvm_setup_pvclock_page(v);
2788 if (v == kvm_get_vcpu(v->kvm, 0))
2789 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
2790 return 0;
2791}
2792
2793/*
2794 * kvmclock updates which are isolated to a given vcpu, such as
2795 * vcpu->cpu migration, should not allow system_timestamp from
2796 * the rest of the vcpus to remain static. Otherwise ntp frequency
2797 * correction applies to one vcpu's system_timestamp but not
2798 * the others.
2799 *
2800 * So in those cases, request a kvmclock update for all vcpus.
2801 * We need to rate-limit these requests though, as they can
2802 * considerably slow guests that have a large number of vcpus.
2803 * The time for a remote vcpu to update its kvmclock is bound
2804 * by the delay we use to rate-limit the updates.
2805 */
2806
2807#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
2808
2809static void kvmclock_update_fn(struct work_struct *work)
2810{
2811 int i;
2812 struct delayed_work *dwork = to_delayed_work(work);
2813 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2814 kvmclock_update_work);
2815 struct kvm *kvm = container_of(ka, struct kvm, arch);
2816 struct kvm_vcpu *vcpu;
2817
2818 kvm_for_each_vcpu(i, vcpu, kvm) {
2819 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2820 kvm_vcpu_kick(vcpu);
2821 }
2822}
2823
2824static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
2825{
2826 struct kvm *kvm = v->kvm;
2827
2828 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
2829 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
2830 KVMCLOCK_UPDATE_DELAY);
2831}
2832
2833#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2834
2835static void kvmclock_sync_fn(struct work_struct *work)
2836{
2837 struct delayed_work *dwork = to_delayed_work(work);
2838 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2839 kvmclock_sync_work);
2840 struct kvm *kvm = container_of(ka, struct kvm, arch);
2841
2842 if (!kvmclock_periodic_sync)
2843 return;
2844
2845 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2846 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2847 KVMCLOCK_SYNC_PERIOD);
2848}
2849
David Brazdil0f672f62019-12-10 10:32:29 +00002850/*
2851 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
2852 */
2853static bool can_set_mci_status(struct kvm_vcpu *vcpu)
2854{
2855 /* McStatusWrEn enabled? */
Olivier Deprez157378f2022-04-04 15:47:50 +02002856 if (guest_cpuid_is_amd_or_hygon(vcpu))
David Brazdil0f672f62019-12-10 10:32:29 +00002857 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
2858
2859 return false;
2860}
2861
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002862static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2863{
2864 u64 mcg_cap = vcpu->arch.mcg_cap;
2865 unsigned bank_num = mcg_cap & 0xff;
2866 u32 msr = msr_info->index;
2867 u64 data = msr_info->data;
2868
2869 switch (msr) {
2870 case MSR_IA32_MCG_STATUS:
2871 vcpu->arch.mcg_status = data;
2872 break;
2873 case MSR_IA32_MCG_CTL:
2874 if (!(mcg_cap & MCG_CTL_P) &&
2875 (data || !msr_info->host_initiated))
2876 return 1;
2877 if (data != 0 && data != ~(u64)0)
2878 return 1;
2879 vcpu->arch.mcg_ctl = data;
2880 break;
2881 default:
2882 if (msr >= MSR_IA32_MC0_CTL &&
2883 msr < MSR_IA32_MCx_CTL(bank_num)) {
Olivier Deprez0e641232021-09-23 10:07:05 +02002884 u32 offset = array_index_nospec(
2885 msr - MSR_IA32_MC0_CTL,
2886 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2887
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002888 /* only 0 or all 1s can be written to IA32_MCi_CTL
2889 * some Linux kernels though clear bit 10 in bank 4 to
2890 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
Olivier Deprez92d4c212022-12-06 15:05:30 +01002891 * this to avoid an uncatched #GP in the guest.
2892 *
2893 * UNIXWARE clears bit 0 of MC1_CTL to ignore
2894 * correctable, single-bit ECC data errors.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002895 */
2896 if ((offset & 0x3) == 0 &&
Olivier Deprez92d4c212022-12-06 15:05:30 +01002897 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
2898 return 1;
David Brazdil0f672f62019-12-10 10:32:29 +00002899
2900 /* MCi_STATUS */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002901 if (!msr_info->host_initiated &&
David Brazdil0f672f62019-12-10 10:32:29 +00002902 (offset & 0x3) == 1 && data != 0) {
2903 if (!can_set_mci_status(vcpu))
Olivier Deprez92d4c212022-12-06 15:05:30 +01002904 return 1;
David Brazdil0f672f62019-12-10 10:32:29 +00002905 }
2906
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002907 vcpu->arch.mce_banks[offset] = data;
2908 break;
2909 }
2910 return 1;
2911 }
2912 return 0;
2913}
2914
2915static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2916{
2917 struct kvm *kvm = vcpu->kvm;
2918 int lm = is_long_mode(vcpu);
2919 u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2920 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2921 u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2922 : kvm->arch.xen_hvm_config.blob_size_32;
2923 u32 page_num = data & ~PAGE_MASK;
2924 u64 page_addr = data & PAGE_MASK;
2925 u8 *page;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002926
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002927 if (page_num >= blob_size)
Olivier Deprez157378f2022-04-04 15:47:50 +02002928 return 1;
2929
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002930 page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
Olivier Deprez157378f2022-04-04 15:47:50 +02002931 if (IS_ERR(page))
2932 return PTR_ERR(page);
2933
2934 if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE)) {
2935 kfree(page);
2936 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002937 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002938 return 0;
2939}
2940
2941static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
2942{
2943 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
2944
2945 return (vcpu->arch.apf.msr_en_val & mask) == mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002946}
2947
2948static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2949{
2950 gpa_t gpa = data & ~0x3f;
2951
Olivier Deprez157378f2022-04-04 15:47:50 +02002952 /* Bits 4:5 are reserved, Should be zero */
2953 if (data & 0x30)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002954 return 1;
2955
Olivier Deprez157378f2022-04-04 15:47:50 +02002956 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
2957 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
2958 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002959
Olivier Deprez157378f2022-04-04 15:47:50 +02002960 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
2961 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
2962 return 1;
2963
2964 if (!lapic_in_kernel(vcpu))
2965 return data ? 1 : 0;
2966
2967 vcpu->arch.apf.msr_en_val = data;
2968
2969 if (!kvm_pv_async_pf_enabled(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002970 kvm_clear_async_pf_completion_queue(vcpu);
2971 kvm_async_pf_hash_reset(vcpu);
2972 return 0;
2973 }
2974
2975 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
Olivier Deprez157378f2022-04-04 15:47:50 +02002976 sizeof(u64)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002977 return 1;
2978
2979 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2980 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
Olivier Deprez157378f2022-04-04 15:47:50 +02002981
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002982 kvm_async_pf_wakeup_all(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02002983
2984 return 0;
2985}
2986
2987static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
2988{
2989 /* Bits 8-63 are reserved */
2990 if (data >> 8)
2991 return 1;
2992
2993 if (!lapic_in_kernel(vcpu))
2994 return 1;
2995
2996 vcpu->arch.apf.msr_int_val = data;
2997
2998 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
2999
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003000 return 0;
3001}
3002
3003static void kvmclock_reset(struct kvm_vcpu *vcpu)
3004{
3005 vcpu->arch.pv_time_enabled = false;
David Brazdil0f672f62019-12-10 10:32:29 +00003006 vcpu->arch.time = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003007}
3008
Olivier Deprez157378f2022-04-04 15:47:50 +02003009static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003010{
3011 ++vcpu->stat.tlb_flush;
Olivier Deprez157378f2022-04-04 15:47:50 +02003012 kvm_x86_ops.tlb_flush_all(vcpu);
3013}
3014
3015static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3016{
3017 ++vcpu->stat.tlb_flush;
3018 kvm_x86_ops.tlb_flush_guest(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003019}
3020
3021static void record_steal_time(struct kvm_vcpu *vcpu)
3022{
Olivier Deprez0e641232021-09-23 10:07:05 +02003023 struct kvm_host_map map;
3024 struct kvm_steal_time *st;
3025
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003026 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3027 return;
3028
Olivier Deprez0e641232021-09-23 10:07:05 +02003029 /* -EAGAIN is returned in atomic context so we can just return. */
3030 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
3031 &map, &vcpu->arch.st.cache, false))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003032 return;
3033
Olivier Deprez0e641232021-09-23 10:07:05 +02003034 st = map.hva +
3035 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3036
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003037 /*
3038 * Doing a TLB flush here, on the guest's behalf, can avoid
3039 * expensive IPIs.
3040 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003041 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3042 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3043 st->preempted & KVM_VCPU_FLUSH_TLB);
3044 if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
3045 kvm_vcpu_flush_tlb_guest(vcpu);
3046 } else {
3047 st->preempted = 0;
3048 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003049
Olivier Deprez0e641232021-09-23 10:07:05 +02003050 vcpu->arch.st.preempted = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003051
Olivier Deprez0e641232021-09-23 10:07:05 +02003052 if (st->version & 1)
3053 st->version += 1; /* first time write, random junk */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003054
Olivier Deprez0e641232021-09-23 10:07:05 +02003055 st->version += 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003056
3057 smp_wmb();
3058
Olivier Deprez0e641232021-09-23 10:07:05 +02003059 st->steal += current->sched_info.run_delay -
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003060 vcpu->arch.st.last_steal;
3061 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3062
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003063 smp_wmb();
3064
Olivier Deprez0e641232021-09-23 10:07:05 +02003065 st->version += 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003066
Olivier Deprez0e641232021-09-23 10:07:05 +02003067 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003068}
3069
3070int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3071{
3072 bool pr = false;
3073 u32 msr = msr_info->index;
3074 u64 data = msr_info->data;
3075
3076 switch (msr) {
3077 case MSR_AMD64_NB_CFG:
3078 case MSR_IA32_UCODE_WRITE:
3079 case MSR_VM_HSAVE_PA:
3080 case MSR_AMD64_PATCH_LOADER:
3081 case MSR_AMD64_BU_CFG2:
3082 case MSR_AMD64_DC_CFG:
3083 case MSR_F15H_EX_CFG:
3084 break;
3085
3086 case MSR_IA32_UCODE_REV:
3087 if (msr_info->host_initiated)
3088 vcpu->arch.microcode_version = data;
3089 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003090 case MSR_IA32_ARCH_CAPABILITIES:
3091 if (!msr_info->host_initiated)
3092 return 1;
3093 vcpu->arch.arch_capabilities = data;
3094 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003095 case MSR_IA32_PERF_CAPABILITIES: {
3096 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3097
3098 if (!msr_info->host_initiated)
3099 return 1;
3100 if (kvm_get_msr_feature(&msr_ent))
3101 return 1;
3102 if (data & ~msr_ent.data)
3103 return 1;
3104
3105 vcpu->arch.perf_capabilities = data;
3106
3107 return 0;
3108 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003109 case MSR_EFER:
David Brazdil0f672f62019-12-10 10:32:29 +00003110 return set_efer(vcpu, msr_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003111 case MSR_K7_HWCR:
3112 data &= ~(u64)0x40; /* ignore flush filter disable */
3113 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3114 data &= ~(u64)0x8; /* ignore TLB cache disable */
David Brazdil0f672f62019-12-10 10:32:29 +00003115
3116 /* Handle McStatusWrEn */
3117 if (data == BIT_ULL(18)) {
3118 vcpu->arch.msr_hwcr = data;
3119 } else if (data != 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003120 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3121 data);
3122 return 1;
3123 }
3124 break;
3125 case MSR_FAM10H_MMIO_CONF_BASE:
3126 if (data != 0) {
3127 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3128 "0x%llx\n", data);
3129 return 1;
3130 }
3131 break;
3132 case MSR_IA32_DEBUGCTLMSR:
3133 if (!data) {
3134 /* We support the non-activated case already */
3135 break;
3136 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
3137 /* Values other than LBR and BTF are vendor-specific,
3138 thus reserved and should throw a #GP */
3139 return 1;
Olivier Deprez157378f2022-04-04 15:47:50 +02003140 } else if (report_ignored_msrs)
3141 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
3142 __func__, data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003143 break;
3144 case 0x200 ... 0x2ff:
3145 return kvm_mtrr_set_msr(vcpu, msr, data);
3146 case MSR_IA32_APICBASE:
3147 return kvm_set_apic_base(vcpu, msr_info);
Olivier Deprez0e641232021-09-23 10:07:05 +02003148 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003149 return kvm_x2apic_msr_write(vcpu, msr, data);
3150 case MSR_IA32_TSCDEADLINE:
3151 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3152 break;
3153 case MSR_IA32_TSC_ADJUST:
3154 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3155 if (!msr_info->host_initiated) {
3156 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3157 adjust_tsc_offset_guest(vcpu, adj);
Olivier Deprez0e641232021-09-23 10:07:05 +02003158 /* Before back to guest, tsc_timestamp must be adjusted
3159 * as well, otherwise guest's percpu pvclock time could jump.
3160 */
3161 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003162 }
3163 vcpu->arch.ia32_tsc_adjust_msr = data;
3164 }
3165 break;
3166 case MSR_IA32_MISC_ENABLE:
David Brazdil0f672f62019-12-10 10:32:29 +00003167 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3168 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3169 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3170 return 1;
3171 vcpu->arch.ia32_misc_enable_msr = data;
Olivier Deprez157378f2022-04-04 15:47:50 +02003172 kvm_update_cpuid_runtime(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00003173 } else {
3174 vcpu->arch.ia32_misc_enable_msr = data;
3175 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003176 break;
3177 case MSR_IA32_SMBASE:
3178 if (!msr_info->host_initiated)
3179 return 1;
3180 vcpu->arch.smbase = data;
3181 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003182 case MSR_IA32_POWER_CTL:
3183 vcpu->arch.msr_ia32_power_ctl = data;
3184 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003185 case MSR_IA32_TSC:
Olivier Deprez157378f2022-04-04 15:47:50 +02003186 if (msr_info->host_initiated) {
3187 kvm_synchronize_tsc(vcpu, data);
3188 } else {
3189 u64 adj = kvm_compute_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3190 adjust_tsc_offset_guest(vcpu, adj);
3191 vcpu->arch.ia32_tsc_adjust_msr += adj;
3192 }
3193 break;
3194 case MSR_IA32_XSS:
3195 if (!msr_info->host_initiated &&
3196 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3197 return 1;
3198 /*
3199 * KVM supports exposing PT to the guest, but does not support
3200 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3201 * XSAVES/XRSTORS to save/restore PT MSRs.
3202 */
3203 if (data & ~supported_xss)
3204 return 1;
3205 vcpu->arch.ia32_xss = data;
3206 kvm_update_cpuid_runtime(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003207 break;
3208 case MSR_SMI_COUNT:
3209 if (!msr_info->host_initiated)
3210 return 1;
3211 vcpu->arch.smi_count = data;
3212 break;
3213 case MSR_KVM_WALL_CLOCK_NEW:
Olivier Deprez157378f2022-04-04 15:47:50 +02003214 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3215 return 1;
3216
3217 kvm_write_wall_clock(vcpu->kvm, data);
3218 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003219 case MSR_KVM_WALL_CLOCK:
Olivier Deprez157378f2022-04-04 15:47:50 +02003220 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3221 return 1;
3222
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003223 kvm_write_wall_clock(vcpu->kvm, data);
3224 break;
3225 case MSR_KVM_SYSTEM_TIME_NEW:
Olivier Deprez157378f2022-04-04 15:47:50 +02003226 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3227 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003228
Olivier Deprez157378f2022-04-04 15:47:50 +02003229 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003230 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003231 case MSR_KVM_SYSTEM_TIME:
3232 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3233 return 1;
3234
3235 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
3236 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003237 case MSR_KVM_ASYNC_PF_EN:
Olivier Deprez157378f2022-04-04 15:47:50 +02003238 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3239 return 1;
3240
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003241 if (kvm_pv_enable_async_pf(vcpu, data))
3242 return 1;
3243 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003244 case MSR_KVM_ASYNC_PF_INT:
3245 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3246 return 1;
3247
3248 if (kvm_pv_enable_async_pf_int(vcpu, data))
3249 return 1;
3250 break;
3251 case MSR_KVM_ASYNC_PF_ACK:
3252 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3253 return 1;
3254 if (data & 0x1) {
3255 vcpu->arch.apf.pageready_pending = false;
3256 kvm_check_async_pf_completion(vcpu);
3257 }
3258 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003259 case MSR_KVM_STEAL_TIME:
Olivier Deprez157378f2022-04-04 15:47:50 +02003260 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3261 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003262
3263 if (unlikely(!sched_info_on()))
3264 return 1;
3265
3266 if (data & KVM_STEAL_RESERVED_MASK)
3267 return 1;
3268
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003269 vcpu->arch.st.msr_val = data;
3270
3271 if (!(data & KVM_MSR_ENABLED))
3272 break;
3273
3274 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3275
3276 break;
3277 case MSR_KVM_PV_EOI_EN:
Olivier Deprez157378f2022-04-04 15:47:50 +02003278 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3279 return 1;
3280
David Brazdil0f672f62019-12-10 10:32:29 +00003281 if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003282 return 1;
3283 break;
3284
David Brazdil0f672f62019-12-10 10:32:29 +00003285 case MSR_KVM_POLL_CONTROL:
Olivier Deprez157378f2022-04-04 15:47:50 +02003286 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3287 return 1;
3288
David Brazdil0f672f62019-12-10 10:32:29 +00003289 /* only enable bit supported */
3290 if (data & (-1ULL << 1))
3291 return 1;
3292
3293 vcpu->arch.msr_kvm_poll_control = data;
3294 break;
3295
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003296 case MSR_IA32_MCG_CTL:
3297 case MSR_IA32_MCG_STATUS:
3298 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3299 return set_msr_mce(vcpu, msr_info);
3300
3301 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3302 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
Olivier Deprez157378f2022-04-04 15:47:50 +02003303 pr = true;
3304 fallthrough;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003305 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3306 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3307 if (kvm_pmu_is_valid_msr(vcpu, msr))
3308 return kvm_pmu_set_msr(vcpu, msr_info);
3309
3310 if (pr || data != 0)
3311 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3312 "0x%x data 0x%llx\n", msr, data);
3313 break;
3314 case MSR_K7_CLK_CTL:
3315 /*
3316 * Ignore all writes to this no longer documented MSR.
3317 * Writes are only relevant for old K7 processors,
3318 * all pre-dating SVM, but a recommended workaround from
3319 * AMD for these chips. It is possible to specify the
3320 * affected processor models on the command line, hence
3321 * the need to ignore the workaround.
3322 */
3323 break;
3324 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
Olivier Deprez157378f2022-04-04 15:47:50 +02003325 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3326 case HV_X64_MSR_SYNDBG_OPTIONS:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003327 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3328 case HV_X64_MSR_CRASH_CTL:
3329 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3330 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3331 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3332 case HV_X64_MSR_TSC_EMULATION_STATUS:
3333 return kvm_hv_set_msr_common(vcpu, msr, data,
3334 msr_info->host_initiated);
3335 case MSR_IA32_BBL_CR_CTL3:
3336 /* Drop writes to this legacy MSR -- see rdmsr
3337 * counterpart for further detail.
3338 */
3339 if (report_ignored_msrs)
3340 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3341 msr, data);
3342 break;
3343 case MSR_AMD64_OSVW_ID_LENGTH:
3344 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3345 return 1;
3346 vcpu->arch.osvw.length = data;
3347 break;
3348 case MSR_AMD64_OSVW_STATUS:
3349 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3350 return 1;
3351 vcpu->arch.osvw.status = data;
3352 break;
3353 case MSR_PLATFORM_INFO:
3354 if (!msr_info->host_initiated ||
3355 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3356 cpuid_fault_enabled(vcpu)))
3357 return 1;
3358 vcpu->arch.msr_platform_info = data;
3359 break;
3360 case MSR_MISC_FEATURES_ENABLES:
3361 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3362 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3363 !supports_cpuid_fault(vcpu)))
3364 return 1;
3365 vcpu->arch.msr_misc_features_enables = data;
3366 break;
3367 default:
3368 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
3369 return xen_hvm_config(vcpu, data);
3370 if (kvm_pmu_is_valid_msr(vcpu, msr))
3371 return kvm_pmu_set_msr(vcpu, msr_info);
Olivier Deprez157378f2022-04-04 15:47:50 +02003372 return KVM_MSR_RET_INVALID;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003373 }
3374 return 0;
3375}
3376EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3377
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003378static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
3379{
3380 u64 data;
3381 u64 mcg_cap = vcpu->arch.mcg_cap;
3382 unsigned bank_num = mcg_cap & 0xff;
3383
3384 switch (msr) {
3385 case MSR_IA32_P5_MC_ADDR:
3386 case MSR_IA32_P5_MC_TYPE:
3387 data = 0;
3388 break;
3389 case MSR_IA32_MCG_CAP:
3390 data = vcpu->arch.mcg_cap;
3391 break;
3392 case MSR_IA32_MCG_CTL:
3393 if (!(mcg_cap & MCG_CTL_P) && !host)
3394 return 1;
3395 data = vcpu->arch.mcg_ctl;
3396 break;
3397 case MSR_IA32_MCG_STATUS:
3398 data = vcpu->arch.mcg_status;
3399 break;
3400 default:
3401 if (msr >= MSR_IA32_MC0_CTL &&
3402 msr < MSR_IA32_MCx_CTL(bank_num)) {
Olivier Deprez0e641232021-09-23 10:07:05 +02003403 u32 offset = array_index_nospec(
3404 msr - MSR_IA32_MC0_CTL,
3405 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3406
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003407 data = vcpu->arch.mce_banks[offset];
3408 break;
3409 }
3410 return 1;
3411 }
3412 *pdata = data;
3413 return 0;
3414}
3415
3416int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3417{
3418 switch (msr_info->index) {
3419 case MSR_IA32_PLATFORM_ID:
3420 case MSR_IA32_EBL_CR_POWERON:
3421 case MSR_IA32_DEBUGCTLMSR:
3422 case MSR_IA32_LASTBRANCHFROMIP:
3423 case MSR_IA32_LASTBRANCHTOIP:
3424 case MSR_IA32_LASTINTFROMIP:
3425 case MSR_IA32_LASTINTTOIP:
3426 case MSR_K8_SYSCFG:
3427 case MSR_K8_TSEG_ADDR:
3428 case MSR_K8_TSEG_MASK:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003429 case MSR_VM_HSAVE_PA:
3430 case MSR_K8_INT_PENDING_MSG:
3431 case MSR_AMD64_NB_CFG:
3432 case MSR_FAM10H_MMIO_CONF_BASE:
3433 case MSR_AMD64_BU_CFG2:
3434 case MSR_IA32_PERF_CTL:
3435 case MSR_AMD64_DC_CFG:
3436 case MSR_F15H_EX_CFG:
Olivier Deprez157378f2022-04-04 15:47:50 +02003437 /*
3438 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3439 * limit) MSRs. Just return 0, as we do not want to expose the host
3440 * data here. Do not conditionalize this on CPUID, as KVM does not do
3441 * so for existing CPU-specific MSRs.
3442 */
3443 case MSR_RAPL_POWER_UNIT:
3444 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3445 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3446 case MSR_PKG_ENERGY_STATUS: /* Total package */
3447 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003448 msr_info->data = 0;
3449 break;
3450 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
3451 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3452 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3453 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3454 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
3455 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
Olivier Deprez157378f2022-04-04 15:47:50 +02003456 return kvm_pmu_get_msr(vcpu, msr_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003457 msr_info->data = 0;
3458 break;
3459 case MSR_IA32_UCODE_REV:
3460 msr_info->data = vcpu->arch.microcode_version;
3461 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003462 case MSR_IA32_ARCH_CAPABILITIES:
3463 if (!msr_info->host_initiated &&
3464 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3465 return 1;
3466 msr_info->data = vcpu->arch.arch_capabilities;
3467 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003468 case MSR_IA32_PERF_CAPABILITIES:
3469 if (!msr_info->host_initiated &&
3470 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3471 return 1;
3472 msr_info->data = vcpu->arch.perf_capabilities;
3473 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003474 case MSR_IA32_POWER_CTL:
3475 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3476 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003477 case MSR_IA32_TSC: {
3478 /*
3479 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3480 * even when not intercepted. AMD manual doesn't explicitly
3481 * state this but appears to behave the same.
3482 *
3483 * On userspace reads and writes, however, we unconditionally
3484 * return L1's TSC value to ensure backwards-compatible
3485 * behavior for migration.
3486 */
3487 u64 tsc_offset = msr_info->host_initiated ? vcpu->arch.l1_tsc_offset :
3488 vcpu->arch.tsc_offset;
3489
3490 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + tsc_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003491 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02003492 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003493 case MSR_MTRRcap:
3494 case 0x200 ... 0x2ff:
3495 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3496 case 0xcd: /* fsb frequency */
3497 msr_info->data = 3;
3498 break;
3499 /*
3500 * MSR_EBC_FREQUENCY_ID
3501 * Conservative value valid for even the basic CPU models.
3502 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3503 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3504 * and 266MHz for model 3, or 4. Set Core Clock
3505 * Frequency to System Bus Frequency Ratio to 1 (bits
3506 * 31:24) even though these are only valid for CPU
3507 * models > 2, however guests may end up dividing or
3508 * multiplying by zero otherwise.
3509 */
3510 case MSR_EBC_FREQUENCY_ID:
3511 msr_info->data = 1 << 24;
3512 break;
3513 case MSR_IA32_APICBASE:
3514 msr_info->data = kvm_get_apic_base(vcpu);
3515 break;
Olivier Deprez0e641232021-09-23 10:07:05 +02003516 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003517 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003518 case MSR_IA32_TSCDEADLINE:
3519 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3520 break;
3521 case MSR_IA32_TSC_ADJUST:
3522 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3523 break;
3524 case MSR_IA32_MISC_ENABLE:
3525 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3526 break;
3527 case MSR_IA32_SMBASE:
3528 if (!msr_info->host_initiated)
3529 return 1;
3530 msr_info->data = vcpu->arch.smbase;
3531 break;
3532 case MSR_SMI_COUNT:
3533 msr_info->data = vcpu->arch.smi_count;
3534 break;
3535 case MSR_IA32_PERF_STATUS:
3536 /* TSC increment by tick */
3537 msr_info->data = 1000ULL;
3538 /* CPU multiplier */
3539 msr_info->data |= (((uint64_t)4ULL) << 40);
3540 break;
3541 case MSR_EFER:
3542 msr_info->data = vcpu->arch.efer;
3543 break;
3544 case MSR_KVM_WALL_CLOCK:
Olivier Deprez157378f2022-04-04 15:47:50 +02003545 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3546 return 1;
3547
3548 msr_info->data = vcpu->kvm->arch.wall_clock;
3549 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003550 case MSR_KVM_WALL_CLOCK_NEW:
Olivier Deprez157378f2022-04-04 15:47:50 +02003551 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3552 return 1;
3553
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003554 msr_info->data = vcpu->kvm->arch.wall_clock;
3555 break;
3556 case MSR_KVM_SYSTEM_TIME:
Olivier Deprez157378f2022-04-04 15:47:50 +02003557 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3558 return 1;
3559
3560 msr_info->data = vcpu->arch.time;
3561 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003562 case MSR_KVM_SYSTEM_TIME_NEW:
Olivier Deprez157378f2022-04-04 15:47:50 +02003563 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3564 return 1;
3565
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003566 msr_info->data = vcpu->arch.time;
3567 break;
3568 case MSR_KVM_ASYNC_PF_EN:
Olivier Deprez157378f2022-04-04 15:47:50 +02003569 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3570 return 1;
3571
3572 msr_info->data = vcpu->arch.apf.msr_en_val;
3573 break;
3574 case MSR_KVM_ASYNC_PF_INT:
3575 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3576 return 1;
3577
3578 msr_info->data = vcpu->arch.apf.msr_int_val;
3579 break;
3580 case MSR_KVM_ASYNC_PF_ACK:
3581 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3582 return 1;
3583
3584 msr_info->data = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003585 break;
3586 case MSR_KVM_STEAL_TIME:
Olivier Deprez157378f2022-04-04 15:47:50 +02003587 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3588 return 1;
3589
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003590 msr_info->data = vcpu->arch.st.msr_val;
3591 break;
3592 case MSR_KVM_PV_EOI_EN:
Olivier Deprez157378f2022-04-04 15:47:50 +02003593 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3594 return 1;
3595
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003596 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3597 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003598 case MSR_KVM_POLL_CONTROL:
Olivier Deprez157378f2022-04-04 15:47:50 +02003599 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3600 return 1;
3601
David Brazdil0f672f62019-12-10 10:32:29 +00003602 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3603 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003604 case MSR_IA32_P5_MC_ADDR:
3605 case MSR_IA32_P5_MC_TYPE:
3606 case MSR_IA32_MCG_CAP:
3607 case MSR_IA32_MCG_CTL:
3608 case MSR_IA32_MCG_STATUS:
3609 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3610 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3611 msr_info->host_initiated);
Olivier Deprez157378f2022-04-04 15:47:50 +02003612 case MSR_IA32_XSS:
3613 if (!msr_info->host_initiated &&
3614 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3615 return 1;
3616 msr_info->data = vcpu->arch.ia32_xss;
3617 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003618 case MSR_K7_CLK_CTL:
3619 /*
3620 * Provide expected ramp-up count for K7. All other
3621 * are set to zero, indicating minimum divisors for
3622 * every field.
3623 *
3624 * This prevents guest kernels on AMD host with CPU
3625 * type 6, model 8 and higher from exploding due to
3626 * the rdmsr failing.
3627 */
3628 msr_info->data = 0x20000000;
3629 break;
3630 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
Olivier Deprez157378f2022-04-04 15:47:50 +02003631 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3632 case HV_X64_MSR_SYNDBG_OPTIONS:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003633 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3634 case HV_X64_MSR_CRASH_CTL:
3635 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3636 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3637 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3638 case HV_X64_MSR_TSC_EMULATION_STATUS:
3639 return kvm_hv_get_msr_common(vcpu,
3640 msr_info->index, &msr_info->data,
3641 msr_info->host_initiated);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003642 case MSR_IA32_BBL_CR_CTL3:
3643 /* This legacy MSR exists but isn't fully documented in current
3644 * silicon. It is however accessed by winxp in very narrow
3645 * scenarios where it sets bit #19, itself documented as
3646 * a "reserved" bit. Best effort attempt to source coherent
3647 * read data here should the balance of the register be
3648 * interpreted by the guest:
3649 *
3650 * L2 cache control register 3: 64GB range, 256KB size,
3651 * enabled, latency 0x1, configured
3652 */
3653 msr_info->data = 0xbe702111;
3654 break;
3655 case MSR_AMD64_OSVW_ID_LENGTH:
3656 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3657 return 1;
3658 msr_info->data = vcpu->arch.osvw.length;
3659 break;
3660 case MSR_AMD64_OSVW_STATUS:
3661 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3662 return 1;
3663 msr_info->data = vcpu->arch.osvw.status;
3664 break;
3665 case MSR_PLATFORM_INFO:
3666 if (!msr_info->host_initiated &&
3667 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3668 return 1;
3669 msr_info->data = vcpu->arch.msr_platform_info;
3670 break;
3671 case MSR_MISC_FEATURES_ENABLES:
3672 msr_info->data = vcpu->arch.msr_misc_features_enables;
3673 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003674 case MSR_K7_HWCR:
3675 msr_info->data = vcpu->arch.msr_hwcr;
3676 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003677 default:
3678 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
Olivier Deprez157378f2022-04-04 15:47:50 +02003679 return kvm_pmu_get_msr(vcpu, msr_info);
3680 return KVM_MSR_RET_INVALID;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003681 }
3682 return 0;
3683}
3684EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3685
3686/*
3687 * Read or write a bunch of msrs. All parameters are kernel addresses.
3688 *
3689 * @return number of msrs set successfully.
3690 */
3691static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3692 struct kvm_msr_entry *entries,
3693 int (*do_msr)(struct kvm_vcpu *vcpu,
3694 unsigned index, u64 *data))
3695{
3696 int i;
3697
3698 for (i = 0; i < msrs->nmsrs; ++i)
3699 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3700 break;
3701
3702 return i;
3703}
3704
3705/*
3706 * Read or write a bunch of msrs. Parameters are user addresses.
3707 *
3708 * @return number of msrs set successfully.
3709 */
3710static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3711 int (*do_msr)(struct kvm_vcpu *vcpu,
3712 unsigned index, u64 *data),
3713 int writeback)
3714{
3715 struct kvm_msrs msrs;
3716 struct kvm_msr_entry *entries;
3717 int r, n;
3718 unsigned size;
3719
3720 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00003721 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003722 goto out;
3723
3724 r = -E2BIG;
3725 if (msrs.nmsrs >= MAX_IO_MSRS)
3726 goto out;
3727
3728 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3729 entries = memdup_user(user_msrs->entries, size);
3730 if (IS_ERR(entries)) {
3731 r = PTR_ERR(entries);
3732 goto out;
3733 }
3734
3735 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3736 if (r < 0)
3737 goto out_free;
3738
3739 r = -EFAULT;
3740 if (writeback && copy_to_user(user_msrs->entries, entries, size))
3741 goto out_free;
3742
3743 r = n;
3744
3745out_free:
3746 kfree(entries);
3747out:
3748 return r;
3749}
3750
3751static inline bool kvm_can_mwait_in_guest(void)
3752{
3753 return boot_cpu_has(X86_FEATURE_MWAIT) &&
3754 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3755 boot_cpu_has(X86_FEATURE_ARAT);
3756}
3757
3758int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3759{
3760 int r = 0;
3761
3762 switch (ext) {
3763 case KVM_CAP_IRQCHIP:
3764 case KVM_CAP_HLT:
3765 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3766 case KVM_CAP_SET_TSS_ADDR:
3767 case KVM_CAP_EXT_CPUID:
3768 case KVM_CAP_EXT_EMUL_CPUID:
3769 case KVM_CAP_CLOCKSOURCE:
3770 case KVM_CAP_PIT:
3771 case KVM_CAP_NOP_IO_DELAY:
3772 case KVM_CAP_MP_STATE:
3773 case KVM_CAP_SYNC_MMU:
3774 case KVM_CAP_USER_NMI:
3775 case KVM_CAP_REINJECT_CONTROL:
3776 case KVM_CAP_IRQ_INJECT_STATUS:
3777 case KVM_CAP_IOEVENTFD:
3778 case KVM_CAP_IOEVENTFD_NO_LENGTH:
3779 case KVM_CAP_PIT2:
3780 case KVM_CAP_PIT_STATE2:
3781 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3782 case KVM_CAP_XEN_HVM:
3783 case KVM_CAP_VCPU_EVENTS:
3784 case KVM_CAP_HYPERV:
3785 case KVM_CAP_HYPERV_VAPIC:
3786 case KVM_CAP_HYPERV_SPIN:
3787 case KVM_CAP_HYPERV_SYNIC:
3788 case KVM_CAP_HYPERV_SYNIC2:
3789 case KVM_CAP_HYPERV_VP_INDEX:
3790 case KVM_CAP_HYPERV_EVENTFD:
3791 case KVM_CAP_HYPERV_TLBFLUSH:
David Brazdil0f672f62019-12-10 10:32:29 +00003792 case KVM_CAP_HYPERV_SEND_IPI:
3793 case KVM_CAP_HYPERV_CPUID:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003794 case KVM_CAP_PCI_SEGMENT:
3795 case KVM_CAP_DEBUGREGS:
3796 case KVM_CAP_X86_ROBUST_SINGLESTEP:
3797 case KVM_CAP_XSAVE:
3798 case KVM_CAP_ASYNC_PF:
Olivier Deprez157378f2022-04-04 15:47:50 +02003799 case KVM_CAP_ASYNC_PF_INT:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003800 case KVM_CAP_GET_TSC_KHZ:
3801 case KVM_CAP_KVMCLOCK_CTRL:
3802 case KVM_CAP_READONLY_MEM:
3803 case KVM_CAP_HYPERV_TIME:
3804 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3805 case KVM_CAP_TSC_DEADLINE_TIMER:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003806 case KVM_CAP_DISABLE_QUIRKS:
3807 case KVM_CAP_SET_BOOT_CPU_ID:
3808 case KVM_CAP_SPLIT_IRQCHIP:
3809 case KVM_CAP_IMMEDIATE_EXIT:
David Brazdil0f672f62019-12-10 10:32:29 +00003810 case KVM_CAP_PMU_EVENT_FILTER:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003811 case KVM_CAP_GET_MSR_FEATURES:
3812 case KVM_CAP_MSR_PLATFORM_INFO:
David Brazdil0f672f62019-12-10 10:32:29 +00003813 case KVM_CAP_EXCEPTION_PAYLOAD:
Olivier Deprez157378f2022-04-04 15:47:50 +02003814 case KVM_CAP_SET_GUEST_DEBUG:
3815 case KVM_CAP_LAST_CPU:
3816 case KVM_CAP_X86_USER_SPACE_MSR:
3817 case KVM_CAP_X86_MSR_FILTER:
3818 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003819 r = 1;
3820 break;
3821 case KVM_CAP_SYNC_REGS:
3822 r = KVM_SYNC_X86_VALID_FIELDS;
3823 break;
3824 case KVM_CAP_ADJUST_CLOCK:
3825 r = KVM_CLOCK_TSC_STABLE;
3826 break;
3827 case KVM_CAP_X86_DISABLE_EXITS:
David Brazdil0f672f62019-12-10 10:32:29 +00003828 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3829 KVM_X86_DISABLE_EXITS_CSTATE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003830 if(kvm_can_mwait_in_guest())
3831 r |= KVM_X86_DISABLE_EXITS_MWAIT;
3832 break;
3833 case KVM_CAP_X86_SMM:
3834 /* SMBASE is usually relocated above 1M on modern chipsets,
3835 * and SMM handlers might indeed rely on 4G segment limits,
3836 * so do not report SMM to be available if real mode is
3837 * emulated via vm86 mode. Still, do not go to great lengths
3838 * to avoid userspace's usage of the feature, because it is a
3839 * fringe case that is not enabled except via specific settings
3840 * of the module parameters.
3841 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003842 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003843 break;
3844 case KVM_CAP_VAPIC:
Olivier Deprez157378f2022-04-04 15:47:50 +02003845 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003846 break;
3847 case KVM_CAP_NR_VCPUS:
3848 r = KVM_SOFT_MAX_VCPUS;
3849 break;
3850 case KVM_CAP_MAX_VCPUS:
3851 r = KVM_MAX_VCPUS;
3852 break;
David Brazdil0f672f62019-12-10 10:32:29 +00003853 case KVM_CAP_MAX_VCPU_ID:
3854 r = KVM_MAX_VCPU_ID;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003855 break;
3856 case KVM_CAP_PV_MMU: /* obsolete */
3857 r = 0;
3858 break;
3859 case KVM_CAP_MCE:
3860 r = KVM_MAX_MCE_BANKS;
3861 break;
3862 case KVM_CAP_XCRS:
3863 r = boot_cpu_has(X86_FEATURE_XSAVE);
3864 break;
3865 case KVM_CAP_TSC_CONTROL:
3866 r = kvm_has_tsc_control;
3867 break;
3868 case KVM_CAP_X2APIC_API:
3869 r = KVM_X2APIC_API_VALID_FLAGS;
3870 break;
3871 case KVM_CAP_NESTED_STATE:
Olivier Deprez157378f2022-04-04 15:47:50 +02003872 r = kvm_x86_ops.nested_ops->get_state ?
3873 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
David Brazdil0f672f62019-12-10 10:32:29 +00003874 break;
3875 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
Olivier Deprez157378f2022-04-04 15:47:50 +02003876 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00003877 break;
3878 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
Olivier Deprez157378f2022-04-04 15:47:50 +02003879 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3880 break;
3881 case KVM_CAP_SMALLER_MAXPHYADDR:
3882 r = (int) allow_smaller_maxphyaddr;
3883 break;
3884 case KVM_CAP_STEAL_TIME:
3885 r = sched_info_on();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003886 break;
3887 default:
3888 break;
3889 }
3890 return r;
3891
3892}
3893
3894long kvm_arch_dev_ioctl(struct file *filp,
3895 unsigned int ioctl, unsigned long arg)
3896{
3897 void __user *argp = (void __user *)arg;
3898 long r;
3899
3900 switch (ioctl) {
3901 case KVM_GET_MSR_INDEX_LIST: {
3902 struct kvm_msr_list __user *user_msr_list = argp;
3903 struct kvm_msr_list msr_list;
3904 unsigned n;
3905
3906 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00003907 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003908 goto out;
3909 n = msr_list.nmsrs;
3910 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
David Brazdil0f672f62019-12-10 10:32:29 +00003911 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003912 goto out;
3913 r = -E2BIG;
3914 if (n < msr_list.nmsrs)
3915 goto out;
3916 r = -EFAULT;
3917 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3918 num_msrs_to_save * sizeof(u32)))
3919 goto out;
3920 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3921 &emulated_msrs,
3922 num_emulated_msrs * sizeof(u32)))
3923 goto out;
3924 r = 0;
3925 break;
3926 }
3927 case KVM_GET_SUPPORTED_CPUID:
3928 case KVM_GET_EMULATED_CPUID: {
3929 struct kvm_cpuid2 __user *cpuid_arg = argp;
3930 struct kvm_cpuid2 cpuid;
3931
3932 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00003933 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003934 goto out;
3935
3936 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3937 ioctl);
3938 if (r)
3939 goto out;
3940
3941 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00003942 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003943 goto out;
3944 r = 0;
3945 break;
3946 }
Olivier Deprez157378f2022-04-04 15:47:50 +02003947 case KVM_X86_GET_MCE_CAP_SUPPORTED:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003948 r = -EFAULT;
3949 if (copy_to_user(argp, &kvm_mce_cap_supported,
3950 sizeof(kvm_mce_cap_supported)))
3951 goto out;
3952 r = 0;
3953 break;
3954 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3955 struct kvm_msr_list __user *user_msr_list = argp;
3956 struct kvm_msr_list msr_list;
3957 unsigned int n;
3958
3959 r = -EFAULT;
3960 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3961 goto out;
3962 n = msr_list.nmsrs;
3963 msr_list.nmsrs = num_msr_based_features;
3964 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3965 goto out;
3966 r = -E2BIG;
3967 if (n < msr_list.nmsrs)
3968 goto out;
3969 r = -EFAULT;
3970 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3971 num_msr_based_features * sizeof(u32)))
3972 goto out;
3973 r = 0;
3974 break;
3975 }
3976 case KVM_GET_MSRS:
3977 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3978 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003979 default:
3980 r = -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02003981 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003982 }
3983out:
3984 return r;
3985}
3986
3987static void wbinvd_ipi(void *garbage)
3988{
3989 wbinvd();
3990}
3991
3992static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3993{
3994 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3995}
3996
3997void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3998{
3999 /* Address WBINVD may be executed by guest */
4000 if (need_emulate_wbinvd(vcpu)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004001 if (kvm_x86_ops.has_wbinvd_exit())
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004002 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4003 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4004 smp_call_function_single(vcpu->cpu,
4005 wbinvd_ipi, NULL, 1);
4006 }
4007
Olivier Deprez157378f2022-04-04 15:47:50 +02004008 kvm_x86_ops.vcpu_load(vcpu, cpu);
4009
4010 /* Save host pkru register if supported */
4011 vcpu->arch.host_pkru = read_pkru();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004012
4013 /* Apply any externally detected TSC adjustments (due to suspend) */
4014 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4015 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4016 vcpu->arch.tsc_offset_adjustment = 0;
4017 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4018 }
4019
4020 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
4021 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
4022 rdtsc() - vcpu->arch.last_host_tsc;
4023 if (tsc_delta < 0)
4024 mark_tsc_unstable("KVM discovered backwards TSC");
4025
4026 if (kvm_check_tsc_unstable()) {
4027 u64 offset = kvm_compute_tsc_offset(vcpu,
4028 vcpu->arch.last_guest_tsc);
4029 kvm_vcpu_write_tsc_offset(vcpu, offset);
4030 vcpu->arch.tsc_catchup = 1;
4031 }
4032
4033 if (kvm_lapic_hv_timer_in_use(vcpu))
4034 kvm_lapic_restart_hv_timer(vcpu);
4035
4036 /*
4037 * On a host with synchronized TSC, there is no need to update
4038 * kvmclock on vcpu->cpu migration
4039 */
4040 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
4041 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
4042 if (vcpu->cpu != cpu)
4043 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
4044 vcpu->cpu = cpu;
4045 }
4046
4047 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4048}
4049
4050static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4051{
Olivier Deprez0e641232021-09-23 10:07:05 +02004052 struct kvm_host_map map;
4053 struct kvm_steal_time *st;
4054
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004055 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4056 return;
4057
Olivier Deprez0e641232021-09-23 10:07:05 +02004058 if (vcpu->arch.st.preempted)
4059 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004060
Olivier Deprez0e641232021-09-23 10:07:05 +02004061 if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
4062 &vcpu->arch.st.cache, true))
4063 return;
4064
4065 st = map.hva +
4066 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
4067
4068 st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4069
4070 kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004071}
4072
4073void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4074{
4075 int idx;
4076
4077 if (vcpu->preempted)
Olivier Deprez157378f2022-04-04 15:47:50 +02004078 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004079
4080 /*
4081 * Disable page faults because we're in atomic context here.
4082 * kvm_write_guest_offset_cached() would call might_fault()
4083 * that relies on pagefault_disable() to tell if there's a
4084 * bug. NOTE: the write to guest memory may not go through if
4085 * during postcopy live migration or if there's heavy guest
4086 * paging.
4087 */
4088 pagefault_disable();
4089 /*
4090 * kvm_memslots() will be called by
4091 * kvm_write_guest_offset_cached() so take the srcu lock.
4092 */
4093 idx = srcu_read_lock(&vcpu->kvm->srcu);
4094 kvm_steal_time_set_preempted(vcpu);
4095 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4096 pagefault_enable();
Olivier Deprez157378f2022-04-04 15:47:50 +02004097 kvm_x86_ops.vcpu_put(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004098 vcpu->arch.last_host_tsc = rdtsc();
4099 /*
4100 * If userspace has set any breakpoints or watchpoints, dr6 is restored
4101 * on every vmexit, but if not, we might have a stale dr6 from the
4102 * guest. do_debug expects dr6 to be cleared after it runs, do the same.
4103 */
4104 set_debugreg(0, 6);
4105}
4106
4107static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4108 struct kvm_lapic_state *s)
4109{
4110 if (vcpu->arch.apicv_active)
Olivier Deprez157378f2022-04-04 15:47:50 +02004111 kvm_x86_ops.sync_pir_to_irr(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004112
4113 return kvm_apic_get_state(vcpu, s);
4114}
4115
4116static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4117 struct kvm_lapic_state *s)
4118{
4119 int r;
4120
4121 r = kvm_apic_set_state(vcpu, s);
4122 if (r)
4123 return r;
4124 update_cr8_intercept(vcpu);
4125
4126 return 0;
4127}
4128
4129static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4130{
Olivier Deprez0e641232021-09-23 10:07:05 +02004131 /*
4132 * We can accept userspace's request for interrupt injection
4133 * as long as we have a place to store the interrupt number.
4134 * The actual injection will happen when the CPU is able to
4135 * deliver the interrupt.
4136 */
4137 if (kvm_cpu_has_extint(vcpu))
4138 return false;
4139
4140 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004141 return (!lapic_in_kernel(vcpu) ||
4142 kvm_apic_accept_pic_intr(vcpu));
4143}
4144
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004145static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4146{
Olivier Deprez0e641232021-09-23 10:07:05 +02004147 /*
4148 * Do not cause an interrupt window exit if an exception
4149 * is pending or an event needs reinjection; userspace
4150 * might want to inject the interrupt manually using KVM_SET_REGS
4151 * or KVM_SET_SREGS. For that to work, we must be at an
4152 * instruction boundary and with no events half-injected.
4153 */
4154 return (kvm_arch_interrupt_allowed(vcpu) &&
4155 kvm_cpu_accept_dm_intr(vcpu) &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004156 !kvm_event_needs_reinjection(vcpu) &&
Olivier Deprez0e641232021-09-23 10:07:05 +02004157 !vcpu->arch.exception.pending);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004158}
4159
4160static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4161 struct kvm_interrupt *irq)
4162{
4163 if (irq->irq >= KVM_NR_INTERRUPTS)
4164 return -EINVAL;
4165
4166 if (!irqchip_in_kernel(vcpu->kvm)) {
4167 kvm_queue_interrupt(vcpu, irq->irq, false);
4168 kvm_make_request(KVM_REQ_EVENT, vcpu);
4169 return 0;
4170 }
4171
4172 /*
4173 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4174 * fail for in-kernel 8259.
4175 */
4176 if (pic_in_kernel(vcpu->kvm))
4177 return -ENXIO;
4178
4179 if (vcpu->arch.pending_external_vector != -1)
4180 return -EEXIST;
4181
4182 vcpu->arch.pending_external_vector = irq->irq;
4183 kvm_make_request(KVM_REQ_EVENT, vcpu);
4184 return 0;
4185}
4186
4187static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4188{
4189 kvm_inject_nmi(vcpu);
4190
4191 return 0;
4192}
4193
4194static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4195{
4196 kvm_make_request(KVM_REQ_SMI, vcpu);
4197
4198 return 0;
4199}
4200
4201static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4202 struct kvm_tpr_access_ctl *tac)
4203{
4204 if (tac->flags)
4205 return -EINVAL;
4206 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4207 return 0;
4208}
4209
4210static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4211 u64 mcg_cap)
4212{
4213 int r;
4214 unsigned bank_num = mcg_cap & 0xff, bank;
4215
4216 r = -EINVAL;
Olivier Deprez0e641232021-09-23 10:07:05 +02004217 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004218 goto out;
4219 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
4220 goto out;
4221 r = 0;
4222 vcpu->arch.mcg_cap = mcg_cap;
4223 /* Init IA32_MCG_CTL to all 1s */
4224 if (mcg_cap & MCG_CTL_P)
4225 vcpu->arch.mcg_ctl = ~(u64)0;
4226 /* Init IA32_MCi_CTL to all 1s */
4227 for (bank = 0; bank < bank_num; bank++)
4228 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
4229
Olivier Deprez157378f2022-04-04 15:47:50 +02004230 kvm_x86_ops.setup_mce(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004231out:
4232 return r;
4233}
4234
4235static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4236 struct kvm_x86_mce *mce)
4237{
4238 u64 mcg_cap = vcpu->arch.mcg_cap;
4239 unsigned bank_num = mcg_cap & 0xff;
4240 u64 *banks = vcpu->arch.mce_banks;
4241
4242 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4243 return -EINVAL;
4244 /*
4245 * if IA32_MCG_CTL is not all 1s, the uncorrected error
4246 * reporting is disabled
4247 */
4248 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4249 vcpu->arch.mcg_ctl != ~(u64)0)
4250 return 0;
4251 banks += 4 * mce->bank;
4252 /*
4253 * if IA32_MCi_CTL is not all 1s, the uncorrected error
4254 * reporting is disabled for the bank
4255 */
4256 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4257 return 0;
4258 if (mce->status & MCI_STATUS_UC) {
4259 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
4260 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
4261 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4262 return 0;
4263 }
4264 if (banks[1] & MCI_STATUS_VAL)
4265 mce->status |= MCI_STATUS_OVER;
4266 banks[2] = mce->addr;
4267 banks[3] = mce->misc;
4268 vcpu->arch.mcg_status = mce->mcg_status;
4269 banks[1] = mce->status;
4270 kvm_queue_exception(vcpu, MC_VECTOR);
4271 } else if (!(banks[1] & MCI_STATUS_VAL)
4272 || !(banks[1] & MCI_STATUS_UC)) {
4273 if (banks[1] & MCI_STATUS_VAL)
4274 mce->status |= MCI_STATUS_OVER;
4275 banks[2] = mce->addr;
4276 banks[3] = mce->misc;
4277 banks[1] = mce->status;
4278 } else
4279 banks[1] |= MCI_STATUS_OVER;
4280 return 0;
4281}
4282
4283static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4284 struct kvm_vcpu_events *events)
4285{
4286 process_nmi(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00004287
Olivier Deprez0e641232021-09-23 10:07:05 +02004288 if (kvm_check_request(KVM_REQ_SMI, vcpu))
4289 process_smi(vcpu);
4290
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004291 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02004292 * In guest mode, payload delivery should be deferred,
4293 * so that the L1 hypervisor can intercept #PF before
4294 * CR2 is modified (or intercept #DB before DR6 is
4295 * modified under nVMX). Unless the per-VM capability,
4296 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4297 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4298 * opportunistically defer the exception payload, deliver it if the
4299 * capability hasn't been requested before processing a
4300 * KVM_GET_VCPU_EVENTS.
4301 */
4302 if (!vcpu->kvm->arch.exception_payload_enabled &&
4303 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4304 kvm_deliver_exception_payload(vcpu);
4305
4306 /*
David Brazdil0f672f62019-12-10 10:32:29 +00004307 * The API doesn't provide the instruction length for software
4308 * exceptions, so don't report them. As long as the guest RIP
4309 * isn't advanced, we should expect to encounter the exception
4310 * again.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004311 */
David Brazdil0f672f62019-12-10 10:32:29 +00004312 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4313 events->exception.injected = 0;
4314 events->exception.pending = 0;
4315 } else {
4316 events->exception.injected = vcpu->arch.exception.injected;
4317 events->exception.pending = vcpu->arch.exception.pending;
4318 /*
4319 * For ABI compatibility, deliberately conflate
4320 * pending and injected exceptions when
4321 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4322 */
4323 if (!vcpu->kvm->arch.exception_payload_enabled)
4324 events->exception.injected |=
4325 vcpu->arch.exception.pending;
4326 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004327 events->exception.nr = vcpu->arch.exception.nr;
4328 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004329 events->exception.error_code = vcpu->arch.exception.error_code;
David Brazdil0f672f62019-12-10 10:32:29 +00004330 events->exception_has_payload = vcpu->arch.exception.has_payload;
4331 events->exception_payload = vcpu->arch.exception.payload;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004332
4333 events->interrupt.injected =
4334 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4335 events->interrupt.nr = vcpu->arch.interrupt.nr;
4336 events->interrupt.soft = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02004337 events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004338
4339 events->nmi.injected = vcpu->arch.nmi_injected;
4340 events->nmi.pending = vcpu->arch.nmi_pending != 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02004341 events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004342 events->nmi.pad = 0;
4343
4344 events->sipi_vector = 0; /* never valid when reporting to user space */
4345
4346 events->smi.smm = is_smm(vcpu);
4347 events->smi.pending = vcpu->arch.smi_pending;
4348 events->smi.smm_inside_nmi =
4349 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4350 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4351
4352 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4353 | KVM_VCPUEVENT_VALID_SHADOW
4354 | KVM_VCPUEVENT_VALID_SMM);
David Brazdil0f672f62019-12-10 10:32:29 +00004355 if (vcpu->kvm->arch.exception_payload_enabled)
4356 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4357
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004358 memset(&events->reserved, 0, sizeof(events->reserved));
4359}
4360
David Brazdil0f672f62019-12-10 10:32:29 +00004361static void kvm_smm_changed(struct kvm_vcpu *vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004362
4363static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4364 struct kvm_vcpu_events *events)
4365{
4366 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4367 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4368 | KVM_VCPUEVENT_VALID_SHADOW
David Brazdil0f672f62019-12-10 10:32:29 +00004369 | KVM_VCPUEVENT_VALID_SMM
4370 | KVM_VCPUEVENT_VALID_PAYLOAD))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004371 return -EINVAL;
4372
David Brazdil0f672f62019-12-10 10:32:29 +00004373 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4374 if (!vcpu->kvm->arch.exception_payload_enabled)
4375 return -EINVAL;
4376 if (events->exception.pending)
4377 events->exception.injected = 0;
4378 else
4379 events->exception_has_payload = 0;
4380 } else {
4381 events->exception.pending = 0;
4382 events->exception_has_payload = 0;
4383 }
4384
4385 if ((events->exception.injected || events->exception.pending) &&
4386 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004387 return -EINVAL;
4388
4389 /* INITs are latched while in SMM */
4390 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4391 (events->smi.smm || events->smi.pending) &&
4392 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4393 return -EINVAL;
4394
4395 process_nmi(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00004396 vcpu->arch.exception.injected = events->exception.injected;
4397 vcpu->arch.exception.pending = events->exception.pending;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004398 vcpu->arch.exception.nr = events->exception.nr;
4399 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4400 vcpu->arch.exception.error_code = events->exception.error_code;
David Brazdil0f672f62019-12-10 10:32:29 +00004401 vcpu->arch.exception.has_payload = events->exception_has_payload;
4402 vcpu->arch.exception.payload = events->exception_payload;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004403
4404 vcpu->arch.interrupt.injected = events->interrupt.injected;
4405 vcpu->arch.interrupt.nr = events->interrupt.nr;
4406 vcpu->arch.interrupt.soft = events->interrupt.soft;
4407 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
Olivier Deprez157378f2022-04-04 15:47:50 +02004408 kvm_x86_ops.set_interrupt_shadow(vcpu,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004409 events->interrupt.shadow);
4410
4411 vcpu->arch.nmi_injected = events->nmi.injected;
4412 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4413 vcpu->arch.nmi_pending = events->nmi.pending;
Olivier Deprez157378f2022-04-04 15:47:50 +02004414 kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004415
4416 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4417 lapic_in_kernel(vcpu))
4418 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4419
4420 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
David Brazdil0f672f62019-12-10 10:32:29 +00004421 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4422 if (events->smi.smm)
4423 vcpu->arch.hflags |= HF_SMM_MASK;
4424 else
4425 vcpu->arch.hflags &= ~HF_SMM_MASK;
Olivier Deprez157378f2022-04-04 15:47:50 +02004426
4427 kvm_x86_ops.nested_ops->leave_nested(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00004428 kvm_smm_changed(vcpu);
4429 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004430
4431 vcpu->arch.smi_pending = events->smi.pending;
4432
4433 if (events->smi.smm) {
4434 if (events->smi.smm_inside_nmi)
4435 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4436 else
4437 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
Olivier Deprez157378f2022-04-04 15:47:50 +02004438 }
4439
4440 if (lapic_in_kernel(vcpu)) {
4441 if (events->smi.latched_init)
4442 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4443 else
4444 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004445 }
4446 }
4447
4448 kvm_make_request(KVM_REQ_EVENT, vcpu);
4449
4450 return 0;
4451}
4452
4453static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4454 struct kvm_debugregs *dbgregs)
4455{
4456 unsigned long val;
4457
4458 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4459 kvm_get_dr(vcpu, 6, &val);
4460 dbgregs->dr6 = val;
4461 dbgregs->dr7 = vcpu->arch.dr7;
4462 dbgregs->flags = 0;
4463 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4464}
4465
4466static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4467 struct kvm_debugregs *dbgregs)
4468{
4469 if (dbgregs->flags)
4470 return -EINVAL;
4471
4472 if (dbgregs->dr6 & ~0xffffffffull)
4473 return -EINVAL;
4474 if (dbgregs->dr7 & ~0xffffffffull)
4475 return -EINVAL;
4476
4477 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4478 kvm_update_dr0123(vcpu);
4479 vcpu->arch.dr6 = dbgregs->dr6;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004480 vcpu->arch.dr7 = dbgregs->dr7;
4481 kvm_update_dr7(vcpu);
4482
4483 return 0;
4484}
4485
4486#define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4487
4488static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4489{
David Brazdil0f672f62019-12-10 10:32:29 +00004490 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004491 u64 xstate_bv = xsave->header.xfeatures;
4492 u64 valid;
4493
4494 /*
4495 * Copy legacy XSAVE area, to avoid complications with CPUID
4496 * leaves 0 and 1 in the loop below.
4497 */
4498 memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4499
4500 /* Set XSTATE_BV */
4501 xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4502 *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4503
4504 /*
4505 * Copy each region from the possibly compacted offset to the
4506 * non-compacted offset.
4507 */
4508 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4509 while (valid) {
David Brazdil0f672f62019-12-10 10:32:29 +00004510 u64 xfeature_mask = valid & -valid;
4511 int xfeature_nr = fls64(xfeature_mask) - 1;
4512 void *src = get_xsave_addr(xsave, xfeature_nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004513
4514 if (src) {
4515 u32 size, offset, ecx, edx;
David Brazdil0f672f62019-12-10 10:32:29 +00004516 cpuid_count(XSTATE_CPUID, xfeature_nr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004517 &size, &offset, &ecx, &edx);
David Brazdil0f672f62019-12-10 10:32:29 +00004518 if (xfeature_nr == XFEATURE_PKRU)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004519 memcpy(dest + offset, &vcpu->arch.pkru,
4520 sizeof(vcpu->arch.pkru));
4521 else
4522 memcpy(dest + offset, src, size);
4523
4524 }
4525
David Brazdil0f672f62019-12-10 10:32:29 +00004526 valid -= xfeature_mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004527 }
4528}
4529
4530static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4531{
David Brazdil0f672f62019-12-10 10:32:29 +00004532 struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004533 u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4534 u64 valid;
4535
4536 /*
4537 * Copy legacy XSAVE area, to avoid complications with CPUID
4538 * leaves 0 and 1 in the loop below.
4539 */
4540 memcpy(xsave, src, XSAVE_HDR_OFFSET);
4541
4542 /* Set XSTATE_BV and possibly XCOMP_BV. */
4543 xsave->header.xfeatures = xstate_bv;
4544 if (boot_cpu_has(X86_FEATURE_XSAVES))
4545 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4546
4547 /*
4548 * Copy each region from the non-compacted offset to the
4549 * possibly compacted offset.
4550 */
4551 valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4552 while (valid) {
David Brazdil0f672f62019-12-10 10:32:29 +00004553 u64 xfeature_mask = valid & -valid;
4554 int xfeature_nr = fls64(xfeature_mask) - 1;
4555 void *dest = get_xsave_addr(xsave, xfeature_nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004556
4557 if (dest) {
4558 u32 size, offset, ecx, edx;
David Brazdil0f672f62019-12-10 10:32:29 +00004559 cpuid_count(XSTATE_CPUID, xfeature_nr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004560 &size, &offset, &ecx, &edx);
David Brazdil0f672f62019-12-10 10:32:29 +00004561 if (xfeature_nr == XFEATURE_PKRU)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004562 memcpy(&vcpu->arch.pkru, src + offset,
4563 sizeof(vcpu->arch.pkru));
4564 else
4565 memcpy(dest, src + offset, size);
4566 }
4567
David Brazdil0f672f62019-12-10 10:32:29 +00004568 valid -= xfeature_mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004569 }
4570}
4571
4572static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4573 struct kvm_xsave *guest_xsave)
4574{
4575 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4576 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4577 fill_xsave((u8 *) guest_xsave->region, vcpu);
4578 } else {
4579 memcpy(guest_xsave->region,
David Brazdil0f672f62019-12-10 10:32:29 +00004580 &vcpu->arch.guest_fpu->state.fxsave,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004581 sizeof(struct fxregs_state));
4582 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4583 XFEATURE_MASK_FPSSE;
4584 }
4585}
4586
4587#define XSAVE_MXCSR_OFFSET 24
4588
4589static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4590 struct kvm_xsave *guest_xsave)
4591{
4592 u64 xstate_bv =
4593 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4594 u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4595
4596 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4597 /*
4598 * Here we allow setting states that are not present in
4599 * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
4600 * with old userspace.
4601 */
Olivier Deprez157378f2022-04-04 15:47:50 +02004602 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004603 return -EINVAL;
4604 load_xsave(vcpu, (u8 *)guest_xsave->region);
4605 } else {
4606 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4607 mxcsr & ~mxcsr_feature_mask)
4608 return -EINVAL;
David Brazdil0f672f62019-12-10 10:32:29 +00004609 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004610 guest_xsave->region, sizeof(struct fxregs_state));
4611 }
4612 return 0;
4613}
4614
4615static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4616 struct kvm_xcrs *guest_xcrs)
4617{
4618 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4619 guest_xcrs->nr_xcrs = 0;
4620 return;
4621 }
4622
4623 guest_xcrs->nr_xcrs = 1;
4624 guest_xcrs->flags = 0;
4625 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4626 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4627}
4628
4629static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4630 struct kvm_xcrs *guest_xcrs)
4631{
4632 int i, r = 0;
4633
4634 if (!boot_cpu_has(X86_FEATURE_XSAVE))
4635 return -EINVAL;
4636
4637 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4638 return -EINVAL;
4639
4640 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4641 /* Only support XCR0 currently */
4642 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4643 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4644 guest_xcrs->xcrs[i].value);
4645 break;
4646 }
4647 if (r)
4648 r = -EINVAL;
4649 return r;
4650}
4651
4652/*
4653 * kvm_set_guest_paused() indicates to the guest kernel that it has been
4654 * stopped by the hypervisor. This function will be called from the host only.
4655 * EINVAL is returned when the host attempts to set the flag for a guest that
4656 * does not support pv clocks.
4657 */
4658static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4659{
4660 if (!vcpu->arch.pv_time_enabled)
4661 return -EINVAL;
4662 vcpu->arch.pvclock_set_guest_stopped_request = true;
4663 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4664 return 0;
4665}
4666
4667static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4668 struct kvm_enable_cap *cap)
4669{
David Brazdil0f672f62019-12-10 10:32:29 +00004670 int r;
4671 uint16_t vmcs_version;
4672 void __user *user_ptr;
4673
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004674 if (cap->flags)
4675 return -EINVAL;
4676
4677 switch (cap->cap) {
4678 case KVM_CAP_HYPERV_SYNIC2:
4679 if (cap->args[0])
4680 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02004681 fallthrough;
David Brazdil0f672f62019-12-10 10:32:29 +00004682
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004683 case KVM_CAP_HYPERV_SYNIC:
4684 if (!irqchip_in_kernel(vcpu->kvm))
4685 return -EINVAL;
4686 return kvm_hv_activate_synic(vcpu, cap->cap ==
4687 KVM_CAP_HYPERV_SYNIC2);
David Brazdil0f672f62019-12-10 10:32:29 +00004688 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
Olivier Deprez157378f2022-04-04 15:47:50 +02004689 if (!kvm_x86_ops.nested_ops->enable_evmcs)
David Brazdil0f672f62019-12-10 10:32:29 +00004690 return -ENOTTY;
Olivier Deprez157378f2022-04-04 15:47:50 +02004691 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
David Brazdil0f672f62019-12-10 10:32:29 +00004692 if (!r) {
4693 user_ptr = (void __user *)(uintptr_t)cap->args[0];
4694 if (copy_to_user(user_ptr, &vmcs_version,
4695 sizeof(vmcs_version)))
4696 r = -EFAULT;
4697 }
4698 return r;
4699 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
Olivier Deprez157378f2022-04-04 15:47:50 +02004700 if (!kvm_x86_ops.enable_direct_tlbflush)
David Brazdil0f672f62019-12-10 10:32:29 +00004701 return -ENOTTY;
4702
Olivier Deprez157378f2022-04-04 15:47:50 +02004703 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4704
4705 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4706 vcpu->arch.pv_cpuid.enforce = cap->args[0];
4707 if (vcpu->arch.pv_cpuid.enforce)
4708 kvm_update_pv_runtime(vcpu);
4709
4710 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004711
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004712 default:
4713 return -EINVAL;
4714 }
4715}
4716
4717long kvm_arch_vcpu_ioctl(struct file *filp,
4718 unsigned int ioctl, unsigned long arg)
4719{
4720 struct kvm_vcpu *vcpu = filp->private_data;
4721 void __user *argp = (void __user *)arg;
4722 int r;
4723 union {
4724 struct kvm_lapic_state *lapic;
4725 struct kvm_xsave *xsave;
4726 struct kvm_xcrs *xcrs;
4727 void *buffer;
4728 } u;
4729
4730 vcpu_load(vcpu);
4731
4732 u.buffer = NULL;
4733 switch (ioctl) {
4734 case KVM_GET_LAPIC: {
4735 r = -EINVAL;
4736 if (!lapic_in_kernel(vcpu))
4737 goto out;
David Brazdil0f672f62019-12-10 10:32:29 +00004738 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4739 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004740
4741 r = -ENOMEM;
4742 if (!u.lapic)
4743 goto out;
4744 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4745 if (r)
4746 goto out;
4747 r = -EFAULT;
4748 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4749 goto out;
4750 r = 0;
4751 break;
4752 }
4753 case KVM_SET_LAPIC: {
4754 r = -EINVAL;
4755 if (!lapic_in_kernel(vcpu))
4756 goto out;
4757 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4758 if (IS_ERR(u.lapic)) {
4759 r = PTR_ERR(u.lapic);
4760 goto out_nofree;
4761 }
4762
4763 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4764 break;
4765 }
4766 case KVM_INTERRUPT: {
4767 struct kvm_interrupt irq;
4768
4769 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004770 if (copy_from_user(&irq, argp, sizeof(irq)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004771 goto out;
4772 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4773 break;
4774 }
4775 case KVM_NMI: {
4776 r = kvm_vcpu_ioctl_nmi(vcpu);
4777 break;
4778 }
4779 case KVM_SMI: {
4780 r = kvm_vcpu_ioctl_smi(vcpu);
4781 break;
4782 }
4783 case KVM_SET_CPUID: {
4784 struct kvm_cpuid __user *cpuid_arg = argp;
4785 struct kvm_cpuid cpuid;
4786
4787 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004788 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004789 goto out;
4790 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4791 break;
4792 }
4793 case KVM_SET_CPUID2: {
4794 struct kvm_cpuid2 __user *cpuid_arg = argp;
4795 struct kvm_cpuid2 cpuid;
4796
4797 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004798 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004799 goto out;
4800 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4801 cpuid_arg->entries);
4802 break;
4803 }
4804 case KVM_GET_CPUID2: {
4805 struct kvm_cpuid2 __user *cpuid_arg = argp;
4806 struct kvm_cpuid2 cpuid;
4807
4808 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004809 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004810 goto out;
4811 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4812 cpuid_arg->entries);
4813 if (r)
4814 goto out;
4815 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004816 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004817 goto out;
4818 r = 0;
4819 break;
4820 }
4821 case KVM_GET_MSRS: {
4822 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4823 r = msr_io(vcpu, argp, do_get_msr, 1);
4824 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4825 break;
4826 }
4827 case KVM_SET_MSRS: {
4828 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4829 r = msr_io(vcpu, argp, do_set_msr, 0);
4830 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4831 break;
4832 }
4833 case KVM_TPR_ACCESS_REPORTING: {
4834 struct kvm_tpr_access_ctl tac;
4835
4836 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004837 if (copy_from_user(&tac, argp, sizeof(tac)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004838 goto out;
4839 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4840 if (r)
4841 goto out;
4842 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004843 if (copy_to_user(argp, &tac, sizeof(tac)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004844 goto out;
4845 r = 0;
4846 break;
4847 };
4848 case KVM_SET_VAPIC_ADDR: {
4849 struct kvm_vapic_addr va;
4850 int idx;
4851
4852 r = -EINVAL;
4853 if (!lapic_in_kernel(vcpu))
4854 goto out;
4855 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004856 if (copy_from_user(&va, argp, sizeof(va)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004857 goto out;
4858 idx = srcu_read_lock(&vcpu->kvm->srcu);
4859 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4860 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4861 break;
4862 }
4863 case KVM_X86_SETUP_MCE: {
4864 u64 mcg_cap;
4865
4866 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004867 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004868 goto out;
4869 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4870 break;
4871 }
4872 case KVM_X86_SET_MCE: {
4873 struct kvm_x86_mce mce;
4874
4875 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00004876 if (copy_from_user(&mce, argp, sizeof(mce)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004877 goto out;
4878 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4879 break;
4880 }
4881 case KVM_GET_VCPU_EVENTS: {
4882 struct kvm_vcpu_events events;
4883
4884 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4885
4886 r = -EFAULT;
4887 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4888 break;
4889 r = 0;
4890 break;
4891 }
4892 case KVM_SET_VCPU_EVENTS: {
4893 struct kvm_vcpu_events events;
4894
4895 r = -EFAULT;
4896 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4897 break;
4898
4899 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4900 break;
4901 }
4902 case KVM_GET_DEBUGREGS: {
4903 struct kvm_debugregs dbgregs;
4904
4905 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4906
4907 r = -EFAULT;
4908 if (copy_to_user(argp, &dbgregs,
4909 sizeof(struct kvm_debugregs)))
4910 break;
4911 r = 0;
4912 break;
4913 }
4914 case KVM_SET_DEBUGREGS: {
4915 struct kvm_debugregs dbgregs;
4916
4917 r = -EFAULT;
4918 if (copy_from_user(&dbgregs, argp,
4919 sizeof(struct kvm_debugregs)))
4920 break;
4921
4922 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4923 break;
4924 }
4925 case KVM_GET_XSAVE: {
David Brazdil0f672f62019-12-10 10:32:29 +00004926 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004927 r = -ENOMEM;
4928 if (!u.xsave)
4929 break;
4930
4931 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4932
4933 r = -EFAULT;
4934 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4935 break;
4936 r = 0;
4937 break;
4938 }
4939 case KVM_SET_XSAVE: {
4940 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4941 if (IS_ERR(u.xsave)) {
4942 r = PTR_ERR(u.xsave);
4943 goto out_nofree;
4944 }
4945
4946 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4947 break;
4948 }
4949 case KVM_GET_XCRS: {
David Brazdil0f672f62019-12-10 10:32:29 +00004950 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004951 r = -ENOMEM;
4952 if (!u.xcrs)
4953 break;
4954
4955 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4956
4957 r = -EFAULT;
4958 if (copy_to_user(argp, u.xcrs,
4959 sizeof(struct kvm_xcrs)))
4960 break;
4961 r = 0;
4962 break;
4963 }
4964 case KVM_SET_XCRS: {
4965 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4966 if (IS_ERR(u.xcrs)) {
4967 r = PTR_ERR(u.xcrs);
4968 goto out_nofree;
4969 }
4970
4971 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4972 break;
4973 }
4974 case KVM_SET_TSC_KHZ: {
4975 u32 user_tsc_khz;
4976
4977 r = -EINVAL;
4978 user_tsc_khz = (u32)arg;
4979
Olivier Deprez157378f2022-04-04 15:47:50 +02004980 if (kvm_has_tsc_control &&
4981 user_tsc_khz >= kvm_max_guest_tsc_khz)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004982 goto out;
4983
4984 if (user_tsc_khz == 0)
4985 user_tsc_khz = tsc_khz;
4986
4987 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4988 r = 0;
4989
4990 goto out;
4991 }
4992 case KVM_GET_TSC_KHZ: {
4993 r = vcpu->arch.virtual_tsc_khz;
4994 goto out;
4995 }
4996 case KVM_KVMCLOCK_CTRL: {
4997 r = kvm_set_guest_paused(vcpu);
4998 goto out;
4999 }
5000 case KVM_ENABLE_CAP: {
5001 struct kvm_enable_cap cap;
5002
5003 r = -EFAULT;
5004 if (copy_from_user(&cap, argp, sizeof(cap)))
5005 goto out;
5006 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5007 break;
5008 }
5009 case KVM_GET_NESTED_STATE: {
5010 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5011 u32 user_data_size;
5012
5013 r = -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005014 if (!kvm_x86_ops.nested_ops->get_state)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005015 break;
5016
5017 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
5018 r = -EFAULT;
5019 if (get_user(user_data_size, &user_kvm_nested_state->size))
5020 break;
5021
Olivier Deprez157378f2022-04-04 15:47:50 +02005022 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5023 user_data_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005024 if (r < 0)
5025 break;
5026
5027 if (r > user_data_size) {
5028 if (put_user(r, &user_kvm_nested_state->size))
5029 r = -EFAULT;
5030 else
5031 r = -E2BIG;
5032 break;
5033 }
5034
5035 r = 0;
5036 break;
5037 }
5038 case KVM_SET_NESTED_STATE: {
5039 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5040 struct kvm_nested_state kvm_state;
Olivier Deprez0e641232021-09-23 10:07:05 +02005041 int idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005042
5043 r = -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005044 if (!kvm_x86_ops.nested_ops->set_state)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005045 break;
5046
5047 r = -EFAULT;
5048 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
5049 break;
5050
5051 r = -EINVAL;
5052 if (kvm_state.size < sizeof(kvm_state))
5053 break;
5054
5055 if (kvm_state.flags &
David Brazdil0f672f62019-12-10 10:32:29 +00005056 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
Olivier Deprez157378f2022-04-04 15:47:50 +02005057 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5058 | KVM_STATE_NESTED_GIF_SET))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005059 break;
5060
5061 /* nested_run_pending implies guest_mode. */
David Brazdil0f672f62019-12-10 10:32:29 +00005062 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5063 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005064 break;
5065
Olivier Deprez0e641232021-09-23 10:07:05 +02005066 idx = srcu_read_lock(&vcpu->kvm->srcu);
Olivier Deprez157378f2022-04-04 15:47:50 +02005067 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
Olivier Deprez0e641232021-09-23 10:07:05 +02005068 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005069 break;
5070 }
David Brazdil0f672f62019-12-10 10:32:29 +00005071 case KVM_GET_SUPPORTED_HV_CPUID: {
5072 struct kvm_cpuid2 __user *cpuid_arg = argp;
5073 struct kvm_cpuid2 cpuid;
5074
5075 r = -EFAULT;
5076 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5077 goto out;
5078
5079 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
5080 cpuid_arg->entries);
5081 if (r)
5082 goto out;
5083
5084 r = -EFAULT;
5085 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5086 goto out;
5087 r = 0;
5088 break;
5089 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005090 default:
5091 r = -EINVAL;
5092 }
5093out:
5094 kfree(u.buffer);
5095out_nofree:
5096 vcpu_put(vcpu);
5097 return r;
5098}
5099
5100vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
5101{
5102 return VM_FAULT_SIGBUS;
5103}
5104
5105static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5106{
5107 int ret;
5108
5109 if (addr > (unsigned int)(-3 * PAGE_SIZE))
5110 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005111 ret = kvm_x86_ops.set_tss_addr(kvm, addr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005112 return ret;
5113}
5114
5115static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5116 u64 ident_addr)
5117{
Olivier Deprez157378f2022-04-04 15:47:50 +02005118 return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005119}
5120
5121static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
David Brazdil0f672f62019-12-10 10:32:29 +00005122 unsigned long kvm_nr_mmu_pages)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005123{
5124 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5125 return -EINVAL;
5126
5127 mutex_lock(&kvm->slots_lock);
5128
5129 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
5130 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
5131
5132 mutex_unlock(&kvm->slots_lock);
5133 return 0;
5134}
5135
David Brazdil0f672f62019-12-10 10:32:29 +00005136static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005137{
5138 return kvm->arch.n_max_mmu_pages;
5139}
5140
5141static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5142{
5143 struct kvm_pic *pic = kvm->arch.vpic;
5144 int r;
5145
5146 r = 0;
5147 switch (chip->chip_id) {
5148 case KVM_IRQCHIP_PIC_MASTER:
5149 memcpy(&chip->chip.pic, &pic->pics[0],
5150 sizeof(struct kvm_pic_state));
5151 break;
5152 case KVM_IRQCHIP_PIC_SLAVE:
5153 memcpy(&chip->chip.pic, &pic->pics[1],
5154 sizeof(struct kvm_pic_state));
5155 break;
5156 case KVM_IRQCHIP_IOAPIC:
5157 kvm_get_ioapic(kvm, &chip->chip.ioapic);
5158 break;
5159 default:
5160 r = -EINVAL;
5161 break;
5162 }
5163 return r;
5164}
5165
5166static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5167{
5168 struct kvm_pic *pic = kvm->arch.vpic;
5169 int r;
5170
5171 r = 0;
5172 switch (chip->chip_id) {
5173 case KVM_IRQCHIP_PIC_MASTER:
5174 spin_lock(&pic->lock);
5175 memcpy(&pic->pics[0], &chip->chip.pic,
5176 sizeof(struct kvm_pic_state));
5177 spin_unlock(&pic->lock);
5178 break;
5179 case KVM_IRQCHIP_PIC_SLAVE:
5180 spin_lock(&pic->lock);
5181 memcpy(&pic->pics[1], &chip->chip.pic,
5182 sizeof(struct kvm_pic_state));
5183 spin_unlock(&pic->lock);
5184 break;
5185 case KVM_IRQCHIP_IOAPIC:
5186 kvm_set_ioapic(kvm, &chip->chip.ioapic);
5187 break;
5188 default:
5189 r = -EINVAL;
5190 break;
5191 }
5192 kvm_pic_update_irq(pic);
5193 return r;
5194}
5195
5196static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5197{
5198 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5199
5200 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5201
5202 mutex_lock(&kps->lock);
5203 memcpy(ps, &kps->channels, sizeof(*ps));
5204 mutex_unlock(&kps->lock);
5205 return 0;
5206}
5207
5208static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5209{
5210 int i;
5211 struct kvm_pit *pit = kvm->arch.vpit;
5212
5213 mutex_lock(&pit->pit_state.lock);
5214 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
5215 for (i = 0; i < 3; i++)
5216 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5217 mutex_unlock(&pit->pit_state.lock);
5218 return 0;
5219}
5220
5221static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5222{
5223 mutex_lock(&kvm->arch.vpit->pit_state.lock);
5224 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5225 sizeof(ps->channels));
5226 ps->flags = kvm->arch.vpit->pit_state.flags;
5227 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
5228 memset(&ps->reserved, 0, sizeof(ps->reserved));
5229 return 0;
5230}
5231
5232static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5233{
5234 int start = 0;
5235 int i;
5236 u32 prev_legacy, cur_legacy;
5237 struct kvm_pit *pit = kvm->arch.vpit;
5238
5239 mutex_lock(&pit->pit_state.lock);
5240 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
5241 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5242 if (!prev_legacy && cur_legacy)
5243 start = 1;
5244 memcpy(&pit->pit_state.channels, &ps->channels,
5245 sizeof(pit->pit_state.channels));
5246 pit->pit_state.flags = ps->flags;
5247 for (i = 0; i < 3; i++)
5248 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
5249 start && i == 0);
5250 mutex_unlock(&pit->pit_state.lock);
5251 return 0;
5252}
5253
5254static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5255 struct kvm_reinject_control *control)
5256{
5257 struct kvm_pit *pit = kvm->arch.vpit;
5258
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005259 /* pit->pit_state.lock was overloaded to prevent userspace from getting
5260 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5261 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
5262 */
5263 mutex_lock(&pit->pit_state.lock);
5264 kvm_pit_set_reinject(pit, control->pit_reinject);
5265 mutex_unlock(&pit->pit_state.lock);
5266
5267 return 0;
5268}
5269
Olivier Deprez157378f2022-04-04 15:47:50 +02005270void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005271{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005272 /*
5273 * Flush potentially hardware-cached dirty pages to dirty_bitmap.
5274 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005275 if (kvm_x86_ops.flush_log_dirty)
5276 kvm_x86_ops.flush_log_dirty(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005277}
5278
5279int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5280 bool line_status)
5281{
5282 if (!irqchip_in_kernel(kvm))
5283 return -ENXIO;
5284
5285 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
5286 irq_event->irq, irq_event->level,
5287 line_status);
5288 return 0;
5289}
5290
David Brazdil0f672f62019-12-10 10:32:29 +00005291int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5292 struct kvm_enable_cap *cap)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005293{
5294 int r;
5295
5296 if (cap->flags)
5297 return -EINVAL;
5298
5299 switch (cap->cap) {
5300 case KVM_CAP_DISABLE_QUIRKS:
5301 kvm->arch.disabled_quirks = cap->args[0];
5302 r = 0;
5303 break;
5304 case KVM_CAP_SPLIT_IRQCHIP: {
5305 mutex_lock(&kvm->lock);
5306 r = -EINVAL;
5307 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
5308 goto split_irqchip_unlock;
5309 r = -EEXIST;
5310 if (irqchip_in_kernel(kvm))
5311 goto split_irqchip_unlock;
5312 if (kvm->created_vcpus)
5313 goto split_irqchip_unlock;
5314 r = kvm_setup_empty_irq_routing(kvm);
5315 if (r)
5316 goto split_irqchip_unlock;
5317 /* Pairs with irqchip_in_kernel. */
5318 smp_wmb();
5319 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
5320 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
5321 r = 0;
5322split_irqchip_unlock:
5323 mutex_unlock(&kvm->lock);
5324 break;
5325 }
5326 case KVM_CAP_X2APIC_API:
5327 r = -EINVAL;
5328 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5329 break;
5330
5331 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5332 kvm->arch.x2apic_format = true;
5333 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5334 kvm->arch.x2apic_broadcast_quirk_disabled = true;
5335
5336 r = 0;
5337 break;
5338 case KVM_CAP_X86_DISABLE_EXITS:
5339 r = -EINVAL;
5340 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5341 break;
5342
5343 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5344 kvm_can_mwait_in_guest())
5345 kvm->arch.mwait_in_guest = true;
5346 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5347 kvm->arch.hlt_in_guest = true;
5348 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5349 kvm->arch.pause_in_guest = true;
David Brazdil0f672f62019-12-10 10:32:29 +00005350 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5351 kvm->arch.cstate_in_guest = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005352 r = 0;
5353 break;
5354 case KVM_CAP_MSR_PLATFORM_INFO:
5355 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5356 r = 0;
5357 break;
David Brazdil0f672f62019-12-10 10:32:29 +00005358 case KVM_CAP_EXCEPTION_PAYLOAD:
5359 kvm->arch.exception_payload_enabled = cap->args[0];
5360 r = 0;
5361 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02005362 case KVM_CAP_X86_USER_SPACE_MSR:
Olivier Deprez92d4c212022-12-06 15:05:30 +01005363 r = -EINVAL;
5364 if (cap->args[0] & ~(KVM_MSR_EXIT_REASON_INVAL |
5365 KVM_MSR_EXIT_REASON_UNKNOWN |
5366 KVM_MSR_EXIT_REASON_FILTER))
5367 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02005368 kvm->arch.user_space_msr_mask = cap->args[0];
5369 r = 0;
5370 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005371 default:
5372 r = -EINVAL;
5373 break;
5374 }
5375 return r;
5376}
5377
Olivier Deprez157378f2022-04-04 15:47:50 +02005378static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
5379{
5380 struct kvm_x86_msr_filter *msr_filter;
5381
5382 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
5383 if (!msr_filter)
5384 return NULL;
5385
5386 msr_filter->default_allow = default_allow;
5387 return msr_filter;
5388}
5389
5390static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
5391{
5392 u32 i;
5393
5394 if (!msr_filter)
5395 return;
5396
5397 for (i = 0; i < msr_filter->count; i++)
5398 kfree(msr_filter->ranges[i].bitmap);
5399
5400 kfree(msr_filter);
5401}
5402
5403static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
5404 struct kvm_msr_filter_range *user_range)
5405{
5406 struct msr_bitmap_range range;
5407 unsigned long *bitmap = NULL;
5408 size_t bitmap_size;
5409 int r;
5410
5411 if (!user_range->nmsrs)
5412 return 0;
5413
5414 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
5415 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
5416 return -EINVAL;
5417
5418 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
5419 if (IS_ERR(bitmap))
5420 return PTR_ERR(bitmap);
5421
5422 range = (struct msr_bitmap_range) {
5423 .flags = user_range->flags,
5424 .base = user_range->base,
5425 .nmsrs = user_range->nmsrs,
5426 .bitmap = bitmap,
5427 };
5428
5429 if (range.flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE)) {
5430 r = -EINVAL;
5431 goto err;
5432 }
5433
5434 if (!range.flags) {
5435 r = -EINVAL;
5436 goto err;
5437 }
5438
5439 /* Everything ok, add this range identifier. */
5440 msr_filter->ranges[msr_filter->count] = range;
5441 msr_filter->count++;
5442
5443 return 0;
5444err:
5445 kfree(bitmap);
5446 return r;
5447}
5448
Olivier Deprez92d4c212022-12-06 15:05:30 +01005449static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
5450 struct kvm_msr_filter *filter)
Olivier Deprez157378f2022-04-04 15:47:50 +02005451{
Olivier Deprez157378f2022-04-04 15:47:50 +02005452 struct kvm_x86_msr_filter *new_filter, *old_filter;
Olivier Deprez157378f2022-04-04 15:47:50 +02005453 bool default_allow;
5454 bool empty = true;
5455 int r = 0;
5456 u32 i;
5457
Olivier Deprez92d4c212022-12-06 15:05:30 +01005458 if (filter->flags & ~KVM_MSR_FILTER_DEFAULT_DENY)
5459 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005460
Olivier Deprez92d4c212022-12-06 15:05:30 +01005461 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
5462 empty &= !filter->ranges[i].nmsrs;
Olivier Deprez157378f2022-04-04 15:47:50 +02005463
Olivier Deprez92d4c212022-12-06 15:05:30 +01005464 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
Olivier Deprez157378f2022-04-04 15:47:50 +02005465 if (empty && !default_allow)
5466 return -EINVAL;
5467
5468 new_filter = kvm_alloc_msr_filter(default_allow);
5469 if (!new_filter)
5470 return -ENOMEM;
5471
Olivier Deprez92d4c212022-12-06 15:05:30 +01005472 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
5473 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
Olivier Deprez157378f2022-04-04 15:47:50 +02005474 if (r) {
5475 kvm_free_msr_filter(new_filter);
5476 return r;
5477 }
5478 }
5479
5480 mutex_lock(&kvm->lock);
5481
5482 /* The per-VM filter is protected by kvm->lock... */
5483 old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
5484
5485 rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
5486 synchronize_srcu(&kvm->srcu);
5487
5488 kvm_free_msr_filter(old_filter);
5489
5490 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
5491 mutex_unlock(&kvm->lock);
5492
5493 return 0;
5494}
5495
Olivier Deprez92d4c212022-12-06 15:05:30 +01005496#ifdef CONFIG_KVM_COMPAT
5497/* for KVM_X86_SET_MSR_FILTER */
5498struct kvm_msr_filter_range_compat {
5499 __u32 flags;
5500 __u32 nmsrs;
5501 __u32 base;
5502 __u32 bitmap;
5503};
5504
5505struct kvm_msr_filter_compat {
5506 __u32 flags;
5507 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
5508};
5509
5510#define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
5511
5512long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
5513 unsigned long arg)
5514{
5515 void __user *argp = (void __user *)arg;
5516 struct kvm *kvm = filp->private_data;
5517 long r = -ENOTTY;
5518
5519 switch (ioctl) {
5520 case KVM_X86_SET_MSR_FILTER_COMPAT: {
5521 struct kvm_msr_filter __user *user_msr_filter = argp;
5522 struct kvm_msr_filter_compat filter_compat;
5523 struct kvm_msr_filter filter;
5524 int i;
5525
5526 if (copy_from_user(&filter_compat, user_msr_filter,
5527 sizeof(filter_compat)))
5528 return -EFAULT;
5529
5530 filter.flags = filter_compat.flags;
5531 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
5532 struct kvm_msr_filter_range_compat *cr;
5533
5534 cr = &filter_compat.ranges[i];
5535 filter.ranges[i] = (struct kvm_msr_filter_range) {
5536 .flags = cr->flags,
5537 .nmsrs = cr->nmsrs,
5538 .base = cr->base,
5539 .bitmap = (__u8 *)(ulong)cr->bitmap,
5540 };
5541 }
5542
5543 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
5544 break;
5545 }
5546 }
5547
5548 return r;
5549}
5550#endif
5551
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005552long kvm_arch_vm_ioctl(struct file *filp,
5553 unsigned int ioctl, unsigned long arg)
5554{
5555 struct kvm *kvm = filp->private_data;
5556 void __user *argp = (void __user *)arg;
5557 int r = -ENOTTY;
5558 /*
5559 * This union makes it completely explicit to gcc-3.x
5560 * that these two variables' stack usage should be
5561 * combined, not added together.
5562 */
5563 union {
5564 struct kvm_pit_state ps;
5565 struct kvm_pit_state2 ps2;
5566 struct kvm_pit_config pit_config;
5567 } u;
5568
5569 switch (ioctl) {
5570 case KVM_SET_TSS_ADDR:
5571 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5572 break;
5573 case KVM_SET_IDENTITY_MAP_ADDR: {
5574 u64 ident_addr;
5575
5576 mutex_lock(&kvm->lock);
5577 r = -EINVAL;
5578 if (kvm->created_vcpus)
5579 goto set_identity_unlock;
5580 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00005581 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005582 goto set_identity_unlock;
5583 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5584set_identity_unlock:
5585 mutex_unlock(&kvm->lock);
5586 break;
5587 }
5588 case KVM_SET_NR_MMU_PAGES:
5589 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5590 break;
5591 case KVM_GET_NR_MMU_PAGES:
5592 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5593 break;
5594 case KVM_CREATE_IRQCHIP: {
5595 mutex_lock(&kvm->lock);
5596
5597 r = -EEXIST;
5598 if (irqchip_in_kernel(kvm))
5599 goto create_irqchip_unlock;
5600
5601 r = -EINVAL;
5602 if (kvm->created_vcpus)
5603 goto create_irqchip_unlock;
5604
5605 r = kvm_pic_init(kvm);
5606 if (r)
5607 goto create_irqchip_unlock;
5608
5609 r = kvm_ioapic_init(kvm);
5610 if (r) {
5611 kvm_pic_destroy(kvm);
5612 goto create_irqchip_unlock;
5613 }
5614
5615 r = kvm_setup_default_irq_routing(kvm);
5616 if (r) {
5617 kvm_ioapic_destroy(kvm);
5618 kvm_pic_destroy(kvm);
5619 goto create_irqchip_unlock;
5620 }
5621 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5622 smp_wmb();
5623 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5624 create_irqchip_unlock:
5625 mutex_unlock(&kvm->lock);
5626 break;
5627 }
5628 case KVM_CREATE_PIT:
5629 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5630 goto create_pit;
5631 case KVM_CREATE_PIT2:
5632 r = -EFAULT;
5633 if (copy_from_user(&u.pit_config, argp,
5634 sizeof(struct kvm_pit_config)))
5635 goto out;
5636 create_pit:
5637 mutex_lock(&kvm->lock);
5638 r = -EEXIST;
5639 if (kvm->arch.vpit)
5640 goto create_pit_unlock;
5641 r = -ENOMEM;
5642 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5643 if (kvm->arch.vpit)
5644 r = 0;
5645 create_pit_unlock:
5646 mutex_unlock(&kvm->lock);
5647 break;
5648 case KVM_GET_IRQCHIP: {
5649 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5650 struct kvm_irqchip *chip;
5651
5652 chip = memdup_user(argp, sizeof(*chip));
5653 if (IS_ERR(chip)) {
5654 r = PTR_ERR(chip);
5655 goto out;
5656 }
5657
5658 r = -ENXIO;
5659 if (!irqchip_kernel(kvm))
5660 goto get_irqchip_out;
5661 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5662 if (r)
5663 goto get_irqchip_out;
5664 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00005665 if (copy_to_user(argp, chip, sizeof(*chip)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005666 goto get_irqchip_out;
5667 r = 0;
5668 get_irqchip_out:
5669 kfree(chip);
5670 break;
5671 }
5672 case KVM_SET_IRQCHIP: {
5673 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5674 struct kvm_irqchip *chip;
5675
5676 chip = memdup_user(argp, sizeof(*chip));
5677 if (IS_ERR(chip)) {
5678 r = PTR_ERR(chip);
5679 goto out;
5680 }
5681
5682 r = -ENXIO;
5683 if (!irqchip_kernel(kvm))
5684 goto set_irqchip_out;
5685 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005686 set_irqchip_out:
5687 kfree(chip);
5688 break;
5689 }
5690 case KVM_GET_PIT: {
5691 r = -EFAULT;
5692 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5693 goto out;
5694 r = -ENXIO;
5695 if (!kvm->arch.vpit)
5696 goto out;
5697 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5698 if (r)
5699 goto out;
5700 r = -EFAULT;
5701 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5702 goto out;
5703 r = 0;
5704 break;
5705 }
5706 case KVM_SET_PIT: {
5707 r = -EFAULT;
David Brazdil0f672f62019-12-10 10:32:29 +00005708 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005709 goto out;
Olivier Deprez0e641232021-09-23 10:07:05 +02005710 mutex_lock(&kvm->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005711 r = -ENXIO;
5712 if (!kvm->arch.vpit)
Olivier Deprez0e641232021-09-23 10:07:05 +02005713 goto set_pit_out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005714 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
Olivier Deprez0e641232021-09-23 10:07:05 +02005715set_pit_out:
5716 mutex_unlock(&kvm->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005717 break;
5718 }
5719 case KVM_GET_PIT2: {
5720 r = -ENXIO;
5721 if (!kvm->arch.vpit)
5722 goto out;
5723 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5724 if (r)
5725 goto out;
5726 r = -EFAULT;
5727 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5728 goto out;
5729 r = 0;
5730 break;
5731 }
5732 case KVM_SET_PIT2: {
5733 r = -EFAULT;
5734 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5735 goto out;
Olivier Deprez0e641232021-09-23 10:07:05 +02005736 mutex_lock(&kvm->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005737 r = -ENXIO;
5738 if (!kvm->arch.vpit)
Olivier Deprez0e641232021-09-23 10:07:05 +02005739 goto set_pit2_out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005740 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
Olivier Deprez0e641232021-09-23 10:07:05 +02005741set_pit2_out:
5742 mutex_unlock(&kvm->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005743 break;
5744 }
5745 case KVM_REINJECT_CONTROL: {
5746 struct kvm_reinject_control control;
5747 r = -EFAULT;
5748 if (copy_from_user(&control, argp, sizeof(control)))
5749 goto out;
Olivier Deprez157378f2022-04-04 15:47:50 +02005750 r = -ENXIO;
5751 if (!kvm->arch.vpit)
5752 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005753 r = kvm_vm_ioctl_reinject(kvm, &control);
5754 break;
5755 }
5756 case KVM_SET_BOOT_CPU_ID:
5757 r = 0;
5758 mutex_lock(&kvm->lock);
5759 if (kvm->created_vcpus)
5760 r = -EBUSY;
5761 else
5762 kvm->arch.bsp_vcpu_id = arg;
5763 mutex_unlock(&kvm->lock);
5764 break;
5765 case KVM_XEN_HVM_CONFIG: {
5766 struct kvm_xen_hvm_config xhc;
5767 r = -EFAULT;
5768 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5769 goto out;
5770 r = -EINVAL;
5771 if (xhc.flags)
5772 goto out;
5773 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5774 r = 0;
5775 break;
5776 }
5777 case KVM_SET_CLOCK: {
5778 struct kvm_clock_data user_ns;
5779 u64 now_ns;
5780
5781 r = -EFAULT;
5782 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5783 goto out;
5784
5785 r = -EINVAL;
5786 if (user_ns.flags)
5787 goto out;
5788
5789 r = 0;
5790 /*
5791 * TODO: userspace has to take care of races with VCPU_RUN, so
5792 * kvm_gen_update_masterclock() can be cut down to locked
5793 * pvclock_update_vm_gtod_copy().
5794 */
5795 kvm_gen_update_masterclock(kvm);
5796 now_ns = get_kvmclock_ns(kvm);
5797 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5798 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5799 break;
5800 }
5801 case KVM_GET_CLOCK: {
5802 struct kvm_clock_data user_ns;
5803 u64 now_ns;
5804
5805 now_ns = get_kvmclock_ns(kvm);
5806 user_ns.clock = now_ns;
5807 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5808 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5809
5810 r = -EFAULT;
5811 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5812 goto out;
5813 r = 0;
5814 break;
5815 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005816 case KVM_MEMORY_ENCRYPT_OP: {
5817 r = -ENOTTY;
Olivier Deprez157378f2022-04-04 15:47:50 +02005818 if (kvm_x86_ops.mem_enc_op)
5819 r = kvm_x86_ops.mem_enc_op(kvm, argp);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005820 break;
5821 }
5822 case KVM_MEMORY_ENCRYPT_REG_REGION: {
5823 struct kvm_enc_region region;
5824
5825 r = -EFAULT;
5826 if (copy_from_user(&region, argp, sizeof(region)))
5827 goto out;
5828
5829 r = -ENOTTY;
Olivier Deprez157378f2022-04-04 15:47:50 +02005830 if (kvm_x86_ops.mem_enc_reg_region)
5831 r = kvm_x86_ops.mem_enc_reg_region(kvm, &region);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005832 break;
5833 }
5834 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5835 struct kvm_enc_region region;
5836
5837 r = -EFAULT;
5838 if (copy_from_user(&region, argp, sizeof(region)))
5839 goto out;
5840
5841 r = -ENOTTY;
Olivier Deprez157378f2022-04-04 15:47:50 +02005842 if (kvm_x86_ops.mem_enc_unreg_region)
5843 r = kvm_x86_ops.mem_enc_unreg_region(kvm, &region);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005844 break;
5845 }
5846 case KVM_HYPERV_EVENTFD: {
5847 struct kvm_hyperv_eventfd hvevfd;
5848
5849 r = -EFAULT;
5850 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5851 goto out;
5852 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5853 break;
5854 }
David Brazdil0f672f62019-12-10 10:32:29 +00005855 case KVM_SET_PMU_EVENT_FILTER:
5856 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5857 break;
Olivier Deprez92d4c212022-12-06 15:05:30 +01005858 case KVM_X86_SET_MSR_FILTER: {
5859 struct kvm_msr_filter __user *user_msr_filter = argp;
5860 struct kvm_msr_filter filter;
5861
5862 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
5863 return -EFAULT;
5864
5865 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
Olivier Deprez157378f2022-04-04 15:47:50 +02005866 break;
Olivier Deprez92d4c212022-12-06 15:05:30 +01005867 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005868 default:
5869 r = -ENOTTY;
5870 }
5871out:
5872 return r;
5873}
5874
5875static void kvm_init_msr_list(void)
5876{
David Brazdil0f672f62019-12-10 10:32:29 +00005877 struct x86_pmu_capability x86_pmu;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005878 u32 dummy[2];
David Brazdil0f672f62019-12-10 10:32:29 +00005879 unsigned i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005880
David Brazdil0f672f62019-12-10 10:32:29 +00005881 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5882 "Please update the fixed PMCs in msrs_to_saved_all[]");
5883
5884 perf_get_x86_pmu_capability(&x86_pmu);
5885
5886 num_msrs_to_save = 0;
5887 num_emulated_msrs = 0;
5888 num_msr_based_features = 0;
5889
5890 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5891 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005892 continue;
5893
5894 /*
5895 * Even MSRs that are valid in the host may not be exposed
5896 * to the guests in some cases.
5897 */
David Brazdil0f672f62019-12-10 10:32:29 +00005898 switch (msrs_to_save_all[i]) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005899 case MSR_IA32_BNDCFGS:
5900 if (!kvm_mpx_supported())
5901 continue;
5902 break;
5903 case MSR_TSC_AUX:
Olivier Deprez157378f2022-04-04 15:47:50 +02005904 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005905 continue;
5906 break;
Olivier Deprez0e641232021-09-23 10:07:05 +02005907 case MSR_IA32_UMWAIT_CONTROL:
Olivier Deprez157378f2022-04-04 15:47:50 +02005908 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
Olivier Deprez0e641232021-09-23 10:07:05 +02005909 continue;
5910 break;
David Brazdil0f672f62019-12-10 10:32:29 +00005911 case MSR_IA32_RTIT_CTL:
5912 case MSR_IA32_RTIT_STATUS:
Olivier Deprez157378f2022-04-04 15:47:50 +02005913 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
David Brazdil0f672f62019-12-10 10:32:29 +00005914 continue;
5915 break;
5916 case MSR_IA32_RTIT_CR3_MATCH:
Olivier Deprez157378f2022-04-04 15:47:50 +02005917 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
David Brazdil0f672f62019-12-10 10:32:29 +00005918 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5919 continue;
5920 break;
5921 case MSR_IA32_RTIT_OUTPUT_BASE:
5922 case MSR_IA32_RTIT_OUTPUT_MASK:
Olivier Deprez157378f2022-04-04 15:47:50 +02005923 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
David Brazdil0f672f62019-12-10 10:32:29 +00005924 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5925 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5926 continue;
5927 break;
Olivier Deprez157378f2022-04-04 15:47:50 +02005928 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5929 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
David Brazdil0f672f62019-12-10 10:32:29 +00005930 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5931 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5932 continue;
5933 break;
5934 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5935 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5936 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5937 continue;
5938 break;
5939 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5940 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5941 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5942 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02005943 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005944 default:
5945 break;
5946 }
5947
David Brazdil0f672f62019-12-10 10:32:29 +00005948 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005949 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005950
David Brazdil0f672f62019-12-10 10:32:29 +00005951 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005952 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005953 continue;
5954
David Brazdil0f672f62019-12-10 10:32:29 +00005955 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005956 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005957
David Brazdil0f672f62019-12-10 10:32:29 +00005958 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005959 struct kvm_msr_entry msr;
5960
David Brazdil0f672f62019-12-10 10:32:29 +00005961 msr.index = msr_based_features_all[i];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005962 if (kvm_get_msr_feature(&msr))
5963 continue;
5964
David Brazdil0f672f62019-12-10 10:32:29 +00005965 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005966 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005967}
5968
5969static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5970 const void *v)
5971{
5972 int handled = 0;
5973 int n;
5974
5975 do {
5976 n = min(len, 8);
5977 if (!(lapic_in_kernel(vcpu) &&
5978 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5979 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5980 break;
5981 handled += n;
5982 addr += n;
5983 len -= n;
5984 v += n;
5985 } while (len);
5986
5987 return handled;
5988}
5989
5990static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5991{
5992 int handled = 0;
5993 int n;
5994
5995 do {
5996 n = min(len, 8);
5997 if (!(lapic_in_kernel(vcpu) &&
5998 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5999 addr, n, v))
6000 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
6001 break;
6002 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
6003 handled += n;
6004 addr += n;
6005 len -= n;
6006 v += n;
6007 } while (len);
6008
6009 return handled;
6010}
6011
6012static void kvm_set_segment(struct kvm_vcpu *vcpu,
6013 struct kvm_segment *var, int seg)
6014{
Olivier Deprez157378f2022-04-04 15:47:50 +02006015 kvm_x86_ops.set_segment(vcpu, var, seg);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006016}
6017
6018void kvm_get_segment(struct kvm_vcpu *vcpu,
6019 struct kvm_segment *var, int seg)
6020{
Olivier Deprez157378f2022-04-04 15:47:50 +02006021 kvm_x86_ops.get_segment(vcpu, var, seg);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006022}
6023
6024gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
6025 struct x86_exception *exception)
6026{
6027 gpa_t t_gpa;
6028
6029 BUG_ON(!mmu_is_nested(vcpu));
6030
6031 /* NPT walks are always user-walks */
6032 access |= PFERR_USER_MASK;
David Brazdil0f672f62019-12-10 10:32:29 +00006033 t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006034
6035 return t_gpa;
6036}
6037
6038gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
6039 struct x86_exception *exception)
6040{
Olivier Deprez157378f2022-04-04 15:47:50 +02006041 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006042 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6043}
6044
6045 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
6046 struct x86_exception *exception)
6047{
Olivier Deprez157378f2022-04-04 15:47:50 +02006048 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006049 access |= PFERR_FETCH_MASK;
6050 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6051}
6052
6053gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
6054 struct x86_exception *exception)
6055{
Olivier Deprez157378f2022-04-04 15:47:50 +02006056 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006057 access |= PFERR_WRITE_MASK;
6058 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6059}
6060
6061/* uses this to access any guest's mapped memory without checking CPL */
6062gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
6063 struct x86_exception *exception)
6064{
6065 return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
6066}
6067
6068static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6069 struct kvm_vcpu *vcpu, u32 access,
6070 struct x86_exception *exception)
6071{
6072 void *data = val;
6073 int r = X86EMUL_CONTINUE;
6074
6075 while (bytes) {
6076 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
6077 exception);
6078 unsigned offset = addr & (PAGE_SIZE-1);
6079 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
6080 int ret;
6081
6082 if (gpa == UNMAPPED_GVA)
6083 return X86EMUL_PROPAGATE_FAULT;
6084 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
6085 offset, toread);
6086 if (ret < 0) {
6087 r = X86EMUL_IO_NEEDED;
6088 goto out;
6089 }
6090
6091 bytes -= toread;
6092 data += toread;
6093 addr += toread;
6094 }
6095out:
6096 return r;
6097}
6098
6099/* used for instruction fetching */
6100static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
6101 gva_t addr, void *val, unsigned int bytes,
6102 struct x86_exception *exception)
6103{
6104 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Olivier Deprez157378f2022-04-04 15:47:50 +02006105 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006106 unsigned offset;
6107 int ret;
6108
6109 /* Inline kvm_read_guest_virt_helper for speed. */
6110 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
6111 exception);
6112 if (unlikely(gpa == UNMAPPED_GVA))
6113 return X86EMUL_PROPAGATE_FAULT;
6114
6115 offset = addr & (PAGE_SIZE-1);
6116 if (WARN_ON(offset + bytes > PAGE_SIZE))
6117 bytes = (unsigned)PAGE_SIZE - offset;
6118 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
6119 offset, bytes);
6120 if (unlikely(ret < 0))
6121 return X86EMUL_IO_NEEDED;
6122
6123 return X86EMUL_CONTINUE;
6124}
6125
6126int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
6127 gva_t addr, void *val, unsigned int bytes,
6128 struct x86_exception *exception)
6129{
Olivier Deprez157378f2022-04-04 15:47:50 +02006130 u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006131
David Brazdil0f672f62019-12-10 10:32:29 +00006132 /*
6133 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
6134 * is returned, but our callers are not ready for that and they blindly
6135 * call kvm_inject_page_fault. Ensure that they at least do not leak
6136 * uninitialized kernel stack memory into cr2 and error code.
6137 */
6138 memset(exception, 0, sizeof(*exception));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006139 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
6140 exception);
6141}
6142EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
6143
6144static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
6145 gva_t addr, void *val, unsigned int bytes,
6146 struct x86_exception *exception, bool system)
6147{
6148 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6149 u32 access = 0;
6150
Olivier Deprez157378f2022-04-04 15:47:50 +02006151 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006152 access |= PFERR_USER_MASK;
6153
6154 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
6155}
6156
6157static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
6158 unsigned long addr, void *val, unsigned int bytes)
6159{
6160 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6161 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
6162
6163 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
6164}
6165
6166static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6167 struct kvm_vcpu *vcpu, u32 access,
6168 struct x86_exception *exception)
6169{
6170 void *data = val;
6171 int r = X86EMUL_CONTINUE;
6172
6173 while (bytes) {
6174 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
6175 access,
6176 exception);
6177 unsigned offset = addr & (PAGE_SIZE-1);
6178 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
6179 int ret;
6180
6181 if (gpa == UNMAPPED_GVA)
6182 return X86EMUL_PROPAGATE_FAULT;
6183 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
6184 if (ret < 0) {
6185 r = X86EMUL_IO_NEEDED;
6186 goto out;
6187 }
6188
6189 bytes -= towrite;
6190 data += towrite;
6191 addr += towrite;
6192 }
6193out:
6194 return r;
6195}
6196
6197static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
6198 unsigned int bytes, struct x86_exception *exception,
6199 bool system)
6200{
6201 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6202 u32 access = PFERR_WRITE_MASK;
6203
Olivier Deprez157378f2022-04-04 15:47:50 +02006204 if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006205 access |= PFERR_USER_MASK;
6206
6207 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6208 access, exception);
6209}
6210
6211int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
6212 unsigned int bytes, struct x86_exception *exception)
6213{
6214 /* kvm_write_guest_virt_system can pull in tons of pages. */
6215 vcpu->arch.l1tf_flush_l1d = true;
6216
6217 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6218 PFERR_WRITE_MASK, exception);
6219}
6220EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
6221
6222int handle_ud(struct kvm_vcpu *vcpu)
6223{
Olivier Deprez157378f2022-04-04 15:47:50 +02006224 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006225 int emul_type = EMULTYPE_TRAP_UD;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006226 char sig[5]; /* ud2; .ascii "kvm" */
6227 struct x86_exception e;
6228
Olivier Deprez157378f2022-04-04 15:47:50 +02006229 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, NULL, 0)))
6230 return 1;
6231
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006232 if (force_emulation_prefix &&
6233 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
6234 sig, sizeof(sig), &e) == 0 &&
Olivier Deprez157378f2022-04-04 15:47:50 +02006235 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006236 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
David Brazdil0f672f62019-12-10 10:32:29 +00006237 emul_type = EMULTYPE_TRAP_UD_FORCED;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006238 }
6239
David Brazdil0f672f62019-12-10 10:32:29 +00006240 return kvm_emulate_instruction(vcpu, emul_type);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006241}
6242EXPORT_SYMBOL_GPL(handle_ud);
6243
6244static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6245 gpa_t gpa, bool write)
6246{
6247 /* For APIC access vmexit */
6248 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6249 return 1;
6250
6251 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
6252 trace_vcpu_match_mmio(gva, gpa, write, true);
6253 return 1;
6254 }
6255
6256 return 0;
6257}
6258
6259static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6260 gpa_t *gpa, struct x86_exception *exception,
6261 bool write)
6262{
Olivier Deprez157378f2022-04-04 15:47:50 +02006263 u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006264 | (write ? PFERR_WRITE_MASK : 0);
6265
6266 /*
6267 * currently PKRU is only applied to ept enabled guest so
6268 * there is no pkey in EPT page table for L1 guest or EPT
6269 * shadow page table for L2 guest.
6270 */
6271 if (vcpu_match_mmio_gva(vcpu, gva)
6272 && !permission_fault(vcpu, vcpu->arch.walk_mmu,
David Brazdil0f672f62019-12-10 10:32:29 +00006273 vcpu->arch.mmio_access, 0, access)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006274 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
6275 (gva & (PAGE_SIZE - 1));
6276 trace_vcpu_match_mmio(gva, *gpa, write, false);
6277 return 1;
6278 }
6279
6280 *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
6281
6282 if (*gpa == UNMAPPED_GVA)
6283 return -1;
6284
6285 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
6286}
6287
6288int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
6289 const void *val, int bytes)
6290{
6291 int ret;
6292
6293 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
6294 if (ret < 0)
6295 return 0;
6296 kvm_page_track_write(vcpu, gpa, val, bytes);
6297 return 1;
6298}
6299
6300struct read_write_emulator_ops {
6301 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
6302 int bytes);
6303 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
6304 void *val, int bytes);
6305 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6306 int bytes, void *val);
6307 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6308 void *val, int bytes);
6309 bool write;
6310};
6311
6312static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
6313{
6314 if (vcpu->mmio_read_completed) {
6315 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
6316 vcpu->mmio_fragments[0].gpa, val);
6317 vcpu->mmio_read_completed = 0;
6318 return 1;
6319 }
6320
6321 return 0;
6322}
6323
6324static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6325 void *val, int bytes)
6326{
6327 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
6328}
6329
6330static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6331 void *val, int bytes)
6332{
6333 return emulator_write_phys(vcpu, gpa, val, bytes);
6334}
6335
6336static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
6337{
6338 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
6339 return vcpu_mmio_write(vcpu, gpa, bytes, val);
6340}
6341
6342static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6343 void *val, int bytes)
6344{
6345 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
6346 return X86EMUL_IO_NEEDED;
6347}
6348
6349static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
6350 void *val, int bytes)
6351{
6352 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
6353
6354 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
6355 return X86EMUL_CONTINUE;
6356}
6357
6358static const struct read_write_emulator_ops read_emultor = {
6359 .read_write_prepare = read_prepare,
6360 .read_write_emulate = read_emulate,
6361 .read_write_mmio = vcpu_mmio_read,
6362 .read_write_exit_mmio = read_exit_mmio,
6363};
6364
6365static const struct read_write_emulator_ops write_emultor = {
6366 .read_write_emulate = write_emulate,
6367 .read_write_mmio = write_mmio,
6368 .read_write_exit_mmio = write_exit_mmio,
6369 .write = true,
6370};
6371
6372static int emulator_read_write_onepage(unsigned long addr, void *val,
6373 unsigned int bytes,
6374 struct x86_exception *exception,
6375 struct kvm_vcpu *vcpu,
6376 const struct read_write_emulator_ops *ops)
6377{
6378 gpa_t gpa;
6379 int handled, ret;
6380 bool write = ops->write;
6381 struct kvm_mmio_fragment *frag;
Olivier Deprez157378f2022-04-04 15:47:50 +02006382 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006383
6384 /*
6385 * If the exit was due to a NPF we may already have a GPA.
6386 * If the GPA is present, use it to avoid the GVA to GPA table walk.
6387 * Note, this cannot be used on string operations since string
6388 * operation using rep will only have the initial GPA from the NPF
6389 * occurred.
6390 */
Olivier Deprez157378f2022-04-04 15:47:50 +02006391 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
6392 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
6393 gpa = ctxt->gpa_val;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006394 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
6395 } else {
6396 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
6397 if (ret < 0)
6398 return X86EMUL_PROPAGATE_FAULT;
6399 }
6400
6401 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
6402 return X86EMUL_CONTINUE;
6403
6404 /*
6405 * Is this MMIO handled locally?
6406 */
6407 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
6408 if (handled == bytes)
6409 return X86EMUL_CONTINUE;
6410
6411 gpa += handled;
6412 bytes -= handled;
6413 val += handled;
6414
6415 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
6416 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
6417 frag->gpa = gpa;
6418 frag->data = val;
6419 frag->len = bytes;
6420 return X86EMUL_CONTINUE;
6421}
6422
6423static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
6424 unsigned long addr,
6425 void *val, unsigned int bytes,
6426 struct x86_exception *exception,
6427 const struct read_write_emulator_ops *ops)
6428{
6429 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6430 gpa_t gpa;
6431 int rc;
6432
6433 if (ops->read_write_prepare &&
6434 ops->read_write_prepare(vcpu, val, bytes))
6435 return X86EMUL_CONTINUE;
6436
6437 vcpu->mmio_nr_fragments = 0;
6438
6439 /* Crossing a page boundary? */
6440 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
6441 int now;
6442
6443 now = -addr & ~PAGE_MASK;
6444 rc = emulator_read_write_onepage(addr, val, now, exception,
6445 vcpu, ops);
6446
6447 if (rc != X86EMUL_CONTINUE)
6448 return rc;
6449 addr += now;
6450 if (ctxt->mode != X86EMUL_MODE_PROT64)
6451 addr = (u32)addr;
6452 val += now;
6453 bytes -= now;
6454 }
6455
6456 rc = emulator_read_write_onepage(addr, val, bytes, exception,
6457 vcpu, ops);
6458 if (rc != X86EMUL_CONTINUE)
6459 return rc;
6460
6461 if (!vcpu->mmio_nr_fragments)
6462 return rc;
6463
6464 gpa = vcpu->mmio_fragments[0].gpa;
6465
6466 vcpu->mmio_needed = 1;
6467 vcpu->mmio_cur_fragment = 0;
6468
6469 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
6470 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
6471 vcpu->run->exit_reason = KVM_EXIT_MMIO;
6472 vcpu->run->mmio.phys_addr = gpa;
6473
6474 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
6475}
6476
6477static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
6478 unsigned long addr,
6479 void *val,
6480 unsigned int bytes,
6481 struct x86_exception *exception)
6482{
6483 return emulator_read_write(ctxt, addr, val, bytes,
6484 exception, &read_emultor);
6485}
6486
6487static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
6488 unsigned long addr,
6489 const void *val,
6490 unsigned int bytes,
6491 struct x86_exception *exception)
6492{
6493 return emulator_read_write(ctxt, addr, (void *)val, bytes,
6494 exception, &write_emultor);
6495}
6496
6497#define CMPXCHG_TYPE(t, ptr, old, new) \
6498 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
6499
6500#ifdef CONFIG_X86_64
6501# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
6502#else
6503# define CMPXCHG64(ptr, old, new) \
6504 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
6505#endif
6506
6507static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
6508 unsigned long addr,
6509 const void *old,
6510 const void *new,
6511 unsigned int bytes,
6512 struct x86_exception *exception)
6513{
David Brazdil0f672f62019-12-10 10:32:29 +00006514 struct kvm_host_map map;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006515 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Olivier Deprez157378f2022-04-04 15:47:50 +02006516 u64 page_line_mask;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006517 gpa_t gpa;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006518 char *kaddr;
6519 bool exchanged;
6520
6521 /* guests cmpxchg8b have to be emulated atomically */
6522 if (bytes > 8 || (bytes & (bytes - 1)))
6523 goto emul_write;
6524
6525 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
6526
6527 if (gpa == UNMAPPED_GVA ||
6528 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6529 goto emul_write;
6530
Olivier Deprez157378f2022-04-04 15:47:50 +02006531 /*
6532 * Emulate the atomic as a straight write to avoid #AC if SLD is
6533 * enabled in the host and the access splits a cache line.
6534 */
6535 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6536 page_line_mask = ~(cache_line_size() - 1);
6537 else
6538 page_line_mask = PAGE_MASK;
6539
6540 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006541 goto emul_write;
6542
David Brazdil0f672f62019-12-10 10:32:29 +00006543 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006544 goto emul_write;
6545
David Brazdil0f672f62019-12-10 10:32:29 +00006546 kaddr = map.hva + offset_in_page(gpa);
6547
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006548 switch (bytes) {
6549 case 1:
6550 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6551 break;
6552 case 2:
6553 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6554 break;
6555 case 4:
6556 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6557 break;
6558 case 8:
6559 exchanged = CMPXCHG64(kaddr, old, new);
6560 break;
6561 default:
6562 BUG();
6563 }
David Brazdil0f672f62019-12-10 10:32:29 +00006564
6565 kvm_vcpu_unmap(vcpu, &map, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006566
6567 if (!exchanged)
6568 return X86EMUL_CMPXCHG_FAILED;
6569
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006570 kvm_page_track_write(vcpu, gpa, new, bytes);
6571
6572 return X86EMUL_CONTINUE;
6573
6574emul_write:
6575 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6576
6577 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6578}
6579
6580static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6581{
6582 int r = 0, i;
6583
6584 for (i = 0; i < vcpu->arch.pio.count; i++) {
6585 if (vcpu->arch.pio.in)
6586 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6587 vcpu->arch.pio.size, pd);
6588 else
6589 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6590 vcpu->arch.pio.port, vcpu->arch.pio.size,
6591 pd);
6592 if (r)
6593 break;
6594 pd += vcpu->arch.pio.size;
6595 }
6596 return r;
6597}
6598
6599static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6600 unsigned short port, void *val,
6601 unsigned int count, bool in)
6602{
6603 vcpu->arch.pio.port = port;
6604 vcpu->arch.pio.in = in;
6605 vcpu->arch.pio.count = count;
6606 vcpu->arch.pio.size = size;
6607
6608 if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6609 vcpu->arch.pio.count = 0;
6610 return 1;
6611 }
6612
6613 vcpu->run->exit_reason = KVM_EXIT_IO;
6614 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6615 vcpu->run->io.size = size;
6616 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6617 vcpu->run->io.count = count;
6618 vcpu->run->io.port = port;
6619
6620 return 0;
6621}
6622
Olivier Deprez157378f2022-04-04 15:47:50 +02006623static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6624 unsigned short port, void *val, unsigned int count)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006625{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006626 int ret;
6627
6628 if (vcpu->arch.pio.count)
6629 goto data_avail;
6630
6631 memset(vcpu->arch.pio_data, 0, size * count);
6632
6633 ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6634 if (ret) {
6635data_avail:
6636 memcpy(val, vcpu->arch.pio_data, size * count);
6637 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6638 vcpu->arch.pio.count = 0;
6639 return 1;
6640 }
6641
6642 return 0;
6643}
6644
Olivier Deprez157378f2022-04-04 15:47:50 +02006645static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6646 int size, unsigned short port, void *val,
6647 unsigned int count)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006648{
Olivier Deprez157378f2022-04-04 15:47:50 +02006649 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006650
Olivier Deprez157378f2022-04-04 15:47:50 +02006651}
6652
6653static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6654 unsigned short port, const void *val,
6655 unsigned int count)
6656{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006657 memcpy(vcpu->arch.pio_data, val, size * count);
6658 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6659 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6660}
6661
Olivier Deprez157378f2022-04-04 15:47:50 +02006662static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6663 int size, unsigned short port,
6664 const void *val, unsigned int count)
6665{
6666 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6667}
6668
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006669static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6670{
Olivier Deprez157378f2022-04-04 15:47:50 +02006671 return kvm_x86_ops.get_segment_base(vcpu, seg);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006672}
6673
6674static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6675{
6676 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6677}
6678
6679static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6680{
6681 if (!need_emulate_wbinvd(vcpu))
6682 return X86EMUL_CONTINUE;
6683
Olivier Deprez157378f2022-04-04 15:47:50 +02006684 if (kvm_x86_ops.has_wbinvd_exit()) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006685 int cpu = get_cpu();
6686
6687 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6688 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6689 wbinvd_ipi, NULL, 1);
6690 put_cpu();
6691 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6692 } else
6693 wbinvd();
6694 return X86EMUL_CONTINUE;
6695}
6696
6697int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6698{
6699 kvm_emulate_wbinvd_noskip(vcpu);
6700 return kvm_skip_emulated_instruction(vcpu);
6701}
6702EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6703
6704
6705
6706static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6707{
6708 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6709}
6710
6711static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6712 unsigned long *dest)
6713{
6714 return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6715}
6716
6717static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6718 unsigned long value)
6719{
6720
6721 return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6722}
6723
6724static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6725{
6726 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6727}
6728
6729static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6730{
6731 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6732 unsigned long value;
6733
6734 switch (cr) {
6735 case 0:
6736 value = kvm_read_cr0(vcpu);
6737 break;
6738 case 2:
6739 value = vcpu->arch.cr2;
6740 break;
6741 case 3:
6742 value = kvm_read_cr3(vcpu);
6743 break;
6744 case 4:
6745 value = kvm_read_cr4(vcpu);
6746 break;
6747 case 8:
6748 value = kvm_get_cr8(vcpu);
6749 break;
6750 default:
6751 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6752 return 0;
6753 }
6754
6755 return value;
6756}
6757
6758static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6759{
6760 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6761 int res = 0;
6762
6763 switch (cr) {
6764 case 0:
6765 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6766 break;
6767 case 2:
6768 vcpu->arch.cr2 = val;
6769 break;
6770 case 3:
6771 res = kvm_set_cr3(vcpu, val);
6772 break;
6773 case 4:
6774 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6775 break;
6776 case 8:
6777 res = kvm_set_cr8(vcpu, val);
6778 break;
6779 default:
6780 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6781 res = -1;
6782 }
6783
6784 return res;
6785}
6786
6787static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6788{
Olivier Deprez157378f2022-04-04 15:47:50 +02006789 return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006790}
6791
6792static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6793{
Olivier Deprez157378f2022-04-04 15:47:50 +02006794 kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006795}
6796
6797static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6798{
Olivier Deprez157378f2022-04-04 15:47:50 +02006799 kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006800}
6801
6802static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6803{
Olivier Deprez157378f2022-04-04 15:47:50 +02006804 kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006805}
6806
6807static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6808{
Olivier Deprez157378f2022-04-04 15:47:50 +02006809 kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006810}
6811
6812static unsigned long emulator_get_cached_segment_base(
6813 struct x86_emulate_ctxt *ctxt, int seg)
6814{
6815 return get_segment_base(emul_to_vcpu(ctxt), seg);
6816}
6817
6818static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6819 struct desc_struct *desc, u32 *base3,
6820 int seg)
6821{
6822 struct kvm_segment var;
6823
6824 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6825 *selector = var.selector;
6826
6827 if (var.unusable) {
6828 memset(desc, 0, sizeof(*desc));
6829 if (base3)
6830 *base3 = 0;
6831 return false;
6832 }
6833
6834 if (var.g)
6835 var.limit >>= 12;
6836 set_desc_limit(desc, var.limit);
6837 set_desc_base(desc, (unsigned long)var.base);
6838#ifdef CONFIG_X86_64
6839 if (base3)
6840 *base3 = var.base >> 32;
6841#endif
6842 desc->type = var.type;
6843 desc->s = var.s;
6844 desc->dpl = var.dpl;
6845 desc->p = var.present;
6846 desc->avl = var.avl;
6847 desc->l = var.l;
6848 desc->d = var.db;
6849 desc->g = var.g;
6850
6851 return true;
6852}
6853
6854static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6855 struct desc_struct *desc, u32 base3,
6856 int seg)
6857{
6858 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6859 struct kvm_segment var;
6860
6861 var.selector = selector;
6862 var.base = get_desc_base(desc);
6863#ifdef CONFIG_X86_64
6864 var.base |= ((u64)base3) << 32;
6865#endif
6866 var.limit = get_desc_limit(desc);
6867 if (desc->g)
6868 var.limit = (var.limit << 12) | 0xfff;
6869 var.type = desc->type;
6870 var.dpl = desc->dpl;
6871 var.db = desc->d;
6872 var.s = desc->s;
6873 var.l = desc->l;
6874 var.g = desc->g;
6875 var.avl = desc->avl;
6876 var.present = desc->p;
6877 var.unusable = !var.present;
6878 var.padding = 0;
6879
6880 kvm_set_segment(vcpu, &var, seg);
6881 return;
6882}
6883
6884static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6885 u32 msr_index, u64 *pdata)
6886{
Olivier Deprez157378f2022-04-04 15:47:50 +02006887 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6888 int r;
6889
6890 r = kvm_get_msr(vcpu, msr_index, pdata);
6891
6892 if (r && kvm_get_msr_user_space(vcpu, msr_index, r)) {
6893 /* Bounce to user space */
6894 return X86EMUL_IO_NEEDED;
6895 }
6896
6897 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006898}
6899
6900static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6901 u32 msr_index, u64 data)
6902{
Olivier Deprez157378f2022-04-04 15:47:50 +02006903 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6904 int r;
6905
6906 r = kvm_set_msr(vcpu, msr_index, data);
6907
6908 if (r && kvm_set_msr_user_space(vcpu, msr_index, data, r)) {
6909 /* Bounce to user space */
6910 return X86EMUL_IO_NEEDED;
6911 }
6912
6913 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006914}
6915
6916static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6917{
6918 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6919
6920 return vcpu->arch.smbase;
6921}
6922
6923static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6924{
6925 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6926
6927 vcpu->arch.smbase = smbase;
6928}
6929
6930static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6931 u32 pmc)
6932{
Olivier Deprez157378f2022-04-04 15:47:50 +02006933 return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006934}
6935
6936static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6937 u32 pmc, u64 *pdata)
6938{
6939 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6940}
6941
6942static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6943{
6944 emul_to_vcpu(ctxt)->arch.halt_request = 1;
6945}
6946
6947static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6948 struct x86_instruction_info *info,
6949 enum x86_intercept_stage stage)
6950{
Olivier Deprez157378f2022-04-04 15:47:50 +02006951 return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6952 &ctxt->exception);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006953}
6954
6955static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
Olivier Deprez157378f2022-04-04 15:47:50 +02006956 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6957 bool exact_only)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006958{
Olivier Deprez157378f2022-04-04 15:47:50 +02006959 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6960}
6961
6962static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6963{
6964 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6965}
6966
6967static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6968{
6969 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6970}
6971
6972static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6973{
6974 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006975}
6976
Olivier Deprez92d4c212022-12-06 15:05:30 +01006977static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
6978{
6979 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
6980}
6981
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006982static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6983{
6984 return kvm_register_read(emul_to_vcpu(ctxt), reg);
6985}
6986
6987static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6988{
6989 kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6990}
6991
6992static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6993{
Olivier Deprez157378f2022-04-04 15:47:50 +02006994 kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006995}
6996
6997static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6998{
6999 return emul_to_vcpu(ctxt)->arch.hflags;
7000}
7001
7002static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
7003{
Olivier Deprez0e641232021-09-23 10:07:05 +02007004 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7005
7006 vcpu->arch.hflags = emul_flags;
7007 kvm_mmu_reset_context(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007008}
7009
David Brazdil0f672f62019-12-10 10:32:29 +00007010static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
7011 const char *smstate)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007012{
Olivier Deprez157378f2022-04-04 15:47:50 +02007013 return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
David Brazdil0f672f62019-12-10 10:32:29 +00007014}
7015
7016static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
7017{
7018 kvm_smm_changed(emul_to_vcpu(ctxt));
7019}
7020
7021static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
7022{
7023 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007024}
7025
7026static const struct x86_emulate_ops emulate_ops = {
7027 .read_gpr = emulator_read_gpr,
7028 .write_gpr = emulator_write_gpr,
7029 .read_std = emulator_read_std,
7030 .write_std = emulator_write_std,
7031 .read_phys = kvm_read_guest_phys_system,
7032 .fetch = kvm_fetch_guest_virt,
7033 .read_emulated = emulator_read_emulated,
7034 .write_emulated = emulator_write_emulated,
7035 .cmpxchg_emulated = emulator_cmpxchg_emulated,
7036 .invlpg = emulator_invlpg,
7037 .pio_in_emulated = emulator_pio_in_emulated,
7038 .pio_out_emulated = emulator_pio_out_emulated,
7039 .get_segment = emulator_get_segment,
7040 .set_segment = emulator_set_segment,
7041 .get_cached_segment_base = emulator_get_cached_segment_base,
7042 .get_gdt = emulator_get_gdt,
7043 .get_idt = emulator_get_idt,
7044 .set_gdt = emulator_set_gdt,
7045 .set_idt = emulator_set_idt,
7046 .get_cr = emulator_get_cr,
7047 .set_cr = emulator_set_cr,
7048 .cpl = emulator_get_cpl,
7049 .get_dr = emulator_get_dr,
7050 .set_dr = emulator_set_dr,
7051 .get_smbase = emulator_get_smbase,
7052 .set_smbase = emulator_set_smbase,
7053 .set_msr = emulator_set_msr,
7054 .get_msr = emulator_get_msr,
7055 .check_pmc = emulator_check_pmc,
7056 .read_pmc = emulator_read_pmc,
7057 .halt = emulator_halt,
7058 .wbinvd = emulator_wbinvd,
7059 .fix_hypercall = emulator_fix_hypercall,
7060 .intercept = emulator_intercept,
7061 .get_cpuid = emulator_get_cpuid,
Olivier Deprez157378f2022-04-04 15:47:50 +02007062 .guest_has_long_mode = emulator_guest_has_long_mode,
7063 .guest_has_movbe = emulator_guest_has_movbe,
7064 .guest_has_fxsr = emulator_guest_has_fxsr,
Olivier Deprez92d4c212022-12-06 15:05:30 +01007065 .guest_has_rdpid = emulator_guest_has_rdpid,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007066 .set_nmi_mask = emulator_set_nmi_mask,
7067 .get_hflags = emulator_get_hflags,
7068 .set_hflags = emulator_set_hflags,
7069 .pre_leave_smm = emulator_pre_leave_smm,
David Brazdil0f672f62019-12-10 10:32:29 +00007070 .post_leave_smm = emulator_post_leave_smm,
7071 .set_xcr = emulator_set_xcr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007072};
7073
7074static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
7075{
Olivier Deprez157378f2022-04-04 15:47:50 +02007076 u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007077 /*
7078 * an sti; sti; sequence only disable interrupts for the first
7079 * instruction. So, if the last instruction, be it emulated or
7080 * not, left the system with the INT_STI flag enabled, it
7081 * means that the last instruction is an sti. We should not
7082 * leave the flag on in this case. The same goes for mov ss
7083 */
7084 if (int_shadow & mask)
7085 mask = 0;
7086 if (unlikely(int_shadow || mask)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007087 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007088 if (!mask)
7089 kvm_make_request(KVM_REQ_EVENT, vcpu);
7090 }
7091}
7092
7093static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
7094{
Olivier Deprez157378f2022-04-04 15:47:50 +02007095 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007096 if (ctxt->exception.vector == PF_VECTOR)
Olivier Deprez157378f2022-04-04 15:47:50 +02007097 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007098
7099 if (ctxt->exception.error_code_valid)
7100 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
7101 ctxt->exception.error_code);
7102 else
7103 kvm_queue_exception(vcpu, ctxt->exception.vector);
7104 return false;
7105}
7106
Olivier Deprez157378f2022-04-04 15:47:50 +02007107static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
7108{
7109 struct x86_emulate_ctxt *ctxt;
7110
7111 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
7112 if (!ctxt) {
7113 pr_err("kvm: failed to allocate vcpu's emulator\n");
7114 return NULL;
7115 }
7116
7117 ctxt->vcpu = vcpu;
7118 ctxt->ops = &emulate_ops;
7119 vcpu->arch.emulate_ctxt = ctxt;
7120
7121 return ctxt;
7122}
7123
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007124static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
7125{
Olivier Deprez157378f2022-04-04 15:47:50 +02007126 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007127 int cs_db, cs_l;
7128
Olivier Deprez157378f2022-04-04 15:47:50 +02007129 kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007130
Olivier Deprez157378f2022-04-04 15:47:50 +02007131 ctxt->gpa_available = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007132 ctxt->eflags = kvm_get_rflags(vcpu);
7133 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
7134
7135 ctxt->eip = kvm_rip_read(vcpu);
7136 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
7137 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
7138 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
7139 cs_db ? X86EMUL_MODE_PROT32 :
7140 X86EMUL_MODE_PROT16;
7141 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
7142 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
7143 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
7144
Olivier Deprez157378f2022-04-04 15:47:50 +02007145 ctxt->interruptibility = 0;
7146 ctxt->have_exception = false;
7147 ctxt->exception.vector = -1;
7148 ctxt->perm_ok = false;
7149
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007150 init_decode_cache(ctxt);
7151 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7152}
7153
David Brazdil0f672f62019-12-10 10:32:29 +00007154void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007155{
Olivier Deprez157378f2022-04-04 15:47:50 +02007156 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007157 int ret;
7158
7159 init_emulate_ctxt(vcpu);
7160
7161 ctxt->op_bytes = 2;
7162 ctxt->ad_bytes = 2;
7163 ctxt->_eip = ctxt->eip + inc_eip;
7164 ret = emulate_int_real(ctxt, irq);
7165
David Brazdil0f672f62019-12-10 10:32:29 +00007166 if (ret != X86EMUL_CONTINUE) {
7167 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7168 } else {
7169 ctxt->eip = ctxt->_eip;
7170 kvm_rip_write(vcpu, ctxt->eip);
7171 kvm_set_rflags(vcpu, ctxt->eflags);
7172 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007173}
7174EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
7175
7176static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
7177{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007178 ++vcpu->stat.insn_emulation_fail;
7179 trace_kvm_emulate_insn_failed(vcpu);
7180
David Brazdil0f672f62019-12-10 10:32:29 +00007181 if (emulation_type & EMULTYPE_VMWARE_GP) {
7182 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7183 return 1;
7184 }
7185
7186 if (emulation_type & EMULTYPE_SKIP) {
7187 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7188 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7189 vcpu->run->internal.ndata = 0;
7190 return 0;
7191 }
7192
7193 kvm_queue_exception(vcpu, UD_VECTOR);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007194
Olivier Deprez157378f2022-04-04 15:47:50 +02007195 if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007196 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7197 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7198 vcpu->run->internal.ndata = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00007199 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007200 }
7201
David Brazdil0f672f62019-12-10 10:32:29 +00007202 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007203}
7204
Olivier Deprez0e641232021-09-23 10:07:05 +02007205static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007206 bool write_fault_to_shadow_pgtable,
7207 int emulation_type)
7208{
Olivier Deprez0e641232021-09-23 10:07:05 +02007209 gpa_t gpa = cr2_or_gpa;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007210 kvm_pfn_t pfn;
7211
Olivier Deprez157378f2022-04-04 15:47:50 +02007212 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007213 return false;
7214
Olivier Deprez157378f2022-04-04 15:47:50 +02007215 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7216 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007217 return false;
7218
David Brazdil0f672f62019-12-10 10:32:29 +00007219 if (!vcpu->arch.mmu->direct_map) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007220 /*
7221 * Write permission should be allowed since only
7222 * write access need to be emulated.
7223 */
Olivier Deprez0e641232021-09-23 10:07:05 +02007224 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007225
7226 /*
7227 * If the mapping is invalid in guest, let cpu retry
7228 * it to generate fault.
7229 */
7230 if (gpa == UNMAPPED_GVA)
7231 return true;
7232 }
7233
7234 /*
7235 * Do not retry the unhandleable instruction if it faults on the
7236 * readonly host memory, otherwise it will goto a infinite loop:
7237 * retry instruction -> write #PF -> emulation fail -> retry
7238 * instruction -> ...
7239 */
7240 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
7241
7242 /*
7243 * If the instruction failed on the error pfn, it can not be fixed,
7244 * report the error to userspace.
7245 */
7246 if (is_error_noslot_pfn(pfn))
7247 return false;
7248
7249 kvm_release_pfn_clean(pfn);
7250
7251 /* The instructions are well-emulated on direct mmu. */
David Brazdil0f672f62019-12-10 10:32:29 +00007252 if (vcpu->arch.mmu->direct_map) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007253 unsigned int indirect_shadow_pages;
7254
7255 spin_lock(&vcpu->kvm->mmu_lock);
7256 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
7257 spin_unlock(&vcpu->kvm->mmu_lock);
7258
7259 if (indirect_shadow_pages)
7260 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7261
7262 return true;
7263 }
7264
7265 /*
7266 * if emulation was due to access to shadowed page table
7267 * and it failed try to unshadow page and re-enter the
7268 * guest to let CPU execute the instruction.
7269 */
7270 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7271
7272 /*
7273 * If the access faults on its page table, it can not
7274 * be fixed by unprotecting shadow page and it should
7275 * be reported to userspace.
7276 */
7277 return !write_fault_to_shadow_pgtable;
7278}
7279
7280static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
Olivier Deprez0e641232021-09-23 10:07:05 +02007281 gpa_t cr2_or_gpa, int emulation_type)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007282{
7283 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Olivier Deprez0e641232021-09-23 10:07:05 +02007284 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007285
7286 last_retry_eip = vcpu->arch.last_retry_eip;
7287 last_retry_addr = vcpu->arch.last_retry_addr;
7288
7289 /*
7290 * If the emulation is caused by #PF and it is non-page_table
7291 * writing instruction, it means the VM-EXIT is caused by shadow
7292 * page protected, we can zap the shadow page and retry this
7293 * instruction directly.
7294 *
7295 * Note: if the guest uses a non-page-table modifying instruction
7296 * on the PDE that points to the instruction, then we will unmap
7297 * the instruction and go to an infinite loop. So, we cache the
7298 * last retried eip and the last fault address, if we meet the eip
7299 * and the address again, we can break out of the potential infinite
7300 * loop.
7301 */
7302 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
7303
Olivier Deprez157378f2022-04-04 15:47:50 +02007304 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007305 return false;
7306
Olivier Deprez157378f2022-04-04 15:47:50 +02007307 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7308 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007309 return false;
7310
7311 if (x86_page_table_writing_insn(ctxt))
7312 return false;
7313
Olivier Deprez0e641232021-09-23 10:07:05 +02007314 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007315 return false;
7316
7317 vcpu->arch.last_retry_eip = ctxt->eip;
Olivier Deprez0e641232021-09-23 10:07:05 +02007318 vcpu->arch.last_retry_addr = cr2_or_gpa;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007319
David Brazdil0f672f62019-12-10 10:32:29 +00007320 if (!vcpu->arch.mmu->direct_map)
Olivier Deprez0e641232021-09-23 10:07:05 +02007321 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007322
7323 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
7324
7325 return true;
7326}
7327
7328static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
7329static int complete_emulated_pio(struct kvm_vcpu *vcpu);
7330
7331static void kvm_smm_changed(struct kvm_vcpu *vcpu)
7332{
7333 if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
7334 /* This is a good place to trace that we are exiting SMM. */
7335 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
7336
7337 /* Process a latched INIT or SMI, if any. */
7338 kvm_make_request(KVM_REQ_EVENT, vcpu);
7339 }
7340
7341 kvm_mmu_reset_context(vcpu);
7342}
7343
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007344static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
7345 unsigned long *db)
7346{
7347 u32 dr6 = 0;
7348 int i;
7349 u32 enable, rwlen;
7350
7351 enable = dr7;
7352 rwlen = dr7 >> 16;
7353 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
7354 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
7355 dr6 |= (1 << i);
7356 return dr6;
7357}
7358
David Brazdil0f672f62019-12-10 10:32:29 +00007359static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007360{
7361 struct kvm_run *kvm_run = vcpu->run;
7362
7363 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
7364 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
Olivier Deprez157378f2022-04-04 15:47:50 +02007365 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007366 kvm_run->debug.arch.exception = DB_VECTOR;
7367 kvm_run->exit_reason = KVM_EXIT_DEBUG;
David Brazdil0f672f62019-12-10 10:32:29 +00007368 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007369 }
David Brazdil0f672f62019-12-10 10:32:29 +00007370 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
7371 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007372}
7373
7374int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
7375{
Olivier Deprez157378f2022-04-04 15:47:50 +02007376 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00007377 int r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007378
Olivier Deprez157378f2022-04-04 15:47:50 +02007379 r = kvm_x86_ops.skip_emulated_instruction(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00007380 if (unlikely(!r))
7381 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007382
7383 /*
7384 * rflags is the old, "raw" value of the flags. The new value has
7385 * not been saved yet.
7386 *
7387 * This is correct even for TF set by the guest, because "the
7388 * processor will not generate this exception after the instruction
7389 * that sets the TF flag".
7390 */
7391 if (unlikely(rflags & X86_EFLAGS_TF))
David Brazdil0f672f62019-12-10 10:32:29 +00007392 r = kvm_vcpu_do_singlestep(vcpu);
7393 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007394}
7395EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
7396
Olivier Deprez92d4c212022-12-06 15:05:30 +01007397static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu, int *r)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007398{
7399 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
7400 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
7401 struct kvm_run *kvm_run = vcpu->run;
7402 unsigned long eip = kvm_get_linear_rip(vcpu);
7403 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7404 vcpu->arch.guest_debug_dr7,
7405 vcpu->arch.eff_db);
7406
7407 if (dr6 != 0) {
7408 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
7409 kvm_run->debug.arch.pc = eip;
7410 kvm_run->debug.arch.exception = DB_VECTOR;
7411 kvm_run->exit_reason = KVM_EXIT_DEBUG;
David Brazdil0f672f62019-12-10 10:32:29 +00007412 *r = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007413 return true;
7414 }
7415 }
7416
7417 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
7418 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
7419 unsigned long eip = kvm_get_linear_rip(vcpu);
7420 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
7421 vcpu->arch.dr7,
7422 vcpu->arch.db);
7423
7424 if (dr6 != 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007425 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
David Brazdil0f672f62019-12-10 10:32:29 +00007426 *r = 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007427 return true;
7428 }
7429 }
7430
7431 return false;
7432}
7433
7434static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
7435{
7436 switch (ctxt->opcode_len) {
7437 case 1:
7438 switch (ctxt->b) {
7439 case 0xe4: /* IN */
7440 case 0xe5:
7441 case 0xec:
7442 case 0xed:
7443 case 0xe6: /* OUT */
7444 case 0xe7:
7445 case 0xee:
7446 case 0xef:
7447 case 0x6c: /* INS */
7448 case 0x6d:
7449 case 0x6e: /* OUTS */
7450 case 0x6f:
7451 return true;
7452 }
7453 break;
7454 case 2:
7455 switch (ctxt->b) {
7456 case 0x33: /* RDPMC */
7457 return true;
7458 }
7459 break;
7460 }
7461
7462 return false;
7463}
7464
Olivier Deprez157378f2022-04-04 15:47:50 +02007465/*
Olivier Deprez92d4c212022-12-06 15:05:30 +01007466 * Decode an instruction for emulation. The caller is responsible for handling
7467 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
7468 * (and wrong) when emulating on an intercepted fault-like exception[*], as
7469 * code breakpoints have higher priority and thus have already been done by
7470 * hardware.
7471 *
7472 * [*] Except #MC, which is higher priority, but KVM should never emulate in
7473 * response to a machine check.
Olivier Deprez157378f2022-04-04 15:47:50 +02007474 */
7475int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
7476 void *insn, int insn_len)
7477{
Olivier Deprez157378f2022-04-04 15:47:50 +02007478 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Olivier Deprez92d4c212022-12-06 15:05:30 +01007479 int r;
Olivier Deprez157378f2022-04-04 15:47:50 +02007480
7481 init_emulate_ctxt(vcpu);
7482
Olivier Deprez157378f2022-04-04 15:47:50 +02007483 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
7484
7485 r = x86_decode_insn(ctxt, insn, insn_len);
7486
7487 trace_kvm_emulate_insn_start(vcpu);
7488 ++vcpu->stat.insn_emulation;
7489
7490 return r;
7491}
7492EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
7493
Olivier Deprez0e641232021-09-23 10:07:05 +02007494int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
7495 int emulation_type, void *insn, int insn_len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007496{
7497 int r;
Olivier Deprez157378f2022-04-04 15:47:50 +02007498 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007499 bool writeback = true;
Olivier Deprez157378f2022-04-04 15:47:50 +02007500 bool write_fault_to_spt;
7501
7502 if (unlikely(!kvm_x86_ops.can_emulate_instruction(vcpu, insn, insn_len)))
7503 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007504
7505 vcpu->arch.l1tf_flush_l1d = true;
7506
7507 /*
7508 * Clear write_fault_to_shadow_pgtable here to ensure it is
7509 * never reused.
7510 */
Olivier Deprez157378f2022-04-04 15:47:50 +02007511 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007512 vcpu->arch.write_fault_to_shadow_pgtable = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007513
7514 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007515 kvm_clear_exception_queue(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007516
Olivier Deprez92d4c212022-12-06 15:05:30 +01007517 /*
7518 * Return immediately if RIP hits a code breakpoint, such #DBs
7519 * are fault-like and are higher priority than any faults on
7520 * the code fetch itself.
7521 */
7522 if (!(emulation_type & EMULTYPE_SKIP) &&
7523 kvm_vcpu_check_code_breakpoint(vcpu, &r))
7524 return r;
7525
Olivier Deprez157378f2022-04-04 15:47:50 +02007526 r = x86_decode_emulated_instruction(vcpu, emulation_type,
7527 insn, insn_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007528 if (r != EMULATION_OK) {
David Brazdil0f672f62019-12-10 10:32:29 +00007529 if ((emulation_type & EMULTYPE_TRAP_UD) ||
7530 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
7531 kvm_queue_exception(vcpu, UD_VECTOR);
7532 return 1;
7533 }
Olivier Deprez0e641232021-09-23 10:07:05 +02007534 if (reexecute_instruction(vcpu, cr2_or_gpa,
7535 write_fault_to_spt,
7536 emulation_type))
David Brazdil0f672f62019-12-10 10:32:29 +00007537 return 1;
7538 if (ctxt->have_exception) {
7539 /*
7540 * #UD should result in just EMULATION_FAILED, and trap-like
7541 * exception should not be encountered during decode.
7542 */
7543 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
7544 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
7545 inject_emulated_exception(vcpu);
7546 return 1;
7547 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007548 return handle_emulation_failure(vcpu, emulation_type);
7549 }
7550 }
7551
David Brazdil0f672f62019-12-10 10:32:29 +00007552 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
7553 !is_vmware_backdoor_opcode(ctxt)) {
7554 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7555 return 1;
7556 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007557
David Brazdil0f672f62019-12-10 10:32:29 +00007558 /*
7559 * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
7560 * for kvm_skip_emulated_instruction(). The caller is responsible for
7561 * updating interruptibility state and injecting single-step #DBs.
7562 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007563 if (emulation_type & EMULTYPE_SKIP) {
7564 kvm_rip_write(vcpu, ctxt->_eip);
7565 if (ctxt->eflags & X86_EFLAGS_RF)
7566 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
David Brazdil0f672f62019-12-10 10:32:29 +00007567 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007568 }
7569
Olivier Deprez0e641232021-09-23 10:07:05 +02007570 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
David Brazdil0f672f62019-12-10 10:32:29 +00007571 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007572
7573 /* this is needed for vmware backdoor interface to work since it
7574 changes registers values during IO operation */
7575 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
7576 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
7577 emulator_invalidate_register_cache(ctxt);
7578 }
7579
7580restart:
Olivier Deprez157378f2022-04-04 15:47:50 +02007581 if (emulation_type & EMULTYPE_PF) {
7582 /* Save the faulting GPA (cr2) in the address field */
7583 ctxt->exception.address = cr2_or_gpa;
7584
7585 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7586 if (vcpu->arch.mmu->direct_map) {
7587 ctxt->gpa_available = true;
7588 ctxt->gpa_val = cr2_or_gpa;
7589 }
7590 } else {
7591 /* Sanitize the address out of an abundance of paranoia. */
7592 ctxt->exception.address = 0;
7593 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007594
7595 r = x86_emulate_insn(ctxt);
7596
7597 if (r == EMULATION_INTERCEPTED)
David Brazdil0f672f62019-12-10 10:32:29 +00007598 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007599
7600 if (r == EMULATION_FAILED) {
Olivier Deprez0e641232021-09-23 10:07:05 +02007601 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007602 emulation_type))
David Brazdil0f672f62019-12-10 10:32:29 +00007603 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007604
7605 return handle_emulation_failure(vcpu, emulation_type);
7606 }
7607
7608 if (ctxt->have_exception) {
David Brazdil0f672f62019-12-10 10:32:29 +00007609 r = 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007610 if (inject_emulated_exception(vcpu))
7611 return r;
7612 } else if (vcpu->arch.pio.count) {
7613 if (!vcpu->arch.pio.in) {
7614 /* FIXME: return into emulator if single-stepping. */
7615 vcpu->arch.pio.count = 0;
7616 } else {
7617 writeback = false;
7618 vcpu->arch.complete_userspace_io = complete_emulated_pio;
7619 }
David Brazdil0f672f62019-12-10 10:32:29 +00007620 r = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007621 } else if (vcpu->mmio_needed) {
David Brazdil0f672f62019-12-10 10:32:29 +00007622 ++vcpu->stat.mmio_exits;
7623
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007624 if (!vcpu->mmio_is_write)
7625 writeback = false;
David Brazdil0f672f62019-12-10 10:32:29 +00007626 r = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007627 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7628 } else if (r == EMULATION_RESTART)
7629 goto restart;
7630 else
David Brazdil0f672f62019-12-10 10:32:29 +00007631 r = 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007632
7633 if (writeback) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007634 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007635 toggle_interruptibility(vcpu, ctxt->interruptibility);
7636 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
Olivier Deprez92d4c212022-12-06 15:05:30 +01007637
7638 /*
7639 * Note, EXCPT_DB is assumed to be fault-like as the emulator
7640 * only supports code breakpoints and general detect #DB, both
7641 * of which are fault-like.
7642 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007643 if (!ctxt->have_exception ||
David Brazdil0f672f62019-12-10 10:32:29 +00007644 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7645 kvm_rip_write(vcpu, ctxt->eip);
Olivier Deprez0e641232021-09-23 10:07:05 +02007646 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
David Brazdil0f672f62019-12-10 10:32:29 +00007647 r = kvm_vcpu_do_singlestep(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02007648 if (kvm_x86_ops.update_emulated_instruction)
7649 kvm_x86_ops.update_emulated_instruction(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007650 __kvm_set_rflags(vcpu, ctxt->eflags);
David Brazdil0f672f62019-12-10 10:32:29 +00007651 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007652
7653 /*
7654 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7655 * do nothing, and it will be requested again as soon as
7656 * the shadow expires. But we still need to check here,
7657 * because POPF has no interrupt shadow.
7658 */
7659 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7660 kvm_make_request(KVM_REQ_EVENT, vcpu);
7661 } else
7662 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7663
7664 return r;
7665}
7666
7667int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7668{
7669 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7670}
7671EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7672
7673int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7674 void *insn, int insn_len)
7675{
7676 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7677}
7678EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7679
David Brazdil0f672f62019-12-10 10:32:29 +00007680static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7681{
7682 vcpu->arch.pio.count = 0;
7683 return 1;
7684}
7685
7686static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7687{
7688 vcpu->arch.pio.count = 0;
7689
7690 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7691 return 1;
7692
7693 return kvm_skip_emulated_instruction(vcpu);
7694}
7695
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007696static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7697 unsigned short port)
7698{
David Brazdil0f672f62019-12-10 10:32:29 +00007699 unsigned long val = kvm_rax_read(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02007700 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7701
David Brazdil0f672f62019-12-10 10:32:29 +00007702 if (ret)
7703 return ret;
7704
7705 /*
7706 * Workaround userspace that relies on old KVM behavior of %rip being
7707 * incremented prior to exiting to userspace to handle "OUT 0x7e".
7708 */
7709 if (port == 0x7e &&
7710 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7711 vcpu->arch.complete_userspace_io =
7712 complete_fast_pio_out_port_0x7e;
7713 kvm_skip_emulated_instruction(vcpu);
7714 } else {
7715 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7716 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7717 }
7718 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007719}
7720
7721static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7722{
7723 unsigned long val;
7724
7725 /* We should only ever be called with arch.pio.count equal to 1 */
7726 BUG_ON(vcpu->arch.pio.count != 1);
7727
David Brazdil0f672f62019-12-10 10:32:29 +00007728 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7729 vcpu->arch.pio.count = 0;
7730 return 1;
7731 }
7732
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007733 /* For size less than 4 we merge, else we zero extend */
David Brazdil0f672f62019-12-10 10:32:29 +00007734 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007735
7736 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02007737 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007738 * the copy and tracing
7739 */
Olivier Deprez157378f2022-04-04 15:47:50 +02007740 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
David Brazdil0f672f62019-12-10 10:32:29 +00007741 kvm_rax_write(vcpu, val);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007742
David Brazdil0f672f62019-12-10 10:32:29 +00007743 return kvm_skip_emulated_instruction(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007744}
7745
7746static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7747 unsigned short port)
7748{
7749 unsigned long val;
7750 int ret;
7751
7752 /* For size less than 4 we merge, else we zero extend */
David Brazdil0f672f62019-12-10 10:32:29 +00007753 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007754
Olivier Deprez157378f2022-04-04 15:47:50 +02007755 ret = emulator_pio_in(vcpu, size, port, &val, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007756 if (ret) {
David Brazdil0f672f62019-12-10 10:32:29 +00007757 kvm_rax_write(vcpu, val);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007758 return ret;
7759 }
7760
David Brazdil0f672f62019-12-10 10:32:29 +00007761 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007762 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7763
7764 return 0;
7765}
7766
7767int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7768{
David Brazdil0f672f62019-12-10 10:32:29 +00007769 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007770
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007771 if (in)
David Brazdil0f672f62019-12-10 10:32:29 +00007772 ret = kvm_fast_pio_in(vcpu, size, port);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007773 else
David Brazdil0f672f62019-12-10 10:32:29 +00007774 ret = kvm_fast_pio_out(vcpu, size, port);
7775 return ret && kvm_skip_emulated_instruction(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007776}
7777EXPORT_SYMBOL_GPL(kvm_fast_pio);
7778
7779static int kvmclock_cpu_down_prep(unsigned int cpu)
7780{
7781 __this_cpu_write(cpu_tsc_khz, 0);
7782 return 0;
7783}
7784
7785static void tsc_khz_changed(void *data)
7786{
7787 struct cpufreq_freqs *freq = data;
7788 unsigned long khz = 0;
7789
7790 if (data)
7791 khz = freq->new;
7792 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7793 khz = cpufreq_quick_get(raw_smp_processor_id());
7794 if (!khz)
7795 khz = tsc_khz;
7796 __this_cpu_write(cpu_tsc_khz, khz);
7797}
7798
7799#ifdef CONFIG_X86_64
7800static void kvm_hyperv_tsc_notifier(void)
7801{
7802 struct kvm *kvm;
7803 struct kvm_vcpu *vcpu;
7804 int cpu;
7805
David Brazdil0f672f62019-12-10 10:32:29 +00007806 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007807 list_for_each_entry(kvm, &vm_list, vm_list)
7808 kvm_make_mclock_inprogress_request(kvm);
7809
7810 hyperv_stop_tsc_emulation();
7811
7812 /* TSC frequency always matches when on Hyper-V */
7813 for_each_present_cpu(cpu)
7814 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7815 kvm_max_guest_tsc_khz = tsc_khz;
7816
7817 list_for_each_entry(kvm, &vm_list, vm_list) {
7818 struct kvm_arch *ka = &kvm->arch;
7819
7820 spin_lock(&ka->pvclock_gtod_sync_lock);
7821
7822 pvclock_update_vm_gtod_copy(kvm);
7823
7824 kvm_for_each_vcpu(cpu, vcpu, kvm)
7825 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7826
7827 kvm_for_each_vcpu(cpu, vcpu, kvm)
7828 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7829
7830 spin_unlock(&ka->pvclock_gtod_sync_lock);
7831 }
David Brazdil0f672f62019-12-10 10:32:29 +00007832 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007833}
7834#endif
7835
David Brazdil0f672f62019-12-10 10:32:29 +00007836static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007837{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007838 struct kvm *kvm;
7839 struct kvm_vcpu *vcpu;
7840 int i, send_ipi = 0;
7841
7842 /*
7843 * We allow guests to temporarily run on slowing clocks,
7844 * provided we notify them after, or to run on accelerating
7845 * clocks, provided we notify them before. Thus time never
7846 * goes backwards.
7847 *
7848 * However, we have a problem. We can't atomically update
7849 * the frequency of a given CPU from this function; it is
7850 * merely a notifier, which can be called from any CPU.
7851 * Changing the TSC frequency at arbitrary points in time
7852 * requires a recomputation of local variables related to
7853 * the TSC for each VCPU. We must flag these local variables
7854 * to be updated and be sure the update takes place with the
7855 * new frequency before any guests proceed.
7856 *
7857 * Unfortunately, the combination of hotplug CPU and frequency
7858 * change creates an intractable locking scenario; the order
7859 * of when these callouts happen is undefined with respect to
7860 * CPU hotplug, and they can race with each other. As such,
7861 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7862 * undefined; you can actually have a CPU frequency change take
7863 * place in between the computation of X and the setting of the
7864 * variable. To protect against this problem, all updates of
7865 * the per_cpu tsc_khz variable are done in an interrupt
7866 * protected IPI, and all callers wishing to update the value
7867 * must wait for a synchronous IPI to complete (which is trivial
7868 * if the caller is on the CPU already). This establishes the
7869 * necessary total order on variable updates.
7870 *
7871 * Note that because a guest time update may take place
7872 * anytime after the setting of the VCPU's request bit, the
7873 * correct TSC value must be set before the request. However,
7874 * to ensure the update actually makes it to any guest which
7875 * starts running in hardware virtualization between the set
7876 * and the acquisition of the spinlock, we must also ping the
7877 * CPU after setting the request bit.
7878 *
7879 */
7880
David Brazdil0f672f62019-12-10 10:32:29 +00007881 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007882
David Brazdil0f672f62019-12-10 10:32:29 +00007883 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007884 list_for_each_entry(kvm, &vm_list, vm_list) {
7885 kvm_for_each_vcpu(i, vcpu, kvm) {
David Brazdil0f672f62019-12-10 10:32:29 +00007886 if (vcpu->cpu != cpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007887 continue;
7888 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00007889 if (vcpu->cpu != raw_smp_processor_id())
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007890 send_ipi = 1;
7891 }
7892 }
David Brazdil0f672f62019-12-10 10:32:29 +00007893 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007894
7895 if (freq->old < freq->new && send_ipi) {
7896 /*
7897 * We upscale the frequency. Must make the guest
7898 * doesn't see old kvmclock values while running with
7899 * the new frequency, otherwise we risk the guest sees
7900 * time go backwards.
7901 *
7902 * In case we update the frequency for another cpu
7903 * (which might be in guest context) send an interrupt
7904 * to kick the cpu out of guest context. Next time
7905 * guest context is entered kvmclock will be updated,
7906 * so the guest will not see stale values.
7907 */
David Brazdil0f672f62019-12-10 10:32:29 +00007908 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007909 }
David Brazdil0f672f62019-12-10 10:32:29 +00007910}
7911
7912static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7913 void *data)
7914{
7915 struct cpufreq_freqs *freq = data;
7916 int cpu;
7917
7918 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7919 return 0;
7920 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7921 return 0;
7922
7923 for_each_cpu(cpu, freq->policy->cpus)
7924 __kvmclock_cpufreq_notifier(freq, cpu);
7925
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007926 return 0;
7927}
7928
7929static struct notifier_block kvmclock_cpufreq_notifier_block = {
7930 .notifier_call = kvmclock_cpufreq_notifier
7931};
7932
7933static int kvmclock_cpu_online(unsigned int cpu)
7934{
7935 tsc_khz_changed(NULL);
7936 return 0;
7937}
7938
7939static void kvm_timer_init(void)
7940{
7941 max_tsc_khz = tsc_khz;
7942
7943 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7944#ifdef CONFIG_CPU_FREQ
Olivier Deprez157378f2022-04-04 15:47:50 +02007945 struct cpufreq_policy *policy;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007946 int cpu;
7947
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007948 cpu = get_cpu();
Olivier Deprez157378f2022-04-04 15:47:50 +02007949 policy = cpufreq_cpu_get(cpu);
7950 if (policy) {
7951 if (policy->cpuinfo.max_freq)
7952 max_tsc_khz = policy->cpuinfo.max_freq;
7953 cpufreq_cpu_put(policy);
7954 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007955 put_cpu();
7956#endif
7957 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7958 CPUFREQ_TRANSITION_NOTIFIER);
7959 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007960
7961 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7962 kvmclock_cpu_online, kvmclock_cpu_down_prep);
7963}
7964
7965DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7966EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7967
7968int kvm_is_in_guest(void)
7969{
7970 return __this_cpu_read(current_vcpu) != NULL;
7971}
7972
7973static int kvm_is_user_mode(void)
7974{
7975 int user_mode = 3;
7976
7977 if (__this_cpu_read(current_vcpu))
Olivier Deprez157378f2022-04-04 15:47:50 +02007978 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007979
7980 return user_mode != 0;
7981}
7982
7983static unsigned long kvm_get_guest_ip(void)
7984{
7985 unsigned long ip = 0;
7986
7987 if (__this_cpu_read(current_vcpu))
7988 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7989
7990 return ip;
7991}
7992
David Brazdil0f672f62019-12-10 10:32:29 +00007993static void kvm_handle_intel_pt_intr(void)
7994{
7995 struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7996
7997 kvm_make_request(KVM_REQ_PMI, vcpu);
7998 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7999 (unsigned long *)&vcpu->arch.pmu.global_status);
8000}
8001
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008002static struct perf_guest_info_callbacks kvm_guest_cbs = {
8003 .is_in_guest = kvm_is_in_guest,
8004 .is_user_mode = kvm_is_user_mode,
8005 .get_guest_ip = kvm_get_guest_ip,
Olivier Deprez157378f2022-04-04 15:47:50 +02008006 .handle_intel_pt_intr = NULL,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008007};
8008
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008009#ifdef CONFIG_X86_64
8010static void pvclock_gtod_update_fn(struct work_struct *work)
8011{
8012 struct kvm *kvm;
8013
8014 struct kvm_vcpu *vcpu;
8015 int i;
8016
David Brazdil0f672f62019-12-10 10:32:29 +00008017 mutex_lock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008018 list_for_each_entry(kvm, &vm_list, vm_list)
8019 kvm_for_each_vcpu(i, vcpu, kvm)
8020 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
8021 atomic_set(&kvm_guest_has_master_clock, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00008022 mutex_unlock(&kvm_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008023}
8024
8025static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
8026
8027/*
Olivier Deprez157378f2022-04-04 15:47:50 +02008028 * Indirection to move queue_work() out of the tk_core.seq write held
8029 * region to prevent possible deadlocks against time accessors which
8030 * are invoked with work related locks held.
8031 */
8032static void pvclock_irq_work_fn(struct irq_work *w)
8033{
8034 queue_work(system_long_wq, &pvclock_gtod_work);
8035}
8036
8037static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
8038
8039/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008040 * Notification about pvclock gtod data update.
8041 */
8042static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
8043 void *priv)
8044{
8045 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
8046 struct timekeeper *tk = priv;
8047
8048 update_pvclock_gtod(tk);
8049
Olivier Deprez157378f2022-04-04 15:47:50 +02008050 /*
8051 * Disable master clock if host does not trust, or does not use,
8052 * TSC based clocksource. Delegate queue_work() to irq_work as
8053 * this is invoked with tk_core.seq write held.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008054 */
8055 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
8056 atomic_read(&kvm_guest_has_master_clock) != 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02008057 irq_work_queue(&pvclock_irq_work);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008058 return 0;
8059}
8060
8061static struct notifier_block pvclock_gtod_notifier = {
8062 .notifier_call = pvclock_gtod_notify,
8063};
8064#endif
8065
8066int kvm_arch_init(void *opaque)
8067{
Olivier Deprez157378f2022-04-04 15:47:50 +02008068 struct kvm_x86_init_ops *ops = opaque;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008069 int r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008070
Olivier Deprez157378f2022-04-04 15:47:50 +02008071 if (kvm_x86_ops.hardware_enable) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008072 printk(KERN_ERR "kvm: already loaded the other module\n");
8073 r = -EEXIST;
8074 goto out;
8075 }
8076
8077 if (!ops->cpu_has_kvm_support()) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008078 pr_err_ratelimited("kvm: no hardware support\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008079 r = -EOPNOTSUPP;
8080 goto out;
8081 }
8082 if (ops->disabled_by_bios()) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008083 pr_err_ratelimited("kvm: disabled by bios\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008084 r = -EOPNOTSUPP;
8085 goto out;
8086 }
8087
David Brazdil0f672f62019-12-10 10:32:29 +00008088 /*
8089 * KVM explicitly assumes that the guest has an FPU and
8090 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
8091 * vCPU's FPU state as a fxregs_state struct.
8092 */
8093 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
8094 printk(KERN_ERR "kvm: inadequate fpu\n");
8095 r = -EOPNOTSUPP;
8096 goto out;
8097 }
8098
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008099 r = -ENOMEM;
David Brazdil0f672f62019-12-10 10:32:29 +00008100 x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
8101 __alignof__(struct fpu), SLAB_ACCOUNT,
8102 NULL);
8103 if (!x86_fpu_cache) {
8104 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
8105 goto out;
8106 }
8107
Olivier Deprez157378f2022-04-04 15:47:50 +02008108 x86_emulator_cache = kvm_alloc_emulator_cache();
8109 if (!x86_emulator_cache) {
8110 pr_err("kvm: failed to allocate cache for x86 emulator\n");
David Brazdil0f672f62019-12-10 10:32:29 +00008111 goto out_free_x86_fpu_cache;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008112 }
8113
Olivier Deprez157378f2022-04-04 15:47:50 +02008114 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
8115 if (!user_return_msrs) {
8116 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
8117 goto out_free_x86_emulator_cache;
8118 }
8119
Olivier Deprez92d4c212022-12-06 15:05:30 +01008120 r = kvm_mmu_vendor_module_init();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008121 if (r)
8122 goto out_free_percpu;
8123
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008124 kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
8125 PT_DIRTY_MASK, PT64_NX_MASK, 0,
8126 PT_PRESENT_MASK, 0, sme_me_mask);
8127 kvm_timer_init();
8128
Olivier Deprez157378f2022-04-04 15:47:50 +02008129 if (ops->intel_pt_intr_in_guest && ops->intel_pt_intr_in_guest())
8130 kvm_guest_cbs.handle_intel_pt_intr = kvm_handle_intel_pt_intr;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008131 perf_register_guest_info_callbacks(&kvm_guest_cbs);
8132
Olivier Deprez157378f2022-04-04 15:47:50 +02008133 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008134 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
Olivier Deprez157378f2022-04-04 15:47:50 +02008135 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
8136 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008137
8138 kvm_lapic_init();
David Brazdil0f672f62019-12-10 10:32:29 +00008139 if (pi_inject_timer == -1)
8140 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008141#ifdef CONFIG_X86_64
8142 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
8143
8144 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8145 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
8146#endif
8147
8148 return 0;
8149
8150out_free_percpu:
Olivier Deprez157378f2022-04-04 15:47:50 +02008151 free_percpu(user_return_msrs);
8152out_free_x86_emulator_cache:
8153 kmem_cache_destroy(x86_emulator_cache);
David Brazdil0f672f62019-12-10 10:32:29 +00008154out_free_x86_fpu_cache:
8155 kmem_cache_destroy(x86_fpu_cache);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008156out:
8157 return r;
8158}
8159
8160void kvm_arch_exit(void)
8161{
8162#ifdef CONFIG_X86_64
8163 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
8164 clear_hv_tscchange_cb();
8165#endif
8166 kvm_lapic_exit();
8167 perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
Olivier Deprez157378f2022-04-04 15:47:50 +02008168 kvm_guest_cbs.handle_intel_pt_intr = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008169
8170 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8171 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
8172 CPUFREQ_TRANSITION_NOTIFIER);
8173 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
8174#ifdef CONFIG_X86_64
8175 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
Olivier Deprez157378f2022-04-04 15:47:50 +02008176 irq_work_sync(&pvclock_irq_work);
Olivier Deprez0e641232021-09-23 10:07:05 +02008177 cancel_work_sync(&pvclock_gtod_work);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008178#endif
Olivier Deprez157378f2022-04-04 15:47:50 +02008179 kvm_x86_ops.hardware_enable = NULL;
Olivier Deprez92d4c212022-12-06 15:05:30 +01008180 kvm_mmu_vendor_module_exit();
Olivier Deprez157378f2022-04-04 15:47:50 +02008181 free_percpu(user_return_msrs);
8182 kmem_cache_destroy(x86_emulator_cache);
David Brazdil0f672f62019-12-10 10:32:29 +00008183 kmem_cache_destroy(x86_fpu_cache);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008184}
8185
8186int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
8187{
8188 ++vcpu->stat.halt_exits;
8189 if (lapic_in_kernel(vcpu)) {
8190 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
8191 return 1;
8192 } else {
8193 vcpu->run->exit_reason = KVM_EXIT_HLT;
8194 return 0;
8195 }
8196}
8197EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
8198
8199int kvm_emulate_halt(struct kvm_vcpu *vcpu)
8200{
8201 int ret = kvm_skip_emulated_instruction(vcpu);
8202 /*
8203 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
8204 * KVM_EXIT_DEBUG here.
8205 */
8206 return kvm_vcpu_halt(vcpu) && ret;
8207}
8208EXPORT_SYMBOL_GPL(kvm_emulate_halt);
8209
8210#ifdef CONFIG_X86_64
8211static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
8212 unsigned long clock_type)
8213{
8214 struct kvm_clock_pairing clock_pairing;
8215 struct timespec64 ts;
8216 u64 cycle;
8217 int ret;
8218
8219 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
8220 return -KVM_EOPNOTSUPP;
8221
8222 if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
8223 return -KVM_EOPNOTSUPP;
8224
8225 clock_pairing.sec = ts.tv_sec;
8226 clock_pairing.nsec = ts.tv_nsec;
8227 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
8228 clock_pairing.flags = 0;
8229 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
8230
8231 ret = 0;
8232 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
8233 sizeof(struct kvm_clock_pairing)))
8234 ret = -KVM_EFAULT;
8235
8236 return ret;
8237}
8238#endif
8239
8240/*
8241 * kvm_pv_kick_cpu_op: Kick a vcpu.
8242 *
8243 * @apicid - apicid of vcpu to be kicked.
8244 */
8245static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
8246{
Olivier Deprez92d4c212022-12-06 15:05:30 +01008247 /*
8248 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
8249 * common code, e.g. for tracing. Defer initialization to the compiler.
8250 */
8251 struct kvm_lapic_irq lapic_irq = {
8252 .delivery_mode = APIC_DM_REMRD,
8253 .dest_mode = APIC_DEST_PHYSICAL,
8254 .shorthand = APIC_DEST_NOSHORT,
8255 .dest_id = apicid,
8256 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008257
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008258 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
8259}
8260
Olivier Deprez157378f2022-04-04 15:47:50 +02008261bool kvm_apicv_activated(struct kvm *kvm)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008262{
Olivier Deprez157378f2022-04-04 15:47:50 +02008263 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008264}
Olivier Deprez157378f2022-04-04 15:47:50 +02008265EXPORT_SYMBOL_GPL(kvm_apicv_activated);
8266
8267void kvm_apicv_init(struct kvm *kvm, bool enable)
8268{
8269 if (enable)
8270 clear_bit(APICV_INHIBIT_REASON_DISABLE,
8271 &kvm->arch.apicv_inhibit_reasons);
8272 else
8273 set_bit(APICV_INHIBIT_REASON_DISABLE,
8274 &kvm->arch.apicv_inhibit_reasons);
8275}
8276EXPORT_SYMBOL_GPL(kvm_apicv_init);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008277
David Brazdil0f672f62019-12-10 10:32:29 +00008278static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
8279{
8280 struct kvm_vcpu *target = NULL;
8281 struct kvm_apic_map *map;
8282
8283 rcu_read_lock();
8284 map = rcu_dereference(kvm->arch.apic_map);
8285
8286 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
8287 target = map->phys_map[dest_id]->vcpu;
8288
8289 rcu_read_unlock();
8290
8291 if (target && READ_ONCE(target->ready))
8292 kvm_vcpu_yield_to(target);
8293}
8294
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008295int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
8296{
8297 unsigned long nr, a0, a1, a2, a3, ret;
8298 int op_64_bit;
8299
8300 if (kvm_hv_hypercall_enabled(vcpu->kvm))
8301 return kvm_hv_hypercall(vcpu);
8302
David Brazdil0f672f62019-12-10 10:32:29 +00008303 nr = kvm_rax_read(vcpu);
8304 a0 = kvm_rbx_read(vcpu);
8305 a1 = kvm_rcx_read(vcpu);
8306 a2 = kvm_rdx_read(vcpu);
8307 a3 = kvm_rsi_read(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008308
8309 trace_kvm_hypercall(nr, a0, a1, a2, a3);
8310
8311 op_64_bit = is_64_bit_mode(vcpu);
8312 if (!op_64_bit) {
8313 nr &= 0xFFFFFFFF;
8314 a0 &= 0xFFFFFFFF;
8315 a1 &= 0xFFFFFFFF;
8316 a2 &= 0xFFFFFFFF;
8317 a3 &= 0xFFFFFFFF;
8318 }
8319
Olivier Deprez157378f2022-04-04 15:47:50 +02008320 if (kvm_x86_ops.get_cpl(vcpu) != 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008321 ret = -KVM_EPERM;
8322 goto out;
8323 }
8324
Olivier Deprez157378f2022-04-04 15:47:50 +02008325 ret = -KVM_ENOSYS;
8326
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008327 switch (nr) {
8328 case KVM_HC_VAPIC_POLL_IRQ:
8329 ret = 0;
8330 break;
8331 case KVM_HC_KICK_CPU:
Olivier Deprez157378f2022-04-04 15:47:50 +02008332 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
8333 break;
8334
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008335 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
David Brazdil0f672f62019-12-10 10:32:29 +00008336 kvm_sched_yield(vcpu->kvm, a1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008337 ret = 0;
8338 break;
8339#ifdef CONFIG_X86_64
8340 case KVM_HC_CLOCK_PAIRING:
8341 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
8342 break;
David Brazdil0f672f62019-12-10 10:32:29 +00008343#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008344 case KVM_HC_SEND_IPI:
Olivier Deprez157378f2022-04-04 15:47:50 +02008345 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
8346 break;
8347
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008348 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
8349 break;
David Brazdil0f672f62019-12-10 10:32:29 +00008350 case KVM_HC_SCHED_YIELD:
Olivier Deprez157378f2022-04-04 15:47:50 +02008351 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
8352 break;
8353
David Brazdil0f672f62019-12-10 10:32:29 +00008354 kvm_sched_yield(vcpu->kvm, a0);
8355 ret = 0;
8356 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008357 default:
8358 ret = -KVM_ENOSYS;
8359 break;
8360 }
8361out:
8362 if (!op_64_bit)
8363 ret = (u32)ret;
David Brazdil0f672f62019-12-10 10:32:29 +00008364 kvm_rax_write(vcpu, ret);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008365
8366 ++vcpu->stat.hypercalls;
8367 return kvm_skip_emulated_instruction(vcpu);
8368}
8369EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
8370
8371static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8372{
8373 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8374 char instruction[3];
8375 unsigned long rip = kvm_rip_read(vcpu);
8376
Olivier Deprez157378f2022-04-04 15:47:50 +02008377 kvm_x86_ops.patch_hypercall(vcpu, instruction);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008378
8379 return emulator_write_emulated(ctxt, rip, instruction, 3,
8380 &ctxt->exception);
8381}
8382
8383static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
8384{
8385 return vcpu->run->request_interrupt_window &&
8386 likely(!pic_in_kernel(vcpu->kvm));
8387}
8388
8389static void post_kvm_run_save(struct kvm_vcpu *vcpu)
8390{
8391 struct kvm_run *kvm_run = vcpu->run;
8392
8393 kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
8394 kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
8395 kvm_run->cr8 = kvm_get_cr8(vcpu);
8396 kvm_run->apic_base = kvm_get_apic_base(vcpu);
8397 kvm_run->ready_for_interrupt_injection =
8398 pic_in_kernel(vcpu->kvm) ||
8399 kvm_vcpu_ready_for_interrupt_injection(vcpu);
8400}
8401
8402static void update_cr8_intercept(struct kvm_vcpu *vcpu)
8403{
8404 int max_irr, tpr;
8405
Olivier Deprez157378f2022-04-04 15:47:50 +02008406 if (!kvm_x86_ops.update_cr8_intercept)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008407 return;
8408
8409 if (!lapic_in_kernel(vcpu))
8410 return;
8411
8412 if (vcpu->arch.apicv_active)
8413 return;
8414
8415 if (!vcpu->arch.apic->vapic_addr)
8416 max_irr = kvm_lapic_find_highest_irr(vcpu);
8417 else
8418 max_irr = -1;
8419
8420 if (max_irr != -1)
8421 max_irr >>= 4;
8422
8423 tpr = kvm_lapic_get_cr8(vcpu);
8424
Olivier Deprez157378f2022-04-04 15:47:50 +02008425 kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008426}
8427
Olivier Deprez0e641232021-09-23 10:07:05 +02008428static void kvm_inject_exception(struct kvm_vcpu *vcpu)
8429{
Olivier Deprez92d4c212022-12-06 15:05:30 +01008430 trace_kvm_inj_exception(vcpu->arch.exception.nr,
8431 vcpu->arch.exception.has_error_code,
8432 vcpu->arch.exception.error_code,
8433 vcpu->arch.exception.injected);
8434
Olivier Deprez157378f2022-04-04 15:47:50 +02008435 if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
8436 vcpu->arch.exception.error_code = false;
8437 kvm_x86_ops.queue_exception(vcpu);
Olivier Deprez0e641232021-09-23 10:07:05 +02008438}
8439
Olivier Deprez157378f2022-04-04 15:47:50 +02008440static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008441{
8442 int r;
Olivier Deprez157378f2022-04-04 15:47:50 +02008443 bool can_inject = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008444
8445 /* try to reinject previous events if any */
8446
Olivier Deprez157378f2022-04-04 15:47:50 +02008447 if (vcpu->arch.exception.injected) {
Olivier Deprez0e641232021-09-23 10:07:05 +02008448 kvm_inject_exception(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02008449 can_inject = false;
8450 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008451 /*
8452 * Do not inject an NMI or interrupt if there is a pending
8453 * exception. Exceptions and interrupts are recognized at
8454 * instruction boundaries, i.e. the start of an instruction.
8455 * Trap-like exceptions, e.g. #DB, have higher priority than
8456 * NMIs and interrupts, i.e. traps are recognized before an
8457 * NMI/interrupt that's pending on the same instruction.
8458 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
8459 * priority, but are only generated (pended) during instruction
8460 * execution, i.e. a pending fault-like exception means the
8461 * fault occurred on the *previous* instruction and must be
8462 * serviced prior to recognizing any new events in order to
8463 * fully complete the previous instruction.
8464 */
8465 else if (!vcpu->arch.exception.pending) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008466 if (vcpu->arch.nmi_injected) {
8467 kvm_x86_ops.set_nmi(vcpu);
8468 can_inject = false;
8469 } else if (vcpu->arch.interrupt.injected) {
8470 kvm_x86_ops.set_irq(vcpu);
8471 can_inject = false;
8472 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008473 }
8474
Olivier Deprez157378f2022-04-04 15:47:50 +02008475 WARN_ON_ONCE(vcpu->arch.exception.injected &&
8476 vcpu->arch.exception.pending);
8477
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008478 /*
8479 * Call check_nested_events() even if we reinjected a previous event
8480 * in order for caller to determine if it should require immediate-exit
8481 * from L2 to L1 due to pending L1 events which require exit
8482 * from L2 to L1.
8483 */
Olivier Deprez157378f2022-04-04 15:47:50 +02008484 if (is_guest_mode(vcpu)) {
8485 r = kvm_x86_ops.nested_ops->check_events(vcpu);
8486 if (r < 0)
8487 goto busy;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008488 }
8489
8490 /* try to inject new event if pending */
8491 if (vcpu->arch.exception.pending) {
Olivier Deprez92d4c212022-12-06 15:05:30 +01008492 /*
8493 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
8494 * value pushed on the stack. Trap-like exception and all #DBs
8495 * leave RF as-is (KVM follows Intel's behavior in this regard;
8496 * AMD states that code breakpoint #DBs excplitly clear RF=0).
8497 *
8498 * Note, most versions of Intel's SDM and AMD's APM incorrectly
8499 * describe the behavior of General Detect #DBs, which are
8500 * fault-like. They do _not_ set RF, a la code breakpoints.
8501 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008502 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
8503 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
8504 X86_EFLAGS_RF);
8505
David Brazdil0f672f62019-12-10 10:32:29 +00008506 if (vcpu->arch.exception.nr == DB_VECTOR) {
David Brazdil0f672f62019-12-10 10:32:29 +00008507 kvm_deliver_exception_payload(vcpu);
8508 if (vcpu->arch.dr7 & DR7_GD) {
8509 vcpu->arch.dr7 &= ~DR7_GD;
8510 kvm_update_dr7(vcpu);
8511 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008512 }
8513
Olivier Deprez0e641232021-09-23 10:07:05 +02008514 kvm_inject_exception(vcpu);
Olivier Deprez92d4c212022-12-06 15:05:30 +01008515
8516 vcpu->arch.exception.pending = false;
8517 vcpu->arch.exception.injected = true;
8518
Olivier Deprez157378f2022-04-04 15:47:50 +02008519 can_inject = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008520 }
8521
Olivier Deprez157378f2022-04-04 15:47:50 +02008522 /*
8523 * Finally, inject interrupt events. If an event cannot be injected
8524 * due to architectural conditions (e.g. IF=0) a window-open exit
8525 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
8526 * and can architecturally be injected, but we cannot do it right now:
8527 * an interrupt could have arrived just now and we have to inject it
8528 * as a vmexit, or there could already an event in the queue, which is
8529 * indicated by can_inject. In that case we request an immediate exit
8530 * in order to make progress and get back here for another iteration.
8531 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
8532 */
8533 if (vcpu->arch.smi_pending) {
8534 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
8535 if (r < 0)
8536 goto busy;
8537 if (r) {
8538 vcpu->arch.smi_pending = false;
8539 ++vcpu->arch.smi_count;
8540 enter_smm(vcpu);
8541 can_inject = false;
8542 } else
8543 kvm_x86_ops.enable_smi_window(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008544 }
8545
Olivier Deprez157378f2022-04-04 15:47:50 +02008546 if (vcpu->arch.nmi_pending) {
8547 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
8548 if (r < 0)
8549 goto busy;
8550 if (r) {
8551 --vcpu->arch.nmi_pending;
8552 vcpu->arch.nmi_injected = true;
8553 kvm_x86_ops.set_nmi(vcpu);
8554 can_inject = false;
8555 WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
8556 }
8557 if (vcpu->arch.nmi_pending)
8558 kvm_x86_ops.enable_nmi_window(vcpu);
8559 }
8560
8561 if (kvm_cpu_has_injectable_intr(vcpu)) {
8562 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
8563 if (r < 0)
8564 goto busy;
8565 if (r) {
8566 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
8567 kvm_x86_ops.set_irq(vcpu);
8568 WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
8569 }
8570 if (kvm_cpu_has_injectable_intr(vcpu))
8571 kvm_x86_ops.enable_irq_window(vcpu);
8572 }
8573
8574 if (is_guest_mode(vcpu) &&
8575 kvm_x86_ops.nested_ops->hv_timer_pending &&
8576 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
8577 *req_immediate_exit = true;
8578
8579 WARN_ON(vcpu->arch.exception.pending);
8580 return;
8581
8582busy:
8583 *req_immediate_exit = true;
8584 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008585}
8586
8587static void process_nmi(struct kvm_vcpu *vcpu)
8588{
8589 unsigned limit = 2;
8590
8591 /*
8592 * x86 is limited to one NMI running, and one NMI pending after it.
8593 * If an NMI is already in progress, limit further NMIs to just one.
8594 * Otherwise, allow two (and we'll inject the first one immediately).
8595 */
Olivier Deprez157378f2022-04-04 15:47:50 +02008596 if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008597 limit = 1;
8598
8599 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
8600 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
8601 kvm_make_request(KVM_REQ_EVENT, vcpu);
8602}
8603
8604static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
8605{
8606 u32 flags = 0;
8607 flags |= seg->g << 23;
8608 flags |= seg->db << 22;
8609 flags |= seg->l << 21;
8610 flags |= seg->avl << 20;
8611 flags |= seg->present << 15;
8612 flags |= seg->dpl << 13;
8613 flags |= seg->s << 12;
8614 flags |= seg->type << 8;
8615 return flags;
8616}
8617
8618static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
8619{
8620 struct kvm_segment seg;
8621 int offset;
8622
8623 kvm_get_segment(vcpu, &seg, n);
8624 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
8625
8626 if (n < 3)
8627 offset = 0x7f84 + n * 12;
8628 else
8629 offset = 0x7f2c + (n - 3) * 12;
8630
8631 put_smstate(u32, buf, offset + 8, seg.base);
8632 put_smstate(u32, buf, offset + 4, seg.limit);
8633 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
8634}
8635
8636#ifdef CONFIG_X86_64
8637static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
8638{
8639 struct kvm_segment seg;
8640 int offset;
8641 u16 flags;
8642
8643 kvm_get_segment(vcpu, &seg, n);
8644 offset = 0x7e00 + n * 16;
8645
8646 flags = enter_smm_get_segment_flags(&seg) >> 8;
8647 put_smstate(u16, buf, offset, seg.selector);
8648 put_smstate(u16, buf, offset + 2, flags);
8649 put_smstate(u32, buf, offset + 4, seg.limit);
8650 put_smstate(u64, buf, offset + 8, seg.base);
8651}
8652#endif
8653
8654static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8655{
8656 struct desc_ptr dt;
8657 struct kvm_segment seg;
8658 unsigned long val;
8659 int i;
8660
8661 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8662 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8663 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8664 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8665
8666 for (i = 0; i < 8; i++)
8667 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8668
8669 kvm_get_dr(vcpu, 6, &val);
8670 put_smstate(u32, buf, 0x7fcc, (u32)val);
8671 kvm_get_dr(vcpu, 7, &val);
8672 put_smstate(u32, buf, 0x7fc8, (u32)val);
8673
8674 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8675 put_smstate(u32, buf, 0x7fc4, seg.selector);
8676 put_smstate(u32, buf, 0x7f64, seg.base);
8677 put_smstate(u32, buf, 0x7f60, seg.limit);
8678 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8679
8680 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8681 put_smstate(u32, buf, 0x7fc0, seg.selector);
8682 put_smstate(u32, buf, 0x7f80, seg.base);
8683 put_smstate(u32, buf, 0x7f7c, seg.limit);
8684 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8685
Olivier Deprez157378f2022-04-04 15:47:50 +02008686 kvm_x86_ops.get_gdt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008687 put_smstate(u32, buf, 0x7f74, dt.address);
8688 put_smstate(u32, buf, 0x7f70, dt.size);
8689
Olivier Deprez157378f2022-04-04 15:47:50 +02008690 kvm_x86_ops.get_idt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008691 put_smstate(u32, buf, 0x7f58, dt.address);
8692 put_smstate(u32, buf, 0x7f54, dt.size);
8693
8694 for (i = 0; i < 6; i++)
8695 enter_smm_save_seg_32(vcpu, buf, i);
8696
8697 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8698
8699 /* revision id */
8700 put_smstate(u32, buf, 0x7efc, 0x00020000);
8701 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8702}
8703
David Brazdil0f672f62019-12-10 10:32:29 +00008704#ifdef CONFIG_X86_64
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008705static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8706{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008707 struct desc_ptr dt;
8708 struct kvm_segment seg;
8709 unsigned long val;
8710 int i;
8711
8712 for (i = 0; i < 16; i++)
8713 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8714
8715 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8716 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8717
8718 kvm_get_dr(vcpu, 6, &val);
8719 put_smstate(u64, buf, 0x7f68, val);
8720 kvm_get_dr(vcpu, 7, &val);
8721 put_smstate(u64, buf, 0x7f60, val);
8722
8723 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8724 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8725 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8726
8727 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8728
8729 /* revision id */
8730 put_smstate(u32, buf, 0x7efc, 0x00020064);
8731
8732 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8733
8734 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8735 put_smstate(u16, buf, 0x7e90, seg.selector);
8736 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8737 put_smstate(u32, buf, 0x7e94, seg.limit);
8738 put_smstate(u64, buf, 0x7e98, seg.base);
8739
Olivier Deprez157378f2022-04-04 15:47:50 +02008740 kvm_x86_ops.get_idt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008741 put_smstate(u32, buf, 0x7e84, dt.size);
8742 put_smstate(u64, buf, 0x7e88, dt.address);
8743
8744 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8745 put_smstate(u16, buf, 0x7e70, seg.selector);
8746 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8747 put_smstate(u32, buf, 0x7e74, seg.limit);
8748 put_smstate(u64, buf, 0x7e78, seg.base);
8749
Olivier Deprez157378f2022-04-04 15:47:50 +02008750 kvm_x86_ops.get_gdt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008751 put_smstate(u32, buf, 0x7e64, dt.size);
8752 put_smstate(u64, buf, 0x7e68, dt.address);
8753
8754 for (i = 0; i < 6; i++)
8755 enter_smm_save_seg_64(vcpu, buf, i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008756}
David Brazdil0f672f62019-12-10 10:32:29 +00008757#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008758
8759static void enter_smm(struct kvm_vcpu *vcpu)
8760{
8761 struct kvm_segment cs, ds;
8762 struct desc_ptr dt;
8763 char buf[512];
8764 u32 cr0;
8765
8766 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8767 memset(buf, 0, 512);
David Brazdil0f672f62019-12-10 10:32:29 +00008768#ifdef CONFIG_X86_64
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008769 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8770 enter_smm_save_state_64(vcpu, buf);
8771 else
David Brazdil0f672f62019-12-10 10:32:29 +00008772#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008773 enter_smm_save_state_32(vcpu, buf);
8774
8775 /*
8776 * Give pre_enter_smm() a chance to make ISA-specific changes to the
8777 * vCPU state (e.g. leave guest mode) after we've saved the state into
8778 * the SMM state-save area.
8779 */
Olivier Deprez157378f2022-04-04 15:47:50 +02008780 kvm_x86_ops.pre_enter_smm(vcpu, buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008781
8782 vcpu->arch.hflags |= HF_SMM_MASK;
8783 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8784
Olivier Deprez157378f2022-04-04 15:47:50 +02008785 if (kvm_x86_ops.get_nmi_mask(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008786 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8787 else
Olivier Deprez157378f2022-04-04 15:47:50 +02008788 kvm_x86_ops.set_nmi_mask(vcpu, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008789
8790 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8791 kvm_rip_write(vcpu, 0x8000);
8792
8793 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
Olivier Deprez157378f2022-04-04 15:47:50 +02008794 kvm_x86_ops.set_cr0(vcpu, cr0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008795 vcpu->arch.cr0 = cr0;
8796
Olivier Deprez157378f2022-04-04 15:47:50 +02008797 kvm_x86_ops.set_cr4(vcpu, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008798
8799 /* Undocumented: IDT limit is set to zero on entry to SMM. */
8800 dt.address = dt.size = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02008801 kvm_x86_ops.set_idt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008802
8803 __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8804
8805 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8806 cs.base = vcpu->arch.smbase;
8807
8808 ds.selector = 0;
8809 ds.base = 0;
8810
8811 cs.limit = ds.limit = 0xffffffff;
8812 cs.type = ds.type = 0x3;
8813 cs.dpl = ds.dpl = 0;
8814 cs.db = ds.db = 0;
8815 cs.s = ds.s = 1;
8816 cs.l = ds.l = 0;
8817 cs.g = ds.g = 1;
8818 cs.avl = ds.avl = 0;
8819 cs.present = ds.present = 1;
8820 cs.unusable = ds.unusable = 0;
8821 cs.padding = ds.padding = 0;
8822
8823 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8824 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8825 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8826 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8827 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8828 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8829
David Brazdil0f672f62019-12-10 10:32:29 +00008830#ifdef CONFIG_X86_64
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008831 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
Olivier Deprez157378f2022-04-04 15:47:50 +02008832 kvm_x86_ops.set_efer(vcpu, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00008833#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008834
Olivier Deprez157378f2022-04-04 15:47:50 +02008835 kvm_update_cpuid_runtime(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008836 kvm_mmu_reset_context(vcpu);
8837}
8838
8839static void process_smi(struct kvm_vcpu *vcpu)
8840{
8841 vcpu->arch.smi_pending = true;
8842 kvm_make_request(KVM_REQ_EVENT, vcpu);
8843}
8844
Olivier Deprez157378f2022-04-04 15:47:50 +02008845void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8846 unsigned long *vcpu_bitmap)
8847{
8848 cpumask_var_t cpus;
8849
8850 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8851
8852 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8853 NULL, vcpu_bitmap, cpus);
8854
8855 free_cpumask_var(cpus);
8856}
8857
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008858void kvm_make_scan_ioapic_request(struct kvm *kvm)
8859{
8860 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8861}
8862
Olivier Deprez157378f2022-04-04 15:47:50 +02008863void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8864{
8865 if (!lapic_in_kernel(vcpu))
8866 return;
8867
8868 vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8869 kvm_apic_update_apicv(vcpu);
8870 kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8871}
8872EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8873
8874/*
8875 * NOTE: Do not hold any lock prior to calling this.
8876 *
8877 * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8878 * locked, because it calls __x86_set_memory_region() which does
8879 * synchronize_srcu(&kvm->srcu).
8880 */
8881void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8882{
8883 struct kvm_vcpu *except;
8884 unsigned long old, new, expected;
8885
8886 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8887 !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8888 return;
8889
8890 old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8891 do {
8892 expected = new = old;
8893 if (activate)
8894 __clear_bit(bit, &new);
8895 else
8896 __set_bit(bit, &new);
8897 if (new == old)
8898 break;
8899 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8900 } while (old != expected);
8901
8902 if (!!old == !!new)
8903 return;
8904
8905 trace_kvm_apicv_update_request(activate, bit);
8906 if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8907 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8908
8909 /*
8910 * Sending request to update APICV for all other vcpus,
8911 * while update the calling vcpu immediately instead of
8912 * waiting for another #VMEXIT to handle the request.
8913 */
8914 except = kvm_get_running_vcpu();
8915 kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8916 except);
8917 if (except)
8918 kvm_vcpu_update_apicv(except);
8919}
8920EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8921
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008922static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8923{
8924 if (!kvm_apic_present(vcpu))
8925 return;
8926
8927 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8928
8929 if (irqchip_split(vcpu->kvm))
8930 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8931 else {
8932 if (vcpu->arch.apicv_active)
Olivier Deprez157378f2022-04-04 15:47:50 +02008933 kvm_x86_ops.sync_pir_to_irr(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008934 if (ioapic_in_kernel(vcpu->kvm))
8935 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8936 }
8937
8938 if (is_guest_mode(vcpu))
8939 vcpu->arch.load_eoi_exitmap_pending = true;
8940 else
8941 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8942}
8943
8944static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8945{
8946 u64 eoi_exit_bitmap[4];
8947
8948 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8949 return;
8950
8951 bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8952 vcpu_to_synic(vcpu)->vec_bitmap, 256);
Olivier Deprez157378f2022-04-04 15:47:50 +02008953 kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008954}
8955
Olivier Deprez0e641232021-09-23 10:07:05 +02008956void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8957 unsigned long start, unsigned long end)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008958{
8959 unsigned long apic_address;
8960
8961 /*
8962 * The physical address of apic access page is stored in the VMCS.
8963 * Update it when it becomes invalid.
8964 */
8965 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8966 if (start <= apic_address && apic_address < end)
8967 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008968}
8969
Olivier Deprez92d4c212022-12-06 15:05:30 +01008970void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
8971{
8972 if (kvm_x86_ops.guest_memory_reclaimed)
8973 kvm_x86_ops.guest_memory_reclaimed(kvm);
8974}
8975
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008976void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8977{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008978 if (!lapic_in_kernel(vcpu))
8979 return;
8980
Olivier Deprez157378f2022-04-04 15:47:50 +02008981 if (!kvm_x86_ops.set_apic_access_page_addr)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008982 return;
8983
Olivier Deprez157378f2022-04-04 15:47:50 +02008984 kvm_x86_ops.set_apic_access_page_addr(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008985}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008986
8987void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8988{
8989 smp_send_reschedule(vcpu->cpu);
8990}
8991EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8992
8993/*
8994 * Returns 1 to let vcpu_run() continue the guest execution loop without
8995 * exiting to the userspace. Otherwise, the value will be returned to the
8996 * userspace.
8997 */
8998static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8999{
9000 int r;
9001 bool req_int_win =
9002 dm_request_for_irq_injection(vcpu) &&
9003 kvm_cpu_accept_dm_intr(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02009004 fastpath_t exit_fastpath;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009005
9006 bool req_immediate_exit = false;
9007
9008 if (kvm_request_pending(vcpu)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009009 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
9010 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
David Brazdil0f672f62019-12-10 10:32:29 +00009011 r = 0;
9012 goto out;
9013 }
9014 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009015 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
9016 kvm_mmu_unload(vcpu);
9017 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
9018 __kvm_migrate_timers(vcpu);
9019 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
9020 kvm_gen_update_masterclock(vcpu->kvm);
9021 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
9022 kvm_gen_kvmclock_update(vcpu);
9023 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
9024 r = kvm_guest_time_update(vcpu);
9025 if (unlikely(r))
9026 goto out;
9027 }
9028 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
9029 kvm_mmu_sync_roots(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02009030 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
9031 kvm_mmu_load_pgd(vcpu);
9032 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
9033 kvm_vcpu_flush_tlb_all(vcpu);
9034
9035 /* Flushing all ASIDs flushes the current ASID... */
9036 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
9037 }
9038 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
9039 kvm_vcpu_flush_tlb_current(vcpu);
9040 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
9041 kvm_vcpu_flush_tlb_guest(vcpu);
9042
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009043 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
9044 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
9045 r = 0;
9046 goto out;
9047 }
9048 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9049 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
9050 vcpu->mmio_needed = 0;
9051 r = 0;
9052 goto out;
9053 }
9054 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
9055 /* Page is swapped out. Do synthetic halt */
9056 vcpu->arch.apf.halted = true;
9057 r = 1;
9058 goto out;
9059 }
9060 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
9061 record_steal_time(vcpu);
9062 if (kvm_check_request(KVM_REQ_SMI, vcpu))
9063 process_smi(vcpu);
9064 if (kvm_check_request(KVM_REQ_NMI, vcpu))
9065 process_nmi(vcpu);
9066 if (kvm_check_request(KVM_REQ_PMU, vcpu))
9067 kvm_pmu_handle_event(vcpu);
9068 if (kvm_check_request(KVM_REQ_PMI, vcpu))
9069 kvm_pmu_deliver_pmi(vcpu);
9070 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
9071 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
9072 if (test_bit(vcpu->arch.pending_ioapic_eoi,
9073 vcpu->arch.ioapic_handled_vectors)) {
9074 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
9075 vcpu->run->eoi.vector =
9076 vcpu->arch.pending_ioapic_eoi;
9077 r = 0;
9078 goto out;
9079 }
9080 }
9081 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
9082 vcpu_scan_ioapic(vcpu);
9083 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
9084 vcpu_load_eoi_exitmap(vcpu);
9085 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
9086 kvm_vcpu_reload_apic_access_page(vcpu);
9087 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
9088 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9089 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
9090 r = 0;
9091 goto out;
9092 }
9093 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
9094 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9095 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
9096 r = 0;
9097 goto out;
9098 }
9099 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
9100 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
9101 vcpu->run->hyperv = vcpu->arch.hyperv.exit;
9102 r = 0;
9103 goto out;
9104 }
9105
9106 /*
9107 * KVM_REQ_HV_STIMER has to be processed after
9108 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
9109 * depend on the guest clock being up-to-date
9110 */
9111 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
9112 kvm_hv_process_stimers(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02009113 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
9114 kvm_vcpu_update_apicv(vcpu);
9115 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
9116 kvm_check_async_pf_completion(vcpu);
9117 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
9118 kvm_x86_ops.msr_filter_changed(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009119 }
9120
9121 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
9122 ++vcpu->stat.req_event;
9123 kvm_apic_accept_events(vcpu);
9124 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
9125 r = 1;
9126 goto out;
9127 }
9128
Olivier Deprez157378f2022-04-04 15:47:50 +02009129 inject_pending_event(vcpu, &req_immediate_exit);
9130 if (req_int_win)
9131 kvm_x86_ops.enable_irq_window(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009132
9133 if (kvm_lapic_enabled(vcpu)) {
9134 update_cr8_intercept(vcpu);
9135 kvm_lapic_sync_to_vapic(vcpu);
9136 }
9137 }
9138
9139 r = kvm_mmu_reload(vcpu);
9140 if (unlikely(r)) {
9141 goto cancel_injection;
9142 }
9143
9144 preempt_disable();
9145
Olivier Deprez157378f2022-04-04 15:47:50 +02009146 kvm_x86_ops.prepare_guest_switch(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009147
9148 /*
9149 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
9150 * IPI are then delayed after guest entry, which ensures that they
9151 * result in virtual interrupt delivery.
9152 */
9153 local_irq_disable();
9154 vcpu->mode = IN_GUEST_MODE;
9155
9156 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9157
9158 /*
9159 * 1) We should set ->mode before checking ->requests. Please see
9160 * the comment in kvm_vcpu_exiting_guest_mode().
9161 *
David Brazdil0f672f62019-12-10 10:32:29 +00009162 * 2) For APICv, we should set ->mode before checking PID.ON. This
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009163 * pairs with the memory barrier implicit in pi_test_and_set_on
9164 * (see vmx_deliver_posted_interrupt).
9165 *
9166 * 3) This also orders the write to mode from any reads to the page
9167 * tables done while the VCPU is running. Please see the comment
9168 * in kvm_flush_remote_tlbs.
9169 */
9170 smp_mb__after_srcu_read_unlock();
9171
9172 /*
9173 * This handles the case where a posted interrupt was
9174 * notified with kvm_vcpu_kick.
9175 */
9176 if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
Olivier Deprez157378f2022-04-04 15:47:50 +02009177 kvm_x86_ops.sync_pir_to_irr(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009178
Olivier Deprez157378f2022-04-04 15:47:50 +02009179 if (kvm_vcpu_exit_request(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009180 vcpu->mode = OUTSIDE_GUEST_MODE;
9181 smp_wmb();
9182 local_irq_enable();
9183 preempt_enable();
9184 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9185 r = 1;
9186 goto cancel_injection;
9187 }
9188
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009189 if (req_immediate_exit) {
9190 kvm_make_request(KVM_REQ_EVENT, vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02009191 kvm_x86_ops.request_immediate_exit(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009192 }
9193
Olivier Deprez157378f2022-04-04 15:47:50 +02009194 trace_kvm_entry(vcpu);
Olivier Deprez0e641232021-09-23 10:07:05 +02009195
9196 fpregs_assert_state_consistent();
9197 if (test_thread_flag(TIF_NEED_FPU_LOAD))
9198 switch_fpu_return();
David Brazdil0f672f62019-12-10 10:32:29 +00009199
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009200 if (unlikely(vcpu->arch.switch_db_regs)) {
9201 set_debugreg(0, 7);
9202 set_debugreg(vcpu->arch.eff_db[0], 0);
9203 set_debugreg(vcpu->arch.eff_db[1], 1);
9204 set_debugreg(vcpu->arch.eff_db[2], 2);
9205 set_debugreg(vcpu->arch.eff_db[3], 3);
9206 set_debugreg(vcpu->arch.dr6, 6);
9207 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
Olivier Deprez0e641232021-09-23 10:07:05 +02009208 } else if (unlikely(hw_breakpoint_active())) {
9209 set_debugreg(0, 7);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009210 }
9211
Olivier Deprez157378f2022-04-04 15:47:50 +02009212 exit_fastpath = kvm_x86_ops.run(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009213
9214 /*
9215 * Do this here before restoring debug registers on the host. And
9216 * since we do this before handling the vmexit, a DR access vmexit
9217 * can (a) read the correct value of the debug registers, (b) set
9218 * KVM_DEBUGREG_WONT_EXIT again.
9219 */
9220 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
9221 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
Olivier Deprez157378f2022-04-04 15:47:50 +02009222 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009223 kvm_update_dr0123(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009224 kvm_update_dr7(vcpu);
9225 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
9226 }
9227
9228 /*
9229 * If the guest has used debug registers, at least dr7
9230 * will be disabled while returning to the host.
9231 * If we don't have active breakpoints in the host, we don't
9232 * care about the messed up debug address registers. But if
9233 * we have some of them active, restore the old state.
9234 */
9235 if (hw_breakpoint_active())
9236 hw_breakpoint_restore();
9237
Olivier Deprez157378f2022-04-04 15:47:50 +02009238 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009239 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
9240
9241 vcpu->mode = OUTSIDE_GUEST_MODE;
9242 smp_wmb();
9243
Olivier Deprez157378f2022-04-04 15:47:50 +02009244 kvm_x86_ops.handle_exit_irqoff(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009245
David Brazdil0f672f62019-12-10 10:32:29 +00009246 /*
9247 * Consume any pending interrupts, including the possible source of
9248 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
9249 * An instruction is required after local_irq_enable() to fully unblock
9250 * interrupts on processors that implement an interrupt shadow, the
9251 * stat.exits increment will do nicely.
9252 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009253 kvm_before_interrupt(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +00009254 local_irq_enable();
9255 ++vcpu->stat.exits;
9256 local_irq_disable();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009257 kvm_after_interrupt(vcpu);
9258
Olivier Deprez157378f2022-04-04 15:47:50 +02009259 /*
9260 * Wait until after servicing IRQs to account guest time so that any
9261 * ticks that occurred while running the guest are properly accounted
9262 * to the guest. Waiting until IRQs are enabled degrades the accuracy
9263 * of accounting via context tracking, but the loss of accuracy is
9264 * acceptable for all known use cases.
9265 */
9266 vtime_account_guest_exit();
9267
David Brazdil0f672f62019-12-10 10:32:29 +00009268 if (lapic_in_kernel(vcpu)) {
9269 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
9270 if (delta != S64_MIN) {
9271 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
9272 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
9273 }
9274 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009275
9276 local_irq_enable();
9277 preempt_enable();
9278
9279 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9280
9281 /*
9282 * Profile KVM exit RIPs:
9283 */
9284 if (unlikely(prof_on == KVM_PROFILING)) {
9285 unsigned long rip = kvm_rip_read(vcpu);
9286 profile_hit(KVM_PROFILING, (void *)rip);
9287 }
9288
9289 if (unlikely(vcpu->arch.tsc_always_catchup))
9290 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9291
9292 if (vcpu->arch.apic_attention)
9293 kvm_lapic_sync_from_vapic(vcpu);
9294
Olivier Deprez157378f2022-04-04 15:47:50 +02009295 r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009296 return r;
9297
9298cancel_injection:
Olivier Deprez157378f2022-04-04 15:47:50 +02009299 if (req_immediate_exit)
9300 kvm_make_request(KVM_REQ_EVENT, vcpu);
9301 kvm_x86_ops.cancel_injection(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009302 if (unlikely(vcpu->arch.apic_attention))
9303 kvm_lapic_sync_from_vapic(vcpu);
9304out:
9305 return r;
9306}
9307
9308static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
9309{
9310 if (!kvm_arch_vcpu_runnable(vcpu) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02009311 (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009312 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9313 kvm_vcpu_block(vcpu);
9314 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9315
Olivier Deprez157378f2022-04-04 15:47:50 +02009316 if (kvm_x86_ops.post_block)
9317 kvm_x86_ops.post_block(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009318
9319 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
9320 return 1;
9321 }
9322
9323 kvm_apic_accept_events(vcpu);
9324 switch(vcpu->arch.mp_state) {
9325 case KVM_MP_STATE_HALTED:
9326 vcpu->arch.pv.pv_unhalted = false;
9327 vcpu->arch.mp_state =
9328 KVM_MP_STATE_RUNNABLE;
Olivier Deprez157378f2022-04-04 15:47:50 +02009329 fallthrough;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009330 case KVM_MP_STATE_RUNNABLE:
9331 vcpu->arch.apf.halted = false;
9332 break;
9333 case KVM_MP_STATE_INIT_RECEIVED:
9334 break;
9335 default:
9336 return -EINTR;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009337 }
9338 return 1;
9339}
9340
9341static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
9342{
Olivier Deprez157378f2022-04-04 15:47:50 +02009343 if (is_guest_mode(vcpu))
9344 kvm_x86_ops.nested_ops->check_events(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009345
9346 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
9347 !vcpu->arch.apf.halted);
9348}
9349
9350static int vcpu_run(struct kvm_vcpu *vcpu)
9351{
9352 int r;
9353 struct kvm *kvm = vcpu->kvm;
9354
9355 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9356 vcpu->arch.l1tf_flush_l1d = true;
9357
9358 for (;;) {
9359 if (kvm_vcpu_running(vcpu)) {
9360 r = vcpu_enter_guest(vcpu);
9361 } else {
9362 r = vcpu_block(kvm, vcpu);
9363 }
9364
9365 if (r <= 0)
9366 break;
9367
9368 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
9369 if (kvm_cpu_has_pending_timer(vcpu))
9370 kvm_inject_pending_timer_irqs(vcpu);
9371
9372 if (dm_request_for_irq_injection(vcpu) &&
9373 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
9374 r = 0;
9375 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
9376 ++vcpu->stat.request_irq_exits;
9377 break;
9378 }
9379
Olivier Deprez157378f2022-04-04 15:47:50 +02009380 if (__xfer_to_guest_mode_work_pending()) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009381 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
Olivier Deprez157378f2022-04-04 15:47:50 +02009382 r = xfer_to_guest_mode_handle_work(vcpu);
9383 if (r)
9384 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009385 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
9386 }
9387 }
9388
9389 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
9390
9391 return r;
9392}
9393
9394static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
9395{
9396 int r;
David Brazdil0f672f62019-12-10 10:32:29 +00009397
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009398 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9399 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
9400 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
David Brazdil0f672f62019-12-10 10:32:29 +00009401 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009402}
9403
9404static int complete_emulated_pio(struct kvm_vcpu *vcpu)
9405{
9406 BUG_ON(!vcpu->arch.pio.count);
9407
9408 return complete_emulated_io(vcpu);
9409}
9410
9411/*
9412 * Implements the following, as a state machine:
9413 *
9414 * read:
9415 * for each fragment
9416 * for each mmio piece in the fragment
9417 * write gpa, len
9418 * exit
9419 * copy data
9420 * execute insn
9421 *
9422 * write:
9423 * for each fragment
9424 * for each mmio piece in the fragment
9425 * write gpa, len
9426 * copy data
9427 * exit
9428 */
9429static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
9430{
9431 struct kvm_run *run = vcpu->run;
9432 struct kvm_mmio_fragment *frag;
9433 unsigned len;
9434
9435 BUG_ON(!vcpu->mmio_needed);
9436
9437 /* Complete previous fragment */
9438 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
9439 len = min(8u, frag->len);
9440 if (!vcpu->mmio_is_write)
9441 memcpy(frag->data, run->mmio.data, len);
9442
9443 if (frag->len <= 8) {
9444 /* Switch to the next fragment. */
9445 frag++;
9446 vcpu->mmio_cur_fragment++;
9447 } else {
9448 /* Go forward to the next mmio piece. */
9449 frag->data += len;
9450 frag->gpa += len;
9451 frag->len -= len;
9452 }
9453
9454 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
9455 vcpu->mmio_needed = 0;
9456
9457 /* FIXME: return into emulator if single-stepping. */
9458 if (vcpu->mmio_is_write)
9459 return 1;
9460 vcpu->mmio_read_completed = 1;
9461 return complete_emulated_io(vcpu);
9462 }
9463
9464 run->exit_reason = KVM_EXIT_MMIO;
9465 run->mmio.phys_addr = frag->gpa;
9466 if (vcpu->mmio_is_write)
9467 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
9468 run->mmio.len = min(8u, frag->len);
9469 run->mmio.is_write = vcpu->mmio_is_write;
9470 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9471 return 0;
9472}
9473
Olivier Deprez0e641232021-09-23 10:07:05 +02009474static void kvm_save_current_fpu(struct fpu *fpu)
9475{
9476 /*
9477 * If the target FPU state is not resident in the CPU registers, just
9478 * memcpy() from current, else save CPU state directly to the target.
9479 */
9480 if (test_thread_flag(TIF_NEED_FPU_LOAD))
9481 memcpy(&fpu->state, &current->thread.fpu.state,
9482 fpu_kernel_xstate_size);
9483 else
9484 copy_fpregs_to_fpstate(fpu);
9485}
9486
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009487/* Swap (qemu) user FPU context for the guest FPU context. */
9488static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
9489{
David Brazdil0f672f62019-12-10 10:32:29 +00009490 fpregs_lock();
9491
Olivier Deprez0e641232021-09-23 10:07:05 +02009492 kvm_save_current_fpu(vcpu->arch.user_fpu);
9493
Olivier Deprez157378f2022-04-04 15:47:50 +02009494 /* PKRU is separately restored in kvm_x86_ops.run. */
David Brazdil0f672f62019-12-10 10:32:29 +00009495 __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009496 ~XFEATURE_MASK_PKRU);
David Brazdil0f672f62019-12-10 10:32:29 +00009497
9498 fpregs_mark_activate();
9499 fpregs_unlock();
9500
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009501 trace_kvm_fpu(1);
9502}
9503
9504/* When vcpu_run ends, restore user space FPU context. */
9505static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
9506{
David Brazdil0f672f62019-12-10 10:32:29 +00009507 fpregs_lock();
9508
Olivier Deprez0e641232021-09-23 10:07:05 +02009509 kvm_save_current_fpu(vcpu->arch.guest_fpu);
9510
David Brazdil0f672f62019-12-10 10:32:29 +00009511 copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
9512
9513 fpregs_mark_activate();
9514 fpregs_unlock();
9515
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009516 ++vcpu->stat.fpu_reload;
9517 trace_kvm_fpu(0);
9518}
9519
Olivier Deprez157378f2022-04-04 15:47:50 +02009520int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009521{
Olivier Deprez157378f2022-04-04 15:47:50 +02009522 struct kvm_run *kvm_run = vcpu->run;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009523 int r;
9524
9525 vcpu_load(vcpu);
9526 kvm_sigset_activate(vcpu);
9527 kvm_load_guest_fpu(vcpu);
9528
9529 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
9530 if (kvm_run->immediate_exit) {
9531 r = -EINTR;
9532 goto out;
9533 }
9534 kvm_vcpu_block(vcpu);
9535 kvm_apic_accept_events(vcpu);
9536 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
9537 r = -EAGAIN;
9538 if (signal_pending(current)) {
9539 r = -EINTR;
Olivier Deprez157378f2022-04-04 15:47:50 +02009540 kvm_run->exit_reason = KVM_EXIT_INTR;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009541 ++vcpu->stat.signal_exits;
9542 }
9543 goto out;
9544 }
9545
Olivier Deprez157378f2022-04-04 15:47:50 +02009546 if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009547 r = -EINVAL;
9548 goto out;
9549 }
9550
Olivier Deprez157378f2022-04-04 15:47:50 +02009551 if (kvm_run->kvm_dirty_regs) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009552 r = sync_regs(vcpu);
9553 if (r != 0)
9554 goto out;
9555 }
9556
9557 /* re-sync apic's tpr */
9558 if (!lapic_in_kernel(vcpu)) {
9559 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
9560 r = -EINVAL;
9561 goto out;
9562 }
9563 }
9564
9565 if (unlikely(vcpu->arch.complete_userspace_io)) {
9566 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
9567 vcpu->arch.complete_userspace_io = NULL;
9568 r = cui(vcpu);
9569 if (r <= 0)
9570 goto out;
9571 } else
9572 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
9573
9574 if (kvm_run->immediate_exit)
9575 r = -EINTR;
9576 else
9577 r = vcpu_run(vcpu);
9578
9579out:
9580 kvm_put_guest_fpu(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +02009581 if (kvm_run->kvm_valid_regs)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009582 store_regs(vcpu);
9583 post_kvm_run_save(vcpu);
9584 kvm_sigset_deactivate(vcpu);
9585
9586 vcpu_put(vcpu);
9587 return r;
9588}
9589
9590static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9591{
9592 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
9593 /*
9594 * We are here if userspace calls get_regs() in the middle of
9595 * instruction emulation. Registers state needs to be copied
9596 * back from emulation context to vcpu. Userspace shouldn't do
9597 * that usually, but some bad designed PV devices (vmware
9598 * backdoor interface) need this to work
9599 */
Olivier Deprez157378f2022-04-04 15:47:50 +02009600 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009601 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9602 }
David Brazdil0f672f62019-12-10 10:32:29 +00009603 regs->rax = kvm_rax_read(vcpu);
9604 regs->rbx = kvm_rbx_read(vcpu);
9605 regs->rcx = kvm_rcx_read(vcpu);
9606 regs->rdx = kvm_rdx_read(vcpu);
9607 regs->rsi = kvm_rsi_read(vcpu);
9608 regs->rdi = kvm_rdi_read(vcpu);
9609 regs->rsp = kvm_rsp_read(vcpu);
9610 regs->rbp = kvm_rbp_read(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009611#ifdef CONFIG_X86_64
David Brazdil0f672f62019-12-10 10:32:29 +00009612 regs->r8 = kvm_r8_read(vcpu);
9613 regs->r9 = kvm_r9_read(vcpu);
9614 regs->r10 = kvm_r10_read(vcpu);
9615 regs->r11 = kvm_r11_read(vcpu);
9616 regs->r12 = kvm_r12_read(vcpu);
9617 regs->r13 = kvm_r13_read(vcpu);
9618 regs->r14 = kvm_r14_read(vcpu);
9619 regs->r15 = kvm_r15_read(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009620#endif
9621
9622 regs->rip = kvm_rip_read(vcpu);
9623 regs->rflags = kvm_get_rflags(vcpu);
9624}
9625
9626int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9627{
9628 vcpu_load(vcpu);
9629 __get_regs(vcpu, regs);
9630 vcpu_put(vcpu);
9631 return 0;
9632}
9633
9634static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9635{
9636 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
9637 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9638
David Brazdil0f672f62019-12-10 10:32:29 +00009639 kvm_rax_write(vcpu, regs->rax);
9640 kvm_rbx_write(vcpu, regs->rbx);
9641 kvm_rcx_write(vcpu, regs->rcx);
9642 kvm_rdx_write(vcpu, regs->rdx);
9643 kvm_rsi_write(vcpu, regs->rsi);
9644 kvm_rdi_write(vcpu, regs->rdi);
9645 kvm_rsp_write(vcpu, regs->rsp);
9646 kvm_rbp_write(vcpu, regs->rbp);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009647#ifdef CONFIG_X86_64
David Brazdil0f672f62019-12-10 10:32:29 +00009648 kvm_r8_write(vcpu, regs->r8);
9649 kvm_r9_write(vcpu, regs->r9);
9650 kvm_r10_write(vcpu, regs->r10);
9651 kvm_r11_write(vcpu, regs->r11);
9652 kvm_r12_write(vcpu, regs->r12);
9653 kvm_r13_write(vcpu, regs->r13);
9654 kvm_r14_write(vcpu, regs->r14);
9655 kvm_r15_write(vcpu, regs->r15);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009656#endif
9657
9658 kvm_rip_write(vcpu, regs->rip);
9659 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9660
9661 vcpu->arch.exception.pending = false;
9662
9663 kvm_make_request(KVM_REQ_EVENT, vcpu);
9664}
9665
9666int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9667{
9668 vcpu_load(vcpu);
9669 __set_regs(vcpu, regs);
9670 vcpu_put(vcpu);
9671 return 0;
9672}
9673
9674void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9675{
9676 struct kvm_segment cs;
9677
9678 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9679 *db = cs.db;
9680 *l = cs.l;
9681}
9682EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9683
9684static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9685{
9686 struct desc_ptr dt;
9687
9688 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9689 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9690 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9691 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9692 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9693 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9694
9695 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9696 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9697
Olivier Deprez157378f2022-04-04 15:47:50 +02009698 kvm_x86_ops.get_idt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009699 sregs->idt.limit = dt.size;
9700 sregs->idt.base = dt.address;
Olivier Deprez157378f2022-04-04 15:47:50 +02009701 kvm_x86_ops.get_gdt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009702 sregs->gdt.limit = dt.size;
9703 sregs->gdt.base = dt.address;
9704
9705 sregs->cr0 = kvm_read_cr0(vcpu);
9706 sregs->cr2 = vcpu->arch.cr2;
9707 sregs->cr3 = kvm_read_cr3(vcpu);
9708 sregs->cr4 = kvm_read_cr4(vcpu);
9709 sregs->cr8 = kvm_get_cr8(vcpu);
9710 sregs->efer = vcpu->arch.efer;
9711 sregs->apic_base = kvm_get_apic_base(vcpu);
9712
David Brazdil0f672f62019-12-10 10:32:29 +00009713 memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009714
9715 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9716 set_bit(vcpu->arch.interrupt.nr,
9717 (unsigned long *)sregs->interrupt_bitmap);
9718}
9719
9720int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9721 struct kvm_sregs *sregs)
9722{
9723 vcpu_load(vcpu);
9724 __get_sregs(vcpu, sregs);
9725 vcpu_put(vcpu);
9726 return 0;
9727}
9728
9729int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9730 struct kvm_mp_state *mp_state)
9731{
9732 vcpu_load(vcpu);
Olivier Deprez0e641232021-09-23 10:07:05 +02009733 if (kvm_mpx_supported())
9734 kvm_load_guest_fpu(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009735
9736 kvm_apic_accept_events(vcpu);
9737 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9738 vcpu->arch.pv.pv_unhalted)
9739 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9740 else
9741 mp_state->mp_state = vcpu->arch.mp_state;
9742
Olivier Deprez0e641232021-09-23 10:07:05 +02009743 if (kvm_mpx_supported())
9744 kvm_put_guest_fpu(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009745 vcpu_put(vcpu);
9746 return 0;
9747}
9748
9749int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9750 struct kvm_mp_state *mp_state)
9751{
9752 int ret = -EINVAL;
9753
9754 vcpu_load(vcpu);
9755
9756 if (!lapic_in_kernel(vcpu) &&
9757 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9758 goto out;
9759
Olivier Deprez157378f2022-04-04 15:47:50 +02009760 /*
9761 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9762 * INIT state; latched init should be reported using
9763 * KVM_SET_VCPU_EVENTS, so reject it here.
9764 */
9765 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009766 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9767 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9768 goto out;
9769
9770 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9771 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9772 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9773 } else
9774 vcpu->arch.mp_state = mp_state->mp_state;
9775 kvm_make_request(KVM_REQ_EVENT, vcpu);
9776
9777 ret = 0;
9778out:
9779 vcpu_put(vcpu);
9780 return ret;
9781}
9782
9783int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9784 int reason, bool has_error_code, u32 error_code)
9785{
Olivier Deprez157378f2022-04-04 15:47:50 +02009786 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009787 int ret;
9788
9789 init_emulate_ctxt(vcpu);
9790
9791 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9792 has_error_code, error_code);
David Brazdil0f672f62019-12-10 10:32:29 +00009793 if (ret) {
9794 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9795 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9796 vcpu->run->internal.ndata = 0;
9797 return 0;
9798 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009799
9800 kvm_rip_write(vcpu, ctxt->eip);
9801 kvm_set_rflags(vcpu, ctxt->eflags);
David Brazdil0f672f62019-12-10 10:32:29 +00009802 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009803}
9804EXPORT_SYMBOL_GPL(kvm_task_switch);
9805
9806static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9807{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009808 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9809 /*
9810 * When EFER.LME and CR0.PG are set, the processor is in
9811 * 64-bit mode (though maybe in a 32-bit code segment).
9812 * CR4.PAE and EFER.LMA must be set.
9813 */
9814 if (!(sregs->cr4 & X86_CR4_PAE)
9815 || !(sregs->efer & EFER_LMA))
9816 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02009817 if (sregs->cr3 & vcpu->arch.cr3_lm_rsvd_bits)
9818 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009819 } else {
9820 /*
9821 * Not in 64-bit mode: EFER.LMA is clear and the code
9822 * segment cannot be 64-bit.
9823 */
9824 if (sregs->efer & EFER_LMA || sregs->cs.l)
9825 return -EINVAL;
9826 }
9827
David Brazdil0f672f62019-12-10 10:32:29 +00009828 return kvm_valid_cr4(vcpu, sregs->cr4);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009829}
9830
9831static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9832{
9833 struct msr_data apic_base_msr;
9834 int mmu_reset_needed = 0;
9835 int cpuid_update_needed = 0;
9836 int pending_vec, max_bits, idx;
9837 struct desc_ptr dt;
9838 int ret = -EINVAL;
9839
9840 if (kvm_valid_sregs(vcpu, sregs))
9841 goto out;
9842
9843 apic_base_msr.data = sregs->apic_base;
9844 apic_base_msr.host_initiated = true;
9845 if (kvm_set_apic_base(vcpu, &apic_base_msr))
9846 goto out;
9847
9848 dt.size = sregs->idt.limit;
9849 dt.address = sregs->idt.base;
Olivier Deprez157378f2022-04-04 15:47:50 +02009850 kvm_x86_ops.set_idt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009851 dt.size = sregs->gdt.limit;
9852 dt.address = sregs->gdt.base;
Olivier Deprez157378f2022-04-04 15:47:50 +02009853 kvm_x86_ops.set_gdt(vcpu, &dt);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009854
9855 vcpu->arch.cr2 = sregs->cr2;
9856 mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9857 vcpu->arch.cr3 = sregs->cr3;
Olivier Deprez157378f2022-04-04 15:47:50 +02009858 kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009859
9860 kvm_set_cr8(vcpu, sregs->cr8);
9861
9862 mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
Olivier Deprez157378f2022-04-04 15:47:50 +02009863 kvm_x86_ops.set_efer(vcpu, sregs->efer);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009864
9865 mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
Olivier Deprez157378f2022-04-04 15:47:50 +02009866 kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009867 vcpu->arch.cr0 = sregs->cr0;
9868
9869 mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9870 cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9871 (X86_CR4_OSXSAVE | X86_CR4_PKE));
Olivier Deprez157378f2022-04-04 15:47:50 +02009872 kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009873 if (cpuid_update_needed)
Olivier Deprez157378f2022-04-04 15:47:50 +02009874 kvm_update_cpuid_runtime(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009875
9876 idx = srcu_read_lock(&vcpu->kvm->srcu);
David Brazdil0f672f62019-12-10 10:32:29 +00009877 if (is_pae_paging(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009878 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9879 mmu_reset_needed = 1;
9880 }
9881 srcu_read_unlock(&vcpu->kvm->srcu, idx);
9882
9883 if (mmu_reset_needed)
9884 kvm_mmu_reset_context(vcpu);
9885
9886 max_bits = KVM_NR_INTERRUPTS;
9887 pending_vec = find_first_bit(
9888 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9889 if (pending_vec < max_bits) {
9890 kvm_queue_interrupt(vcpu, pending_vec, false);
9891 pr_debug("Set back pending irq %d\n", pending_vec);
9892 }
9893
9894 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9895 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9896 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9897 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9898 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9899 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9900
9901 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9902 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9903
9904 update_cr8_intercept(vcpu);
9905
9906 /* Older userspace won't unhalt the vcpu on reset. */
9907 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9908 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9909 !is_protmode(vcpu))
9910 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9911
9912 kvm_make_request(KVM_REQ_EVENT, vcpu);
9913
9914 ret = 0;
9915out:
9916 return ret;
9917}
9918
9919int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9920 struct kvm_sregs *sregs)
9921{
9922 int ret;
9923
9924 vcpu_load(vcpu);
9925 ret = __set_sregs(vcpu, sregs);
9926 vcpu_put(vcpu);
9927 return ret;
9928}
9929
9930int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9931 struct kvm_guest_debug *dbg)
9932{
9933 unsigned long rflags;
9934 int i, r;
9935
9936 vcpu_load(vcpu);
9937
9938 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9939 r = -EBUSY;
9940 if (vcpu->arch.exception.pending)
9941 goto out;
9942 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9943 kvm_queue_exception(vcpu, DB_VECTOR);
9944 else
9945 kvm_queue_exception(vcpu, BP_VECTOR);
9946 }
9947
9948 /*
9949 * Read rflags as long as potentially injected trace flags are still
9950 * filtered out.
9951 */
9952 rflags = kvm_get_rflags(vcpu);
9953
9954 vcpu->guest_debug = dbg->control;
9955 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9956 vcpu->guest_debug = 0;
9957
9958 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9959 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9960 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9961 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9962 } else {
9963 for (i = 0; i < KVM_NR_DB_REGS; i++)
9964 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9965 }
9966 kvm_update_dr7(vcpu);
9967
9968 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9969 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9970 get_segment_base(vcpu, VCPU_SREG_CS);
9971
9972 /*
9973 * Trigger an rflags update that will inject or remove the trace
9974 * flags.
9975 */
9976 kvm_set_rflags(vcpu, rflags);
9977
Olivier Deprez157378f2022-04-04 15:47:50 +02009978 kvm_x86_ops.update_exception_bitmap(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009979
9980 r = 0;
9981
9982out:
9983 vcpu_put(vcpu);
9984 return r;
9985}
9986
9987/*
9988 * Translate a guest virtual address to a guest physical address.
9989 */
9990int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9991 struct kvm_translation *tr)
9992{
9993 unsigned long vaddr = tr->linear_address;
9994 gpa_t gpa;
9995 int idx;
9996
9997 vcpu_load(vcpu);
9998
9999 idx = srcu_read_lock(&vcpu->kvm->srcu);
10000 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
10001 srcu_read_unlock(&vcpu->kvm->srcu, idx);
10002 tr->physical_address = gpa;
10003 tr->valid = gpa != UNMAPPED_GVA;
10004 tr->writeable = 1;
10005 tr->usermode = 0;
10006
10007 vcpu_put(vcpu);
10008 return 0;
10009}
10010
10011int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
10012{
10013 struct fxregs_state *fxsave;
10014
10015 vcpu_load(vcpu);
10016
David Brazdil0f672f62019-12-10 10:32:29 +000010017 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010018 memcpy(fpu->fpr, fxsave->st_space, 128);
10019 fpu->fcw = fxsave->cwd;
10020 fpu->fsw = fxsave->swd;
10021 fpu->ftwx = fxsave->twd;
10022 fpu->last_opcode = fxsave->fop;
10023 fpu->last_ip = fxsave->rip;
10024 fpu->last_dp = fxsave->rdp;
David Brazdil0f672f62019-12-10 10:32:29 +000010025 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010026
10027 vcpu_put(vcpu);
10028 return 0;
10029}
10030
10031int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
10032{
10033 struct fxregs_state *fxsave;
10034
10035 vcpu_load(vcpu);
10036
David Brazdil0f672f62019-12-10 10:32:29 +000010037 fxsave = &vcpu->arch.guest_fpu->state.fxsave;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010038
10039 memcpy(fxsave->st_space, fpu->fpr, 128);
10040 fxsave->cwd = fpu->fcw;
10041 fxsave->swd = fpu->fsw;
10042 fxsave->twd = fpu->ftwx;
10043 fxsave->fop = fpu->last_opcode;
10044 fxsave->rip = fpu->last_ip;
10045 fxsave->rdp = fpu->last_dp;
David Brazdil0f672f62019-12-10 10:32:29 +000010046 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010047
10048 vcpu_put(vcpu);
10049 return 0;
10050}
10051
10052static void store_regs(struct kvm_vcpu *vcpu)
10053{
10054 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
10055
10056 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
10057 __get_regs(vcpu, &vcpu->run->s.regs.regs);
10058
10059 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
10060 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
10061
10062 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
10063 kvm_vcpu_ioctl_x86_get_vcpu_events(
10064 vcpu, &vcpu->run->s.regs.events);
10065}
10066
10067static int sync_regs(struct kvm_vcpu *vcpu)
10068{
10069 if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
10070 return -EINVAL;
10071
10072 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
10073 __set_regs(vcpu, &vcpu->run->s.regs.regs);
10074 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
10075 }
10076 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
10077 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
10078 return -EINVAL;
10079 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
10080 }
10081 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
10082 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
10083 vcpu, &vcpu->run->s.regs.events))
10084 return -EINVAL;
10085 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
10086 }
10087
10088 return 0;
10089}
10090
10091static void fx_init(struct kvm_vcpu *vcpu)
10092{
David Brazdil0f672f62019-12-10 10:32:29 +000010093 fpstate_init(&vcpu->arch.guest_fpu->state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010094 if (boot_cpu_has(X86_FEATURE_XSAVES))
David Brazdil0f672f62019-12-10 10:32:29 +000010095 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010096 host_xcr0 | XSTATE_COMPACTION_ENABLED;
10097
10098 /*
10099 * Ensure guest xcr0 is valid for loading
10100 */
10101 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10102
10103 vcpu->arch.cr0 |= X86_CR0_ET;
10104}
10105
Olivier Deprez157378f2022-04-04 15:47:50 +020010106int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010107{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010108 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
Olivier Deprez157378f2022-04-04 15:47:50 +020010109 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
10110 "guest TSC will not be reliable\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010111
Olivier Deprez157378f2022-04-04 15:47:50 +020010112 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010113}
10114
Olivier Deprez157378f2022-04-04 15:47:50 +020010115int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010116{
Olivier Deprez157378f2022-04-04 15:47:50 +020010117 struct page *page;
10118 int r;
10119
10120 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
10121 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10122 else
10123 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
10124
10125 kvm_set_tsc_khz(vcpu, max_tsc_khz);
10126
10127 r = kvm_mmu_create(vcpu);
10128 if (r < 0)
10129 return r;
10130
10131 if (irqchip_in_kernel(vcpu->kvm)) {
10132 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
10133 if (r < 0)
10134 goto fail_mmu_destroy;
10135 if (kvm_apicv_activated(vcpu->kvm))
10136 vcpu->arch.apicv_active = true;
10137 } else
10138 static_key_slow_inc(&kvm_no_apic_vcpu);
10139
10140 r = -ENOMEM;
10141
10142 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
10143 if (!page)
10144 goto fail_free_lapic;
10145 vcpu->arch.pio_data = page_address(page);
10146
10147 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
10148 GFP_KERNEL_ACCOUNT);
10149 if (!vcpu->arch.mce_banks)
10150 goto fail_free_pio_data;
10151 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
10152
10153 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
10154 GFP_KERNEL_ACCOUNT))
10155 goto fail_free_mce_banks;
10156
10157 if (!alloc_emulate_ctxt(vcpu))
10158 goto free_wbinvd_dirty_mask;
10159
10160 vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
10161 GFP_KERNEL_ACCOUNT);
10162 if (!vcpu->arch.user_fpu) {
10163 pr_err("kvm: failed to allocate userspace's fpu\n");
10164 goto free_emulate_ctxt;
10165 }
10166
10167 vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
10168 GFP_KERNEL_ACCOUNT);
10169 if (!vcpu->arch.guest_fpu) {
10170 pr_err("kvm: failed to allocate vcpu's fpu\n");
10171 goto free_user_fpu;
10172 }
10173 fx_init(vcpu);
10174
10175 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
10176 vcpu->arch.cr3_lm_rsvd_bits = rsvd_bits(cpuid_maxphyaddr(vcpu), 63);
10177
10178 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
10179
10180 kvm_async_pf_hash_reset(vcpu);
10181 kvm_pmu_init(vcpu);
10182
10183 vcpu->arch.pending_external_vector = -1;
10184 vcpu->arch.preempted_in_kernel = false;
10185
10186 kvm_hv_vcpu_init(vcpu);
10187
10188 r = kvm_x86_ops.vcpu_create(vcpu);
10189 if (r)
10190 goto free_guest_fpu;
10191
David Brazdil0f672f62019-12-10 10:32:29 +000010192 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
10193 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010194 kvm_vcpu_mtrr_init(vcpu);
10195 vcpu_load(vcpu);
10196 kvm_vcpu_reset(vcpu, false);
David Brazdil0f672f62019-12-10 10:32:29 +000010197 kvm_init_mmu(vcpu, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010198 vcpu_put(vcpu);
10199 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +020010200
10201free_guest_fpu:
10202 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
10203free_user_fpu:
10204 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10205free_emulate_ctxt:
10206 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10207free_wbinvd_dirty_mask:
10208 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10209fail_free_mce_banks:
10210 kfree(vcpu->arch.mce_banks);
10211fail_free_pio_data:
10212 free_page((unsigned long)vcpu->arch.pio_data);
10213fail_free_lapic:
10214 kvm_free_lapic(vcpu);
10215fail_mmu_destroy:
10216 kvm_mmu_destroy(vcpu);
10217 return r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010218}
10219
10220void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
10221{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010222 struct kvm *kvm = vcpu->kvm;
10223
10224 kvm_hv_vcpu_postcreate(vcpu);
10225
10226 if (mutex_lock_killable(&vcpu->mutex))
10227 return;
10228 vcpu_load(vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +020010229 kvm_synchronize_tsc(vcpu, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010230 vcpu_put(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +000010231
10232 /* poll control enabled by default */
10233 vcpu->arch.msr_kvm_poll_control = 1;
10234
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010235 mutex_unlock(&vcpu->mutex);
10236
Olivier Deprez157378f2022-04-04 15:47:50 +020010237 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
10238 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
10239 KVMCLOCK_SYNC_PERIOD);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010240}
10241
10242void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
10243{
Olivier Deprez157378f2022-04-04 15:47:50 +020010244 struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
10245 int idx;
10246
10247 kvm_release_pfn(cache->pfn, cache->dirty, cache);
10248
10249 kvmclock_reset(vcpu);
10250
10251 kvm_x86_ops.vcpu_free(vcpu);
10252
10253 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
10254 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
10255 kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
10256 kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
10257
10258 kvm_hv_vcpu_uninit(vcpu);
10259 kvm_pmu_destroy(vcpu);
10260 kfree(vcpu->arch.mce_banks);
10261 kvm_free_lapic(vcpu);
10262 idx = srcu_read_lock(&vcpu->kvm->srcu);
10263 kvm_mmu_destroy(vcpu);
10264 srcu_read_unlock(&vcpu->kvm->srcu, idx);
10265 free_page((unsigned long)vcpu->arch.pio_data);
10266 kvfree(vcpu->arch.cpuid_entries);
10267 if (!lapic_in_kernel(vcpu))
10268 static_key_slow_dec(&kvm_no_apic_vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010269}
10270
10271void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
10272{
10273 kvm_lapic_reset(vcpu, init_event);
10274
10275 vcpu->arch.hflags = 0;
10276
10277 vcpu->arch.smi_pending = 0;
10278 vcpu->arch.smi_count = 0;
10279 atomic_set(&vcpu->arch.nmi_queued, 0);
10280 vcpu->arch.nmi_pending = 0;
10281 vcpu->arch.nmi_injected = false;
10282 kvm_clear_interrupt_queue(vcpu);
10283 kvm_clear_exception_queue(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010284
10285 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
10286 kvm_update_dr0123(vcpu);
10287 vcpu->arch.dr6 = DR6_INIT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010288 vcpu->arch.dr7 = DR7_FIXED_1;
10289 kvm_update_dr7(vcpu);
10290
10291 vcpu->arch.cr2 = 0;
10292
10293 kvm_make_request(KVM_REQ_EVENT, vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +020010294 vcpu->arch.apf.msr_en_val = 0;
10295 vcpu->arch.apf.msr_int_val = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010296 vcpu->arch.st.msr_val = 0;
10297
10298 kvmclock_reset(vcpu);
10299
10300 kvm_clear_async_pf_completion_queue(vcpu);
10301 kvm_async_pf_hash_reset(vcpu);
10302 vcpu->arch.apf.halted = false;
10303
10304 if (kvm_mpx_supported()) {
10305 void *mpx_state_buffer;
10306
10307 /*
10308 * To avoid have the INIT path from kvm_apic_has_events() that be
10309 * called with loaded FPU and does not let userspace fix the state.
10310 */
10311 if (init_event)
10312 kvm_put_guest_fpu(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +000010313 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10314 XFEATURE_BNDREGS);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010315 if (mpx_state_buffer)
10316 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
David Brazdil0f672f62019-12-10 10:32:29 +000010317 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
10318 XFEATURE_BNDCSR);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010319 if (mpx_state_buffer)
10320 memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
10321 if (init_event)
10322 kvm_load_guest_fpu(vcpu);
10323 }
10324
10325 if (!init_event) {
10326 kvm_pmu_reset(vcpu);
10327 vcpu->arch.smbase = 0x30000;
10328
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010329 vcpu->arch.msr_misc_features_enables = 0;
10330
10331 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
10332 }
10333
10334 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
10335 vcpu->arch.regs_avail = ~0;
10336 vcpu->arch.regs_dirty = ~0;
10337
10338 vcpu->arch.ia32_xss = 0;
10339
Olivier Deprez157378f2022-04-04 15:47:50 +020010340 kvm_x86_ops.vcpu_reset(vcpu, init_event);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010341}
10342
10343void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
10344{
10345 struct kvm_segment cs;
10346
10347 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
10348 cs.selector = vector << 8;
10349 cs.base = vector << 12;
10350 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
10351 kvm_rip_write(vcpu, 0);
10352}
10353
10354int kvm_arch_hardware_enable(void)
10355{
10356 struct kvm *kvm;
10357 struct kvm_vcpu *vcpu;
10358 int i;
10359 int ret;
10360 u64 local_tsc;
10361 u64 max_tsc = 0;
10362 bool stable, backwards_tsc = false;
10363
Olivier Deprez157378f2022-04-04 15:47:50 +020010364 kvm_user_return_msr_cpu_online();
10365 ret = kvm_x86_ops.hardware_enable();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010366 if (ret != 0)
10367 return ret;
10368
10369 local_tsc = rdtsc();
10370 stable = !kvm_check_tsc_unstable();
10371 list_for_each_entry(kvm, &vm_list, vm_list) {
10372 kvm_for_each_vcpu(i, vcpu, kvm) {
10373 if (!stable && vcpu->cpu == smp_processor_id())
10374 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10375 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
10376 backwards_tsc = true;
10377 if (vcpu->arch.last_host_tsc > max_tsc)
10378 max_tsc = vcpu->arch.last_host_tsc;
10379 }
10380 }
10381 }
10382
10383 /*
10384 * Sometimes, even reliable TSCs go backwards. This happens on
10385 * platforms that reset TSC during suspend or hibernate actions, but
10386 * maintain synchronization. We must compensate. Fortunately, we can
10387 * detect that condition here, which happens early in CPU bringup,
10388 * before any KVM threads can be running. Unfortunately, we can't
10389 * bring the TSCs fully up to date with real time, as we aren't yet far
10390 * enough into CPU bringup that we know how much real time has actually
David Brazdil0f672f62019-12-10 10:32:29 +000010391 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010392 * variables that haven't been updated yet.
10393 *
10394 * So we simply find the maximum observed TSC above, then record the
10395 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
10396 * the adjustment will be applied. Note that we accumulate
10397 * adjustments, in case multiple suspend cycles happen before some VCPU
10398 * gets a chance to run again. In the event that no KVM threads get a
10399 * chance to run, we will miss the entire elapsed period, as we'll have
10400 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
10401 * loose cycle time. This isn't too big a deal, since the loss will be
10402 * uniform across all VCPUs (not to mention the scenario is extremely
10403 * unlikely). It is possible that a second hibernate recovery happens
10404 * much faster than a first, causing the observed TSC here to be
10405 * smaller; this would require additional padding adjustment, which is
10406 * why we set last_host_tsc to the local tsc observed here.
10407 *
10408 * N.B. - this code below runs only on platforms with reliable TSC,
10409 * as that is the only way backwards_tsc is set above. Also note
10410 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
10411 * have the same delta_cyc adjustment applied if backwards_tsc
10412 * is detected. Note further, this adjustment is only done once,
10413 * as we reset last_host_tsc on all VCPUs to stop this from being
10414 * called multiple times (one for each physical CPU bringup).
10415 *
10416 * Platforms with unreliable TSCs don't have to deal with this, they
10417 * will be compensated by the logic in vcpu_load, which sets the TSC to
10418 * catchup mode. This will catchup all VCPUs to real time, but cannot
10419 * guarantee that they stay in perfect synchronization.
10420 */
10421 if (backwards_tsc) {
10422 u64 delta_cyc = max_tsc - local_tsc;
10423 list_for_each_entry(kvm, &vm_list, vm_list) {
10424 kvm->arch.backwards_tsc_observed = true;
10425 kvm_for_each_vcpu(i, vcpu, kvm) {
10426 vcpu->arch.tsc_offset_adjustment += delta_cyc;
10427 vcpu->arch.last_host_tsc = local_tsc;
10428 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
10429 }
10430
10431 /*
10432 * We have to disable TSC offset matching.. if you were
10433 * booting a VM while issuing an S4 host suspend....
10434 * you may have some problem. Solving this issue is
10435 * left as an exercise to the reader.
10436 */
10437 kvm->arch.last_tsc_nsec = 0;
10438 kvm->arch.last_tsc_write = 0;
10439 }
10440
10441 }
10442 return 0;
10443}
10444
10445void kvm_arch_hardware_disable(void)
10446{
Olivier Deprez157378f2022-04-04 15:47:50 +020010447 kvm_x86_ops.hardware_disable();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010448 drop_user_return_notifiers();
10449}
10450
Olivier Deprez157378f2022-04-04 15:47:50 +020010451int kvm_arch_hardware_setup(void *opaque)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010452{
Olivier Deprez157378f2022-04-04 15:47:50 +020010453 struct kvm_x86_init_ops *ops = opaque;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010454 int r;
10455
Olivier Deprez157378f2022-04-04 15:47:50 +020010456 rdmsrl_safe(MSR_EFER, &host_efer);
10457
10458 if (boot_cpu_has(X86_FEATURE_XSAVES))
10459 rdmsrl(MSR_IA32_XSS, host_xss);
10460
10461 r = ops->hardware_setup();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010462 if (r != 0)
10463 return r;
10464
Olivier Deprez157378f2022-04-04 15:47:50 +020010465 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
10466
10467 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10468 supported_xss = 0;
10469
10470#define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
10471 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
10472#undef __kvm_cpu_cap_has
Olivier Deprez0e641232021-09-23 10:07:05 +020010473
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010474 if (kvm_has_tsc_control) {
10475 /*
10476 * Make sure the user can only configure tsc_khz values that
10477 * fit into a signed integer.
10478 * A min value is not calculated because it will always
10479 * be 1 on all machines.
10480 */
10481 u64 max = min(0x7fffffffULL,
10482 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
10483 kvm_max_guest_tsc_khz = max;
10484
10485 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
10486 }
10487
10488 kvm_init_msr_list();
10489 return 0;
10490}
10491
10492void kvm_arch_hardware_unsetup(void)
10493{
Olivier Deprez157378f2022-04-04 15:47:50 +020010494 kvm_x86_ops.hardware_unsetup();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010495}
10496
Olivier Deprez157378f2022-04-04 15:47:50 +020010497int kvm_arch_check_processor_compat(void *opaque)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010498{
Olivier Deprez157378f2022-04-04 15:47:50 +020010499 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
10500 struct kvm_x86_init_ops *ops = opaque;
10501
10502 WARN_ON(!irqs_disabled());
10503
10504 if (__cr4_reserved_bits(cpu_has, c) !=
10505 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
10506 return -EIO;
10507
10508 return ops->check_processor_compatibility();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010509}
10510
10511bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
10512{
10513 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
10514}
10515EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
10516
10517bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
10518{
10519 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
10520}
10521
10522struct static_key kvm_no_apic_vcpu __read_mostly;
10523EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
10524
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010525void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
10526{
Olivier Deprez157378f2022-04-04 15:47:50 +020010527 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
10528
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010529 vcpu->arch.l1tf_flush_l1d = true;
Olivier Deprez157378f2022-04-04 15:47:50 +020010530 if (pmu->version && unlikely(pmu->event_count)) {
10531 pmu->need_cleanup = true;
10532 kvm_make_request(KVM_REQ_PMU, vcpu);
10533 }
10534 kvm_x86_ops.sched_in(vcpu, cpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010535}
10536
Olivier Deprez157378f2022-04-04 15:47:50 +020010537void kvm_arch_free_vm(struct kvm *kvm)
10538{
10539 kfree(kvm->arch.hyperv.hv_pa_pg);
10540 vfree(kvm);
10541}
10542
10543
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010544int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
10545{
Olivier Deprez157378f2022-04-04 15:47:50 +020010546 int ret;
10547
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010548 if (type)
10549 return -EINVAL;
10550
Olivier Deprez157378f2022-04-04 15:47:50 +020010551 ret = kvm_page_track_init(kvm);
10552 if (ret)
10553 return ret;
10554
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010555 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
10556 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
10557 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
David Brazdil0f672f62019-12-10 10:32:29 +000010558 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010559 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
10560 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
10561
10562 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
10563 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
10564 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
10565 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
10566 &kvm->arch.irq_sources_bitmap);
10567
10568 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
10569 mutex_init(&kvm->arch.apic_map_lock);
10570 spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
10571
Olivier Deprez157378f2022-04-04 15:47:50 +020010572 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010573 pvclock_update_vm_gtod_copy(kvm);
10574
10575 kvm->arch.guest_can_read_msr_platform_info = true;
10576
10577 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
10578 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
10579
10580 kvm_hv_init_vm(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010581 kvm_mmu_init_vm(kvm);
10582
Olivier Deprez157378f2022-04-04 15:47:50 +020010583 return kvm_x86_ops.vm_init(kvm);
David Brazdil0f672f62019-12-10 10:32:29 +000010584}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010585
David Brazdil0f672f62019-12-10 10:32:29 +000010586int kvm_arch_post_init_vm(struct kvm *kvm)
10587{
10588 return kvm_mmu_post_init_vm(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010589}
10590
10591static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
10592{
10593 vcpu_load(vcpu);
10594 kvm_mmu_unload(vcpu);
10595 vcpu_put(vcpu);
10596}
10597
10598static void kvm_free_vcpus(struct kvm *kvm)
10599{
10600 unsigned int i;
10601 struct kvm_vcpu *vcpu;
10602
10603 /*
10604 * Unpin any mmu pages first.
10605 */
10606 kvm_for_each_vcpu(i, vcpu, kvm) {
10607 kvm_clear_async_pf_completion_queue(vcpu);
10608 kvm_unload_vcpu_mmu(vcpu);
10609 }
10610 kvm_for_each_vcpu(i, vcpu, kvm)
Olivier Deprez157378f2022-04-04 15:47:50 +020010611 kvm_vcpu_destroy(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010612
10613 mutex_lock(&kvm->lock);
10614 for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
10615 kvm->vcpus[i] = NULL;
10616
10617 atomic_set(&kvm->online_vcpus, 0);
10618 mutex_unlock(&kvm->lock);
10619}
10620
10621void kvm_arch_sync_events(struct kvm *kvm)
10622{
10623 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
10624 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
10625 kvm_free_pit(kvm);
10626}
10627
10628int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
10629{
10630 int i, r;
Olivier Deprez157378f2022-04-04 15:47:50 +020010631 unsigned long hva, old_npages;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010632 struct kvm_memslots *slots = kvm_memslots(kvm);
Olivier Deprez157378f2022-04-04 15:47:50 +020010633 struct kvm_memory_slot *slot;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010634
10635 /* Called with kvm->slots_lock held. */
10636 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
10637 return -EINVAL;
10638
10639 slot = id_to_memslot(slots, id);
10640 if (size) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010641 if (slot && slot->npages)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010642 return -EEXIST;
10643
10644 /*
10645 * MAP_SHARED to prevent internal slot pages from being moved
10646 * by fork()/COW.
10647 */
10648 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
10649 MAP_SHARED | MAP_ANONYMOUS, 0);
10650 if (IS_ERR((void *)hva))
10651 return PTR_ERR((void *)hva);
10652 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +020010653 if (!slot || !slot->npages)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010654 return 0;
10655
Olivier Deprez157378f2022-04-04 15:47:50 +020010656 old_npages = slot->npages;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010657 hva = 0;
10658 }
10659
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010660 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
10661 struct kvm_userspace_memory_region m;
10662
10663 m.slot = id | (i << 16);
10664 m.flags = 0;
10665 m.guest_phys_addr = gpa;
10666 m.userspace_addr = hva;
10667 m.memory_size = size;
10668 r = __kvm_set_memory_region(kvm, &m);
10669 if (r < 0)
10670 return r;
10671 }
10672
10673 if (!size)
Olivier Deprez157378f2022-04-04 15:47:50 +020010674 vm_munmap(hva, old_npages * PAGE_SIZE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010675
10676 return 0;
10677}
10678EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10679
David Brazdil0f672f62019-12-10 10:32:29 +000010680void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10681{
10682 kvm_mmu_pre_destroy_vm(kvm);
10683}
10684
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010685void kvm_arch_destroy_vm(struct kvm *kvm)
10686{
10687 if (current->mm == kvm->mm) {
10688 /*
10689 * Free memory regions allocated on behalf of userspace,
10690 * unless the the memory map has changed due to process exit
10691 * or fd copying.
10692 */
Olivier Deprez157378f2022-04-04 15:47:50 +020010693 mutex_lock(&kvm->slots_lock);
10694 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10695 0, 0);
10696 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10697 0, 0);
10698 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10699 mutex_unlock(&kvm->slots_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010700 }
Olivier Deprez157378f2022-04-04 15:47:50 +020010701 if (kvm_x86_ops.vm_destroy)
10702 kvm_x86_ops.vm_destroy(kvm);
10703 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010704 kvm_pic_destroy(kvm);
10705 kvm_ioapic_destroy(kvm);
10706 kvm_free_vcpus(kvm);
10707 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
David Brazdil0f672f62019-12-10 10:32:29 +000010708 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010709 kvm_mmu_uninit_vm(kvm);
10710 kvm_page_track_cleanup(kvm);
10711 kvm_hv_destroy_vm(kvm);
10712}
10713
Olivier Deprez157378f2022-04-04 15:47:50 +020010714void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010715{
10716 int i;
10717
10718 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010719 kvfree(slot->arch.rmap[i]);
10720 slot->arch.rmap[i] = NULL;
10721
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010722 if (i == 0)
10723 continue;
10724
Olivier Deprez157378f2022-04-04 15:47:50 +020010725 kvfree(slot->arch.lpage_info[i - 1]);
10726 slot->arch.lpage_info[i - 1] = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010727 }
10728
Olivier Deprez157378f2022-04-04 15:47:50 +020010729 kvm_page_track_free_memslot(slot);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010730}
10731
Olivier Deprez157378f2022-04-04 15:47:50 +020010732static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10733 unsigned long npages)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010734{
10735 int i;
10736
Olivier Deprez0e641232021-09-23 10:07:05 +020010737 /*
10738 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
10739 * old arrays will be freed by __kvm_set_memory_region() if installing
10740 * the new memslot is successful.
10741 */
10742 memset(&slot->arch, 0, sizeof(slot->arch));
10743
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010744 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10745 struct kvm_lpage_info *linfo;
10746 unsigned long ugfn;
10747 int lpages;
10748 int level = i + 1;
10749
10750 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10751 slot->base_gfn, level) + 1;
10752
10753 slot->arch.rmap[i] =
10754 kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
David Brazdil0f672f62019-12-10 10:32:29 +000010755 GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010756 if (!slot->arch.rmap[i])
10757 goto out_free;
10758 if (i == 0)
10759 continue;
10760
David Brazdil0f672f62019-12-10 10:32:29 +000010761 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010762 if (!linfo)
10763 goto out_free;
10764
10765 slot->arch.lpage_info[i - 1] = linfo;
10766
10767 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10768 linfo[0].disallow_lpage = 1;
10769 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10770 linfo[lpages - 1].disallow_lpage = 1;
10771 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10772 /*
10773 * If the gfn and userspace address are not aligned wrt each
Olivier Deprez157378f2022-04-04 15:47:50 +020010774 * other, disable large page support for this slot.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010775 */
Olivier Deprez157378f2022-04-04 15:47:50 +020010776 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010777 unsigned long j;
10778
10779 for (j = 0; j < lpages; ++j)
10780 linfo[j].disallow_lpage = 1;
10781 }
10782 }
10783
10784 if (kvm_page_track_create_memslot(slot, npages))
10785 goto out_free;
10786
10787 return 0;
10788
10789out_free:
10790 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10791 kvfree(slot->arch.rmap[i]);
10792 slot->arch.rmap[i] = NULL;
10793 if (i == 0)
10794 continue;
10795
10796 kvfree(slot->arch.lpage_info[i - 1]);
10797 slot->arch.lpage_info[i - 1] = NULL;
10798 }
10799 return -ENOMEM;
10800}
10801
David Brazdil0f672f62019-12-10 10:32:29 +000010802void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010803{
Olivier Deprez0e641232021-09-23 10:07:05 +020010804 struct kvm_vcpu *vcpu;
10805 int i;
10806
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010807 /*
10808 * memslots->generation has been incremented.
10809 * mmio generation may have reached its maximum value.
10810 */
David Brazdil0f672f62019-12-10 10:32:29 +000010811 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
Olivier Deprez0e641232021-09-23 10:07:05 +020010812
10813 /* Force re-initialization of steal_time cache */
10814 kvm_for_each_vcpu(i, vcpu, kvm)
10815 kvm_vcpu_kick(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010816}
10817
10818int kvm_arch_prepare_memory_region(struct kvm *kvm,
10819 struct kvm_memory_slot *memslot,
10820 const struct kvm_userspace_memory_region *mem,
10821 enum kvm_mr_change change)
10822{
Olivier Deprez157378f2022-04-04 15:47:50 +020010823 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10824 return kvm_alloc_memslot_metadata(memslot,
10825 mem->memory_size >> PAGE_SHIFT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010826 return 0;
10827}
10828
10829static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
Olivier Deprez157378f2022-04-04 15:47:50 +020010830 struct kvm_memory_slot *old,
10831 struct kvm_memory_slot *new,
10832 enum kvm_mr_change change)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010833{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010834 /*
Olivier Deprez157378f2022-04-04 15:47:50 +020010835 * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10836 * See comments below.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010837 */
Olivier Deprez157378f2022-04-04 15:47:50 +020010838 if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10839 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010840
10841 /*
10842 * Dirty logging tracks sptes in 4k granularity, meaning that large
10843 * sptes have to be split. If live migration is successful, the guest
10844 * in the source machine will be destroyed and large sptes will be
10845 * created in the destination. However, if the guest continues to run
10846 * in the source machine (for example if live migration fails), small
10847 * sptes will remain around and cause bad performance.
10848 *
10849 * Scan sptes if dirty logging has been stopped, dropping those
10850 * which can be collapsed into a single large-page spte. Later
10851 * page faults will create the large-page sptes.
David Brazdil0f672f62019-12-10 10:32:29 +000010852 *
10853 * There is no need to do this in any of the following cases:
Olivier Deprez157378f2022-04-04 15:47:50 +020010854 * CREATE: No dirty mappings will already exist.
10855 * MOVE/DELETE: The old mappings will already have been cleaned up by
David Brazdil0f672f62019-12-10 10:32:29 +000010856 * kvm_arch_flush_shadow_memslot()
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010857 */
Olivier Deprez157378f2022-04-04 15:47:50 +020010858 if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10859 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010860 kvm_mmu_zap_collapsible_sptes(kvm, new);
10861
10862 /*
Olivier Deprez157378f2022-04-04 15:47:50 +020010863 * Enable or disable dirty logging for the slot.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010864 *
Olivier Deprez157378f2022-04-04 15:47:50 +020010865 * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10866 * slot have been zapped so no dirty logging updates are needed for
10867 * the old slot.
10868 * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10869 * any mappings that might be created in it will consume the
10870 * properties of the new slot and do not need to be updated here.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010871 *
Olivier Deprez157378f2022-04-04 15:47:50 +020010872 * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10873 * called to enable/disable dirty logging.
10874 *
10875 * When disabling dirty logging with PML enabled, the D-bit is set
10876 * for sptes in the slot in order to prevent unnecessary GPA
10877 * logging in the PML buffer (and potential PML buffer full VMEXIT).
10878 * This guarantees leaving PML enabled for the guest's lifetime
10879 * won't have any additional overhead from PML when the guest is
10880 * running with dirty logging disabled.
10881 *
10882 * When enabling dirty logging, large sptes are write-protected
10883 * so they can be split on first write. New large sptes cannot
10884 * be created for this slot until the end of the logging.
10885 * See the comments in fast_page_fault().
10886 * For small sptes, nothing is done if the dirty log is in the
10887 * initial-all-set state. Otherwise, depending on whether pml
10888 * is enabled the D-bit or the W-bit will be cleared.
10889 */
10890 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10891 if (kvm_x86_ops.slot_enable_log_dirty) {
10892 kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10893 } else {
10894 int level =
10895 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10896 PG_LEVEL_2M : PG_LEVEL_4K;
10897
10898 /*
10899 * If we're with initial-all-set, we don't need
10900 * to write protect any small page because
10901 * they're reported as dirty already. However
10902 * we still need to write-protect huge pages
10903 * so that the page split can happen lazily on
10904 * the first write to the huge page.
10905 */
10906 kvm_mmu_slot_remove_write_access(kvm, new, level);
10907 }
10908 } else {
10909 if (kvm_x86_ops.slot_disable_log_dirty)
10910 kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10911 }
10912}
10913
10914void kvm_arch_commit_memory_region(struct kvm *kvm,
10915 const struct kvm_userspace_memory_region *mem,
10916 struct kvm_memory_slot *old,
10917 const struct kvm_memory_slot *new,
10918 enum kvm_mr_change change)
10919{
10920 if (!kvm->arch.n_requested_mmu_pages)
10921 kvm_mmu_change_mmu_pages(kvm,
10922 kvm_mmu_calculate_default_mmu_pages(kvm));
10923
10924 /*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010925 * FIXME: const-ify all uses of struct kvm_memory_slot.
10926 */
Olivier Deprez157378f2022-04-04 15:47:50 +020010927 kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10928
10929 /* Free the arrays associated with the old memslot. */
10930 if (change == KVM_MR_MOVE)
10931 kvm_arch_free_memslot(kvm, old);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010932}
10933
10934void kvm_arch_flush_shadow_all(struct kvm *kvm)
10935{
David Brazdil0f672f62019-12-10 10:32:29 +000010936 kvm_mmu_zap_all(kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010937}
10938
10939void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10940 struct kvm_memory_slot *slot)
10941{
10942 kvm_page_track_flush_slot(kvm, slot);
10943}
10944
10945static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10946{
10947 return (is_guest_mode(vcpu) &&
Olivier Deprez157378f2022-04-04 15:47:50 +020010948 kvm_x86_ops.guest_apic_has_interrupt &&
10949 kvm_x86_ops.guest_apic_has_interrupt(vcpu));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010950}
10951
10952static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10953{
10954 if (!list_empty_careful(&vcpu->async_pf.done))
10955 return true;
10956
10957 if (kvm_apic_has_events(vcpu))
10958 return true;
10959
10960 if (vcpu->arch.pv.pv_unhalted)
10961 return true;
10962
10963 if (vcpu->arch.exception.pending)
10964 return true;
10965
10966 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10967 (vcpu->arch.nmi_pending &&
Olivier Deprez157378f2022-04-04 15:47:50 +020010968 kvm_x86_ops.nmi_allowed(vcpu, false)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010969 return true;
10970
10971 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
Olivier Deprez157378f2022-04-04 15:47:50 +020010972 (vcpu->arch.smi_pending &&
10973 kvm_x86_ops.smi_allowed(vcpu, false)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010974 return true;
10975
10976 if (kvm_arch_interrupt_allowed(vcpu) &&
10977 (kvm_cpu_has_interrupt(vcpu) ||
10978 kvm_guest_apic_has_interrupt(vcpu)))
10979 return true;
10980
10981 if (kvm_hv_has_stimer_pending(vcpu))
10982 return true;
10983
Olivier Deprez157378f2022-04-04 15:47:50 +020010984 if (is_guest_mode(vcpu) &&
10985 kvm_x86_ops.nested_ops->hv_timer_pending &&
10986 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10987 return true;
10988
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000010989 return false;
10990}
10991
10992int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10993{
10994 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10995}
10996
David Brazdil0f672f62019-12-10 10:32:29 +000010997bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10998{
10999 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11000 return true;
11001
11002 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11003 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11004 kvm_test_request(KVM_REQ_EVENT, vcpu))
11005 return true;
11006
Olivier Deprez157378f2022-04-04 15:47:50 +020011007 if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
David Brazdil0f672f62019-12-10 10:32:29 +000011008 return true;
11009
11010 return false;
11011}
11012
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011013bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
11014{
11015 return vcpu->arch.preempted_in_kernel;
11016}
11017
11018int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
11019{
11020 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
11021}
11022
11023int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
11024{
Olivier Deprez157378f2022-04-04 15:47:50 +020011025 return kvm_x86_ops.interrupt_allowed(vcpu, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011026}
11027
11028unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
11029{
11030 if (is_64_bit_mode(vcpu))
11031 return kvm_rip_read(vcpu);
11032 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
11033 kvm_rip_read(vcpu));
11034}
11035EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
11036
11037bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
11038{
11039 return kvm_get_linear_rip(vcpu) == linear_rip;
11040}
11041EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
11042
11043unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
11044{
11045 unsigned long rflags;
11046
Olivier Deprez157378f2022-04-04 15:47:50 +020011047 rflags = kvm_x86_ops.get_rflags(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011048 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11049 rflags &= ~X86_EFLAGS_TF;
11050 return rflags;
11051}
11052EXPORT_SYMBOL_GPL(kvm_get_rflags);
11053
11054static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11055{
11056 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
11057 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
11058 rflags |= X86_EFLAGS_TF;
Olivier Deprez157378f2022-04-04 15:47:50 +020011059 kvm_x86_ops.set_rflags(vcpu, rflags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011060}
11061
11062void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
11063{
11064 __kvm_set_rflags(vcpu, rflags);
11065 kvm_make_request(KVM_REQ_EVENT, vcpu);
11066}
11067EXPORT_SYMBOL_GPL(kvm_set_rflags);
11068
11069void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
11070{
11071 int r;
11072
David Brazdil0f672f62019-12-10 10:32:29 +000011073 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011074 work->wakeup_all)
11075 return;
11076
11077 r = kvm_mmu_reload(vcpu);
11078 if (unlikely(r))
11079 return;
11080
David Brazdil0f672f62019-12-10 10:32:29 +000011081 if (!vcpu->arch.mmu->direct_map &&
Olivier Deprez157378f2022-04-04 15:47:50 +020011082 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011083 return;
11084
Olivier Deprez157378f2022-04-04 15:47:50 +020011085 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011086}
11087
11088static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
11089{
Olivier Deprez157378f2022-04-04 15:47:50 +020011090 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
11091
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011092 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
11093}
11094
11095static inline u32 kvm_async_pf_next_probe(u32 key)
11096{
Olivier Deprez157378f2022-04-04 15:47:50 +020011097 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011098}
11099
11100static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11101{
11102 u32 key = kvm_async_pf_hash_fn(gfn);
11103
11104 while (vcpu->arch.apf.gfns[key] != ~0)
11105 key = kvm_async_pf_next_probe(key);
11106
11107 vcpu->arch.apf.gfns[key] = gfn;
11108}
11109
11110static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
11111{
11112 int i;
11113 u32 key = kvm_async_pf_hash_fn(gfn);
11114
Olivier Deprez157378f2022-04-04 15:47:50 +020011115 for (i = 0; i < ASYNC_PF_PER_VCPU &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011116 (vcpu->arch.apf.gfns[key] != gfn &&
11117 vcpu->arch.apf.gfns[key] != ~0); i++)
11118 key = kvm_async_pf_next_probe(key);
11119
11120 return key;
11121}
11122
11123bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11124{
11125 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
11126}
11127
11128static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
11129{
11130 u32 i, j, k;
11131
11132 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
Olivier Deprez157378f2022-04-04 15:47:50 +020011133
11134 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
11135 return;
11136
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011137 while (true) {
11138 vcpu->arch.apf.gfns[i] = ~0;
11139 do {
11140 j = kvm_async_pf_next_probe(j);
11141 if (vcpu->arch.apf.gfns[j] == ~0)
11142 return;
11143 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
11144 /*
11145 * k lies cyclically in ]i,j]
11146 * | i.k.j |
11147 * |....j i.k.| or |.k..j i...|
11148 */
11149 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
11150 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
11151 i = j;
11152 }
11153}
11154
Olivier Deprez157378f2022-04-04 15:47:50 +020011155static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011156{
Olivier Deprez157378f2022-04-04 15:47:50 +020011157 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011158
Olivier Deprez157378f2022-04-04 15:47:50 +020011159 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
11160 sizeof(reason));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011161}
11162
Olivier Deprez157378f2022-04-04 15:47:50 +020011163static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011164{
Olivier Deprez157378f2022-04-04 15:47:50 +020011165 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011166
Olivier Deprez157378f2022-04-04 15:47:50 +020011167 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11168 &token, offset, sizeof(token));
11169}
11170
11171static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
11172{
11173 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
11174 u32 val;
11175
11176 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
11177 &val, offset, sizeof(val)))
11178 return false;
11179
11180 return !val;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011181}
11182
David Brazdil0f672f62019-12-10 10:32:29 +000011183static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
11184{
11185 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
11186 return false;
11187
Olivier Deprez157378f2022-04-04 15:47:50 +020011188 if (!kvm_pv_async_pf_enabled(vcpu) ||
11189 (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
David Brazdil0f672f62019-12-10 10:32:29 +000011190 return false;
11191
11192 return true;
11193}
11194
11195bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
11196{
11197 if (unlikely(!lapic_in_kernel(vcpu) ||
11198 kvm_event_needs_reinjection(vcpu) ||
11199 vcpu->arch.exception.pending))
11200 return false;
11201
11202 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
11203 return false;
11204
11205 /*
11206 * If interrupts are off we cannot even use an artificial
11207 * halt state.
11208 */
Olivier Deprez157378f2022-04-04 15:47:50 +020011209 return kvm_arch_interrupt_allowed(vcpu);
David Brazdil0f672f62019-12-10 10:32:29 +000011210}
11211
Olivier Deprez157378f2022-04-04 15:47:50 +020011212bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011213 struct kvm_async_pf *work)
11214{
11215 struct x86_exception fault;
11216
Olivier Deprez0e641232021-09-23 10:07:05 +020011217 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011218 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
11219
David Brazdil0f672f62019-12-10 10:32:29 +000011220 if (kvm_can_deliver_async_pf(vcpu) &&
Olivier Deprez157378f2022-04-04 15:47:50 +020011221 !apf_put_user_notpresent(vcpu)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011222 fault.vector = PF_VECTOR;
11223 fault.error_code_valid = true;
11224 fault.error_code = 0;
11225 fault.nested_page_fault = false;
11226 fault.address = work->arch.token;
11227 fault.async_page_fault = true;
11228 kvm_inject_page_fault(vcpu, &fault);
Olivier Deprez157378f2022-04-04 15:47:50 +020011229 return true;
David Brazdil0f672f62019-12-10 10:32:29 +000011230 } else {
11231 /*
11232 * It is not possible to deliver a paravirtualized asynchronous
11233 * page fault, but putting the guest in an artificial halt state
11234 * can be beneficial nevertheless: if an interrupt arrives, we
11235 * can deliver it timely and perhaps the guest will schedule
11236 * another process. When the instruction that triggered a page
11237 * fault is retried, hopefully the page will be ready in the host.
11238 */
11239 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
Olivier Deprez157378f2022-04-04 15:47:50 +020011240 return false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011241 }
11242}
11243
11244void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
11245 struct kvm_async_pf *work)
11246{
Olivier Deprez157378f2022-04-04 15:47:50 +020011247 struct kvm_lapic_irq irq = {
11248 .delivery_mode = APIC_DM_FIXED,
11249 .vector = vcpu->arch.apf.vec
11250 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011251
11252 if (work->wakeup_all)
11253 work->arch.token = ~0; /* broadcast wakeup */
11254 else
11255 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
Olivier Deprez0e641232021-09-23 10:07:05 +020011256 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011257
Olivier Deprez157378f2022-04-04 15:47:50 +020011258 if ((work->wakeup_all || work->notpresent_injected) &&
11259 kvm_pv_async_pf_enabled(vcpu) &&
11260 !apf_put_user_ready(vcpu, work->arch.token)) {
11261 vcpu->arch.apf.pageready_pending = true;
11262 kvm_apic_set_irq(vcpu, &irq, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011263 }
Olivier Deprez157378f2022-04-04 15:47:50 +020011264
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011265 vcpu->arch.apf.halted = false;
11266 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11267}
11268
Olivier Deprez157378f2022-04-04 15:47:50 +020011269void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011270{
Olivier Deprez157378f2022-04-04 15:47:50 +020011271 kvm_make_request(KVM_REQ_APF_READY, vcpu);
11272 if (!vcpu->arch.apf.pageready_pending)
11273 kvm_vcpu_kick(vcpu);
11274}
11275
11276bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
11277{
11278 if (!kvm_pv_async_pf_enabled(vcpu))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011279 return true;
11280 else
Olivier Deprez92d4c212022-12-06 15:05:30 +010011281 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011282}
11283
11284void kvm_arch_start_assignment(struct kvm *kvm)
11285{
11286 atomic_inc(&kvm->arch.assigned_device_count);
11287}
11288EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
11289
11290void kvm_arch_end_assignment(struct kvm *kvm)
11291{
11292 atomic_dec(&kvm->arch.assigned_device_count);
11293}
11294EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
11295
Olivier Deprez92d4c212022-12-06 15:05:30 +010011296bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011297{
Olivier Deprez92d4c212022-12-06 15:05:30 +010011298 return arch_atomic_read(&kvm->arch.assigned_device_count);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011299}
11300EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
11301
11302void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
11303{
11304 atomic_inc(&kvm->arch.noncoherent_dma_count);
11305}
11306EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
11307
11308void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
11309{
11310 atomic_dec(&kvm->arch.noncoherent_dma_count);
11311}
11312EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
11313
11314bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
11315{
11316 return atomic_read(&kvm->arch.noncoherent_dma_count);
11317}
11318EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
11319
11320bool kvm_arch_has_irq_bypass(void)
11321{
David Brazdil0f672f62019-12-10 10:32:29 +000011322 return true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011323}
11324
11325int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
11326 struct irq_bypass_producer *prod)
11327{
11328 struct kvm_kernel_irqfd *irqfd =
11329 container_of(cons, struct kvm_kernel_irqfd, consumer);
Olivier Deprez157378f2022-04-04 15:47:50 +020011330 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011331
11332 irqfd->producer = prod;
Olivier Deprez157378f2022-04-04 15:47:50 +020011333 kvm_arch_start_assignment(irqfd->kvm);
11334 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm,
11335 prod->irq, irqfd->gsi, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011336
Olivier Deprez157378f2022-04-04 15:47:50 +020011337 if (ret)
11338 kvm_arch_end_assignment(irqfd->kvm);
11339
11340 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011341}
11342
11343void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
11344 struct irq_bypass_producer *prod)
11345{
11346 int ret;
11347 struct kvm_kernel_irqfd *irqfd =
11348 container_of(cons, struct kvm_kernel_irqfd, consumer);
11349
11350 WARN_ON(irqfd->producer != prod);
11351 irqfd->producer = NULL;
11352
11353 /*
11354 * When producer of consumer is unregistered, we change back to
11355 * remapped mode, so we can re-use the current implementation
11356 * when the irq is masked/disabled or the consumer side (KVM
11357 * int this case doesn't want to receive the interrupts.
11358 */
Olivier Deprez157378f2022-04-04 15:47:50 +020011359 ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011360 if (ret)
11361 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
11362 " fails: %d\n", irqfd->consumer.token, ret);
Olivier Deprez157378f2022-04-04 15:47:50 +020011363
11364 kvm_arch_end_assignment(irqfd->kvm);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011365}
11366
11367int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
11368 uint32_t guest_irq, bool set)
11369{
Olivier Deprez157378f2022-04-04 15:47:50 +020011370 return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011371}
11372
11373bool kvm_vector_hashing_enabled(void)
11374{
11375 return vector_hashing;
11376}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011377
David Brazdil0f672f62019-12-10 10:32:29 +000011378bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
11379{
11380 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
11381}
11382EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
11383
11384
Olivier Deprez0e641232021-09-23 10:07:05 +020011385int kvm_spec_ctrl_test_value(u64 value)
11386{
11387 /*
11388 * test that setting IA32_SPEC_CTRL to given value
11389 * is allowed by the host processor
11390 */
11391
11392 u64 saved_value;
11393 unsigned long flags;
11394 int ret = 0;
11395
11396 local_irq_save(flags);
11397
11398 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
11399 ret = 1;
11400 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
11401 ret = 1;
11402 else
11403 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
11404
11405 local_irq_restore(flags);
11406
11407 return ret;
11408}
11409EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
11410
Olivier Deprez157378f2022-04-04 15:47:50 +020011411void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
11412{
11413 struct x86_exception fault;
11414 u32 access = error_code &
11415 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
11416
11417 if (!(error_code & PFERR_PRESENT_MASK) ||
11418 vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
11419 /*
11420 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
11421 * tables probably do not match the TLB. Just proceed
11422 * with the error code that the processor gave.
11423 */
11424 fault.vector = PF_VECTOR;
11425 fault.error_code_valid = true;
11426 fault.error_code = error_code;
11427 fault.nested_page_fault = false;
11428 fault.address = gva;
11429 }
11430 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
11431}
11432EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
11433
11434/*
11435 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
11436 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
11437 * indicates whether exit to userspace is needed.
11438 */
11439int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
11440 struct x86_exception *e)
11441{
11442 if (r == X86EMUL_PROPAGATE_FAULT) {
11443 kvm_inject_emulated_page_fault(vcpu, e);
11444 return 1;
11445 }
11446
11447 /*
11448 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
11449 * while handling a VMX instruction KVM could've handled the request
11450 * correctly by exiting to userspace and performing I/O but there
11451 * doesn't seem to be a real use-case behind such requests, just return
11452 * KVM_EXIT_INTERNAL_ERROR for now.
11453 */
11454 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11455 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11456 vcpu->run->internal.ndata = 0;
11457
11458 return 0;
11459}
11460EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
11461
11462int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
11463{
11464 bool pcid_enabled;
11465 struct x86_exception e;
11466 unsigned i;
11467 unsigned long roots_to_free = 0;
11468 struct {
11469 u64 pcid;
11470 u64 gla;
11471 } operand;
11472 int r;
11473
11474 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
11475 if (r != X86EMUL_CONTINUE)
11476 return kvm_handle_memory_failure(vcpu, r, &e);
11477
11478 if (operand.pcid >> 12 != 0) {
11479 kvm_inject_gp(vcpu, 0);
11480 return 1;
11481 }
11482
11483 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
11484
11485 switch (type) {
11486 case INVPCID_TYPE_INDIV_ADDR:
11487 if ((!pcid_enabled && (operand.pcid != 0)) ||
11488 is_noncanonical_address(operand.gla, vcpu)) {
11489 kvm_inject_gp(vcpu, 0);
11490 return 1;
11491 }
11492 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
11493 return kvm_skip_emulated_instruction(vcpu);
11494
11495 case INVPCID_TYPE_SINGLE_CTXT:
11496 if (!pcid_enabled && (operand.pcid != 0)) {
11497 kvm_inject_gp(vcpu, 0);
11498 return 1;
11499 }
11500
11501 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
11502 kvm_mmu_sync_roots(vcpu);
11503 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
11504 }
11505
11506 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
11507 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
11508 == operand.pcid)
11509 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
11510
11511 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
11512 /*
11513 * If neither the current cr3 nor any of the prev_roots use the
11514 * given PCID, then nothing needs to be done here because a
11515 * resync will happen anyway before switching to any other CR3.
11516 */
11517
11518 return kvm_skip_emulated_instruction(vcpu);
11519
11520 case INVPCID_TYPE_ALL_NON_GLOBAL:
11521 /*
11522 * Currently, KVM doesn't mark global entries in the shadow
11523 * page tables, so a non-global flush just degenerates to a
11524 * global flush. If needed, we could optimize this later by
11525 * keeping track of global entries in shadow page tables.
11526 */
11527
11528 fallthrough;
11529 case INVPCID_TYPE_ALL_INCL_GLOBAL:
11530 kvm_make_request(KVM_REQ_MMU_RELOAD, vcpu);
11531 return kvm_skip_emulated_instruction(vcpu);
11532
11533 default:
11534 BUG(); /* We have already checked above that type <= 3 */
11535 }
11536}
11537EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
11538
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011539EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
11540EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
11541EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
11542EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
11543EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
11544EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
11545EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
11546EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
11547EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
11548EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
David Brazdil0f672f62019-12-10 10:32:29 +000011549EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011550EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
11551EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
11552EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
11553EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
David Brazdil0f672f62019-12-10 10:32:29 +000011554EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011555EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
11556EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
11557EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
11558EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
Olivier Deprez157378f2022-04-04 15:47:50 +020011559EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
11560EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);
Olivier Deprez92d4c212022-12-06 15:05:30 +010011561
11562static int __init kvm_x86_init(void)
11563{
11564 kvm_mmu_x86_module_init();
11565 return 0;
11566}
11567module_init(kvm_x86_init);
11568
11569static void __exit kvm_x86_exit(void)
11570{
11571 /*
11572 * If module_init() is implemented, module_exit() must also be
11573 * implemented to allow module unload.
11574 */
11575}
11576module_exit(kvm_x86_exit);