blob: 7131d735b1ef3fb888beb9144795b0f312923a05 [file] [log] [blame]
Thomas Gleixner20c8ccb2019-06-04 10:11:32 +02001// SPDX-License-Identifier: GPL-2.0-only
Carsten Otte043405e2007-10-10 17:16:19 +02002/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * derived from drivers/kvm/kvm_main.c
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
Ben-Ami Yassour4d5c5d02008-07-28 19:26:26 +03008 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
Nicolas Kaiser9611c182010-10-06 14:23:22 +020010 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
Carsten Otte043405e2007-10-10 17:16:19 +020011 *
12 * Authors:
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
Ben-Ami Yassour4d5c5d02008-07-28 19:26:26 +030015 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
Carsten Otte043405e2007-10-10 17:16:19 +020017 */
18
Avi Kivityedf88412007-12-16 11:02:48 +020019#include <linux/kvm_host.h>
Carsten Otte313a3dc2007-10-11 19:16:52 +020020#include "irq.h"
彭浩(Richard)88197e62020-05-21 05:57:49 +000021#include "ioapic.h"
Zhang Xiantao1d737c82007-12-14 09:35:10 +080022#include "mmu.h"
Sheng Yang78376992008-01-28 05:10:22 +080023#include "i8254.h"
Izik Eidus37817f22008-03-24 23:14:53 +020024#include "tss.h"
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -030025#include "kvm_cache_regs.h"
Sean Christopherson2f728d62020-02-18 15:29:49 -080026#include "kvm_emulate.h"
Avi Kivity26eef702008-07-03 14:59:22 +030027#include "x86.h"
Avi Kivity00b27a32011-11-23 16:30:32 +020028#include "cpuid.h"
Wei Huang474a5bb2015-06-19 13:54:23 +020029#include "pmu.h"
Andrey Smetanine83d5882015-07-03 15:01:34 +030030#include "hyperv.h"
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -060031#include "lapic.h"
Joao Martins23200b72018-06-13 09:55:44 -040032#include "xen.h"
Carsten Otte313a3dc2007-10-11 19:16:52 +020033
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -020034#include <linux/clocksource.h>
Ben-Ami Yassour4d5c5d02008-07-28 19:26:26 +030035#include <linux/interrupt.h>
Carsten Otte313a3dc2007-10-11 19:16:52 +020036#include <linux/kvm.h>
37#include <linux/fs.h>
38#include <linux/vmalloc.h>
Paul Gortmaker1767e932016-07-13 20:19:00 -040039#include <linux/export.h>
40#include <linux/moduleparam.h>
Zhang Xiantao0de10342007-11-20 16:25:04 +080041#include <linux/mman.h>
Marcelo Tosatti2bacc552007-12-12 10:46:12 -050042#include <linux/highmem.h>
Joerg Roedel19de40a2008-12-03 14:43:34 +010043#include <linux/iommu.h>
Ben-Ami Yassour62c476c2008-09-14 03:48:28 +030044#include <linux/intel-iommu.h>
Gerd Hoffmannc8076602009-02-04 17:52:04 +010045#include <linux/cpufreq.h>
Avi Kivity18863bd2009-09-07 11:12:18 +030046#include <linux/user-return-notifier.h>
Marcelo Tosattia983fb22009-12-23 14:35:23 -020047#include <linux/srcu.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090048#include <linux/slab.h>
Zhang, Yanminff9d07a2010-04-19 13:32:45 +080049#include <linux/perf_event.h>
Lai Jiangshan7bee3422010-06-02 17:06:03 +080050#include <linux/uaccess.h>
Gleb Natapovaf585b92010-10-14 11:22:46 +020051#include <linux/hash.h>
Joerg Roedela1b60c12011-09-06 18:46:34 +020052#include <linux/pci.h>
Marcelo Tosatti16e8d742012-11-27 23:29:00 -020053#include <linux/timekeeper_internal.h>
54#include <linux/pvclock_gtod.h>
Feng Wu87276882015-09-18 22:29:40 +080055#include <linux/kvm_irqfd.h>
56#include <linux/irqbypass.h>
Ingo Molnar3905f9a2017-02-05 12:07:04 +010057#include <linux/sched/stat.h>
Wanpeng Li0c5f81d2019-07-06 09:26:51 +080058#include <linux/sched/isolation.h>
Tom Lendackyd0ec49d2017-07-17 16:10:27 -050059#include <linux/mem_encrypt.h>
Thomas Gleixner72c3c0f2020-07-23 00:00:09 +020060#include <linux/entry-kvm.h>
Sergey Senozhatsky7d628742021-06-06 11:10:45 +090061#include <linux/suspend.h>
Ingo Molnar3905f9a2017-02-05 12:07:04 +010062
Avi Kivityaec51dc2009-07-01 16:01:02 +030063#include <trace/events/kvm.h>
Xiao Guangrong2ed152a2010-03-10 19:00:43 +080064
Frederic Weisbecker24f1e32c2009-09-09 19:22:48 +020065#include <asm/debugreg.h>
Zhang Xiantaod825ed02007-11-14 20:08:51 +080066#include <asm/msr.h>
Avi Kivitya5f61302008-02-20 17:57:21 +020067#include <asm/desc.h>
Huang Ying890ca9a2009-05-11 16:48:15 +080068#include <asm/mce.h>
Dave Hansen784a46612021-06-23 14:02:05 +020069#include <asm/pkru.h>
Ingo Molnarf89e32e2015-04-22 10:58:10 +020070#include <linux/kernel_stat.h>
Thomas Gleixnera0ff0612021-10-15 03:16:12 +020071#include <asm/fpu/api.h>
72#include <asm/fpu/xcr.h>
73#include <asm/fpu/xstate.h>
Zachary Amsden1d5f0662010-08-19 22:07:30 -100074#include <asm/pvclock.h>
Avi Kivity217fc9c2010-08-26 13:38:03 +030075#include <asm/div64.h>
Feng Wuefc64402015-09-18 22:29:51 +080076#include <asm/irq_remapping.h>
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +010077#include <asm/mshyperv.h>
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +010078#include <asm/hypervisor.h>
Babu Moger97150922020-09-11 14:29:12 -050079#include <asm/tlbflush.h>
Chao Pengbf8c55d2018-10-24 16:05:14 +080080#include <asm/intel_pt.h>
Masami Hiramatsub3dc0692019-09-06 22:13:59 +090081#include <asm/emulate_prefix.h>
Sean Christophersonfe7e9482021-04-12 16:21:43 +120082#include <asm/sgx.h>
Michael Kelleydd2cb342019-07-01 04:26:06 +000083#include <clocksource/hyperv_timer.h>
Carsten Otte043405e2007-10-10 17:16:19 +020084
Dave Hansend1898b72016-06-01 10:42:20 -070085#define CREATE_TRACE_POINTS
86#include "trace.h"
87
Carsten Otte313a3dc2007-10-11 19:16:52 +020088#define MAX_IO_MSRS 256
Huang Ying890ca9a2009-05-11 16:48:15 +080089#define KVM_MAX_MCE_BANKS 32
Ashok Rajc45dcc72016-06-22 14:59:56 +080090u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
91EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
Huang Ying890ca9a2009-05-11 16:48:15 +080092
Sean Christopherson6e37ec882022-02-02 00:51:57 +000093#define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
94
Avi Kivity0f65dd72011-04-20 13:37:53 +030095#define emul_to_vcpu(ctxt) \
Sean Christophersonc9b8b072020-02-18 15:29:48 -080096 ((struct kvm_vcpu *)(ctxt)->vcpu)
Avi Kivity0f65dd72011-04-20 13:37:53 +030097
Joerg Roedel50a37eb2008-01-31 14:57:38 +010098/* EFER defaults:
99 * - enable syscall per default because its emulated by KVM
100 * - enable LME and LMA per default on 64 bit KVM
101 */
102#ifdef CONFIG_X86_64
Lai Jiangshan1260edbe2011-02-21 11:51:35 +0800103static
104u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
Joerg Roedel50a37eb2008-01-31 14:57:38 +0100105#else
Lai Jiangshan1260edbe2011-02-21 11:51:35 +0800106static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
Joerg Roedel50a37eb2008-01-31 14:57:38 +0100107#endif
Carsten Otte313a3dc2007-10-11 19:16:52 +0200108
Sean Christophersonb11306b2019-12-10 14:44:13 -0800109static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
110
Ashish Kalra0dbb1122021-06-08 18:05:43 +0000111#define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
112
Radim Krčmářc5192652016-07-12 22:09:28 +0200113#define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
114 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
Radim Krčmář371313132016-07-12 22:09:27 +0200115
Gleb Natapovcb142eb2009-08-09 15:17:40 +0300116static void update_cr8_intercept(struct kvm_vcpu *vcpu);
Avi Kivity7460fb4a2011-09-20 13:43:14 +0300117static void process_nmi(struct kvm_vcpu *vcpu);
Jay Zhou1f7becf2021-01-18 16:47:20 +0800118static void process_smi(struct kvm_vcpu *vcpu);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +0200119static void enter_smm(struct kvm_vcpu *vcpu);
Paolo Bonzini6addfc42014-03-27 11:29:28 +0100120static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
Ken Hofsass01643c52018-01-31 16:03:36 -0800121static void store_regs(struct kvm_vcpu *vcpu);
122static int sync_regs(struct kvm_vcpu *vcpu);
Hou Wenlongd2f7d492021-11-02 17:15:31 +0800123static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
Avi Kivity674eea02008-02-11 18:37:23 +0200124
Maxim Levitsky6dba9402021-06-07 12:02:02 +0300125static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
126static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
127
Sean Christophersonafaf0b22020-03-21 13:26:00 -0700128struct kvm_x86_ops kvm_x86_ops __read_mostly;
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -0300129EXPORT_SYMBOL_GPL(kvm_x86_ops);
Zhang Xiantao97896d02007-11-14 20:09:30 +0800130
Jason Baron9af54712021-01-14 22:27:55 -0500131#define KVM_X86_OP(func) \
132 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
133 *(((struct kvm_x86_ops *)0)->func));
134#define KVM_X86_OP_NULL KVM_X86_OP
135#include <asm/kvm-x86-ops.h>
136EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
137EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
138EXPORT_STATIC_CALL_GPL(kvm_x86_tlb_flush_current);
139
Paolo Bonzini893590c2015-11-06 11:46:24 +0100140static bool __read_mostly ignore_msrs = 0;
Rusty Russell476bc002012-01-13 09:32:18 +1030141module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
Andre Przywaraed85c062009-06-25 12:36:49 +0200142
Like Xud8550662021-01-08 09:36:55 +0800143bool __read_mostly report_ignored_msrs = true;
Eyal Moscovicifab0aa32017-11-08 14:32:08 +0200144module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
Like Xud8550662021-01-08 09:36:55 +0800145EXPORT_SYMBOL_GPL(report_ignored_msrs);
Eyal Moscovicifab0aa32017-11-08 14:32:08 +0200146
Wanpeng Li4c276252018-05-05 04:02:32 -0700147unsigned int min_timer_period_us = 200;
Marcelo Tosatti9ed96e82014-01-06 12:00:02 -0200148module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
149
Marcelo Tosatti630994b2015-05-12 22:42:04 -0300150static bool __read_mostly kvmclock_periodic_sync = true;
151module_param(kvmclock_periodic_sync, bool, S_IRUGO);
152
Paolo Bonzini893590c2015-11-06 11:46:24 +0100153bool __read_mostly kvm_has_tsc_control;
Joerg Roedel92a1f122011-03-25 09:44:51 +0100154EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
Paolo Bonzini893590c2015-11-06 11:46:24 +0100155u32 __read_mostly kvm_max_guest_tsc_khz;
Joerg Roedel92a1f122011-03-25 09:44:51 +0100156EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
Haozhong Zhangbc9b9612015-10-20 15:39:01 +0800157u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
158EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
159u64 __read_mostly kvm_max_tsc_scaling_ratio;
160EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
Yunhong Jiang64672c92016-06-13 14:19:59 -0700161u64 __read_mostly kvm_default_tsc_scaling_ratio;
162EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
Chenyi Qiangfe6b6bc2020-11-06 17:03:14 +0800163bool __read_mostly kvm_has_bus_lock_exit;
164EXPORT_SYMBOL_GPL(kvm_has_bus_lock_exit);
Joerg Roedel92a1f122011-03-25 09:44:51 +0100165
Zachary Amsdencc578282012-02-03 15:43:50 -0200166/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
Paolo Bonzini893590c2015-11-06 11:46:24 +0100167static u32 __read_mostly tsc_tolerance_ppm = 250;
Zachary Amsdencc578282012-02-03 15:43:50 -0200168module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
169
Sean Christophersonc3941d92019-04-17 10:15:33 -0700170/*
171 * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
Ingo Molnard9f6e122021-03-18 15:28:01 +0100172 * adaptive tuning starting from default advancement of 1000ns. '0' disables
Sean Christophersonc3941d92019-04-17 10:15:33 -0700173 * advancement entirely. Any other value is used as-is and disables adaptive
Ingo Molnard9f6e122021-03-18 15:28:01 +0100174 * tuning, i.e. allows privileged userspace to set an exact advancement time.
Sean Christophersonc3941d92019-04-17 10:15:33 -0700175 */
176static int __read_mostly lapic_timer_advance_ns = -1;
Wanpeng Li0e6edce2019-05-20 16:18:06 +0800177module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
Marcelo Tosattid0659d92014-12-16 09:08:15 -0500178
Feng Wu520040142016-01-25 16:53:33 +0800179static bool __read_mostly vector_hashing = true;
180module_param(vector_hashing, bool, S_IRUGO);
181
Liran Alonc4ae60e2018-03-12 13:12:47 +0200182bool __read_mostly enable_vmware_backdoor = false;
183module_param(enable_vmware_backdoor, bool, S_IRUGO);
184EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
185
Wanpeng Li6c86eed2018-04-03 16:28:49 -0700186static bool __read_mostly force_emulation_prefix = false;
187module_param(force_emulation_prefix, bool, S_IRUGO);
188
Wanpeng Li0c5f81d2019-07-06 09:26:51 +0800189int __read_mostly pi_inject_timer = -1;
190module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
191
Like Xu4732f242022-01-11 15:38:23 +0800192/* Enable/disable PMU virtualization */
193bool __read_mostly enable_pmu = true;
194EXPORT_SYMBOL_GPL(enable_pmu);
195module_param(enable_pmu, bool, 0444);
196
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700197/*
198 * Restoring the host value for MSRs that are only consumed when running in
199 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
200 * returns to userspace, i.e. the kernel can run with the guest's value.
201 */
202#define KVM_MAX_NR_USER_RETURN_MSRS 16
Avi Kivity18863bd2009-09-07 11:12:18 +0300203
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700204struct kvm_user_return_msrs {
Avi Kivity18863bd2009-09-07 11:12:18 +0300205 struct user_return_notifier urn;
206 bool registered;
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700207 struct kvm_user_return_msr_values {
Sheng Yang2bf78fa2009-12-18 16:48:44 +0800208 u64 host;
209 u64 curr;
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700210 } values[KVM_MAX_NR_USER_RETURN_MSRS];
Avi Kivity18863bd2009-09-07 11:12:18 +0300211};
212
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700213u32 __read_mostly kvm_nr_uret_msrs;
214EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
215static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700216static struct kvm_user_return_msrs __percpu *user_return_msrs;
Avi Kivity18863bd2009-09-07 11:12:18 +0300217
Sean Christophersoncfc48182020-03-02 15:56:23 -0800218#define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
219 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
220 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
Jing Liu86aff7a42022-01-05 04:35:26 -0800221 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
Sean Christophersoncfc48182020-03-02 15:56:23 -0800222
Sean Christopherson91661982020-03-02 15:57:06 -0800223u64 __read_mostly host_efer;
224EXPORT_SYMBOL_GPL(host_efer);
225
Mohammed Gamalb96e6502020-09-03 16:11:22 +0200226bool __read_mostly allow_smaller_maxphyaddr = 0;
Mohammed Gamal3edd6832020-07-10 17:48:11 +0200227EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
228
Vitaly Kuznetsovfdf513e2021-06-09 17:09:08 +0200229bool __read_mostly enable_apicv = true;
230EXPORT_SYMBOL_GPL(enable_apicv);
231
Tom Lendacky86137772020-12-10 11:10:07 -0600232u64 __read_mostly host_xss;
233EXPORT_SYMBOL_GPL(host_xss);
Paolo Bonzini408e9a32020-03-05 16:11:56 +0100234u64 __read_mostly supported_xss;
235EXPORT_SYMBOL_GPL(supported_xss);
Aaron Lewis139a12c2019-10-21 16:30:25 -0700236
Jing Zhangfcfe1ba2021-06-18 22:27:05 +0000237const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
238 KVM_GENERIC_VM_STATS(),
239 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
240 STATS_DESC_COUNTER(VM, mmu_pte_write),
241 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
242 STATS_DESC_COUNTER(VM, mmu_flooded),
243 STATS_DESC_COUNTER(VM, mmu_recycled),
244 STATS_DESC_COUNTER(VM, mmu_cache_miss),
245 STATS_DESC_ICOUNTER(VM, mmu_unsync),
Mingwei Zhang71f51d22021-08-02 21:46:07 -0700246 STATS_DESC_ICOUNTER(VM, pages_4k),
247 STATS_DESC_ICOUNTER(VM, pages_2m),
248 STATS_DESC_ICOUNTER(VM, pages_1g),
Jing Zhangfcfe1ba2021-06-18 22:27:05 +0000249 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
Peter Xuec1cf692021-06-25 11:32:06 -0400250 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400251 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
Jing Zhangfcfe1ba2021-06-18 22:27:05 +0000252};
Jing Zhangfcfe1ba2021-06-18 22:27:05 +0000253
254const struct kvm_stats_header kvm_vm_stats_header = {
255 .name_size = KVM_STATS_NAME_SIZE,
256 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
257 .id_offset = sizeof(struct kvm_stats_header),
258 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
259 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
260 sizeof(kvm_vm_stats_desc),
261};
262
Jing Zhangce55c042021-06-18 22:27:06 +0000263const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
264 KVM_GENERIC_VCPU_STATS(),
265 STATS_DESC_COUNTER(VCPU, pf_fixed),
266 STATS_DESC_COUNTER(VCPU, pf_guest),
267 STATS_DESC_COUNTER(VCPU, tlb_flush),
268 STATS_DESC_COUNTER(VCPU, invlpg),
269 STATS_DESC_COUNTER(VCPU, exits),
270 STATS_DESC_COUNTER(VCPU, io_exits),
271 STATS_DESC_COUNTER(VCPU, mmio_exits),
272 STATS_DESC_COUNTER(VCPU, signal_exits),
273 STATS_DESC_COUNTER(VCPU, irq_window_exits),
274 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
275 STATS_DESC_COUNTER(VCPU, l1d_flush),
276 STATS_DESC_COUNTER(VCPU, halt_exits),
277 STATS_DESC_COUNTER(VCPU, request_irq_exits),
278 STATS_DESC_COUNTER(VCPU, irq_exits),
279 STATS_DESC_COUNTER(VCPU, host_state_reload),
280 STATS_DESC_COUNTER(VCPU, fpu_reload),
281 STATS_DESC_COUNTER(VCPU, insn_emulation),
282 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
283 STATS_DESC_COUNTER(VCPU, hypercalls),
284 STATS_DESC_COUNTER(VCPU, irq_injections),
285 STATS_DESC_COUNTER(VCPU, nmi_injections),
286 STATS_DESC_COUNTER(VCPU, req_event),
287 STATS_DESC_COUNTER(VCPU, nested_run),
288 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
289 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
290 STATS_DESC_ICOUNTER(VCPU, guest_mode)
291};
Jing Zhangce55c042021-06-18 22:27:06 +0000292
293const struct kvm_stats_header kvm_vcpu_stats_header = {
294 .name_size = KVM_STATS_NAME_SIZE,
295 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
296 .id_offset = sizeof(struct kvm_stats_header),
297 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
298 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
299 sizeof(kvm_vcpu_stats_desc),
300};
301
Dexuan Cui2acf9232010-06-10 11:27:12 +0800302u64 __read_mostly host_xcr0;
Sean Christophersoncfc48182020-03-02 15:56:23 -0800303u64 __read_mostly supported_xcr0;
304EXPORT_SYMBOL_GPL(supported_xcr0);
Dexuan Cui2acf9232010-06-10 11:27:12 +0800305
Sean Christophersonc9b8b072020-02-18 15:29:48 -0800306static struct kmem_cache *x86_emulator_cache;
307
Peter Xu6abe9c12020-06-22 18:04:41 -0400308/*
309 * When called, it means the previous get/set msr reached an invalid msr.
Maxim Levitskycc4cb012020-11-01 13:55:23 +0200310 * Return true if we want to ignore/silent this failed msr access.
Peter Xu6abe9c12020-06-22 18:04:41 -0400311 */
Haiwei Lid6328262021-03-13 13:10:32 +0800312static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
Peter Xu6abe9c12020-06-22 18:04:41 -0400313{
314 const char *op = write ? "wrmsr" : "rdmsr";
315
316 if (ignore_msrs) {
317 if (report_ignored_msrs)
Takashi Iwaid383b312020-10-30 16:14:14 +0100318 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
319 op, msr, data);
Peter Xu6abe9c12020-06-22 18:04:41 -0400320 /* Mask the error */
Maxim Levitskycc4cb012020-11-01 13:55:23 +0200321 return true;
Peter Xu6abe9c12020-06-22 18:04:41 -0400322 } else {
Takashi Iwaid383b312020-10-30 16:14:14 +0100323 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
324 op, msr, data);
Maxim Levitskycc4cb012020-11-01 13:55:23 +0200325 return false;
Peter Xu6abe9c12020-06-22 18:04:41 -0400326 }
327}
328
Sean Christophersonc9b8b072020-02-18 15:29:48 -0800329static struct kmem_cache *kvm_alloc_emulator_cache(void)
330{
Sean Christopherson06add252020-02-18 15:29:50 -0800331 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
332 unsigned int size = sizeof(struct x86_emulate_ctxt);
333
334 return kmem_cache_create_usercopy("x86_emulator", size,
Sean Christophersonc9b8b072020-02-18 15:29:48 -0800335 __alignof__(struct x86_emulate_ctxt),
Sean Christopherson06add252020-02-18 15:29:50 -0800336 SLAB_ACCOUNT, useroffset,
337 size - useroffset, NULL);
Sean Christophersonc9b8b072020-02-18 15:29:48 -0800338}
339
Jan Kiszkab6785de2012-09-20 07:43:17 +0200340static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
Avi Kivityd6aa1002011-04-20 15:47:13 +0300341
Gleb Natapovaf585b92010-10-14 11:22:46 +0200342static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
343{
344 int i;
Peter Xudd03bca2020-04-16 11:58:59 -0400345 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
Gleb Natapovaf585b92010-10-14 11:22:46 +0200346 vcpu->arch.apf.gfns[i] = ~0;
347}
348
Avi Kivity18863bd2009-09-07 11:12:18 +0300349static void kvm_on_user_return(struct user_return_notifier *urn)
350{
351 unsigned slot;
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700352 struct kvm_user_return_msrs *msrs
353 = container_of(urn, struct kvm_user_return_msrs, urn);
354 struct kvm_user_return_msr_values *values;
Ignacio Alvarado1650b4e2016-11-04 12:15:55 -0700355 unsigned long flags;
Avi Kivity18863bd2009-09-07 11:12:18 +0300356
Ignacio Alvarado1650b4e2016-11-04 12:15:55 -0700357 /*
358 * Disabling irqs at this point since the following code could be
359 * interrupted and executed through kvm_arch_hardware_disable()
360 */
361 local_irq_save(flags);
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700362 if (msrs->registered) {
363 msrs->registered = false;
Ignacio Alvarado1650b4e2016-11-04 12:15:55 -0700364 user_return_notifier_unregister(urn);
365 }
366 local_irq_restore(flags);
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700367 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700368 values = &msrs->values[slot];
Sheng Yang2bf78fa2009-12-18 16:48:44 +0800369 if (values->host != values->curr) {
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700370 wrmsrl(kvm_uret_msrs_list[slot], values->host);
Sheng Yang2bf78fa2009-12-18 16:48:44 +0800371 values->curr = values->host;
Avi Kivity18863bd2009-09-07 11:12:18 +0300372 }
373 }
Avi Kivity18863bd2009-09-07 11:12:18 +0300374}
375
Sean Christophersone5fda4b2021-05-04 10:17:32 -0700376static int kvm_probe_user_return_msr(u32 msr)
Sean Christopherson5104d7f2021-05-04 10:17:24 -0700377{
378 u64 val;
379 int ret;
380
381 preempt_disable();
382 ret = rdmsrl_safe(msr, &val);
383 if (ret)
384 goto out;
385 ret = wrmsrl_safe(msr, val);
386out:
387 preempt_enable();
388 return ret;
389}
Sean Christopherson5104d7f2021-05-04 10:17:24 -0700390
Sean Christophersone5fda4b2021-05-04 10:17:32 -0700391int kvm_add_user_return_msr(u32 msr)
Sheng Yang2bf78fa2009-12-18 16:48:44 +0800392{
Sean Christophersone5fda4b2021-05-04 10:17:32 -0700393 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
394
395 if (kvm_probe_user_return_msr(msr))
396 return -1;
397
398 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
399 return kvm_nr_uret_msrs++;
Avi Kivity18863bd2009-09-07 11:12:18 +0300400}
Sean Christophersone5fda4b2021-05-04 10:17:32 -0700401EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
Avi Kivity18863bd2009-09-07 11:12:18 +0300402
Sean Christopherson8ea8b8d2021-05-04 10:17:29 -0700403int kvm_find_user_return_msr(u32 msr)
404{
405 int i;
406
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700407 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
408 if (kvm_uret_msrs_list[i] == msr)
Sean Christopherson8ea8b8d2021-05-04 10:17:29 -0700409 return i;
410 }
411 return -1;
412}
413EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
414
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700415static void kvm_user_return_msr_cpu_online(void)
Avi Kivity18863bd2009-09-07 11:12:18 +0300416{
Sean Christopherson05c19c22019-11-22 12:04:50 -0800417 unsigned int cpu = smp_processor_id();
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700418 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Sean Christopherson05c19c22019-11-22 12:04:50 -0800419 u64 value;
420 int i;
Avi Kivity18863bd2009-09-07 11:12:18 +0300421
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700422 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
423 rdmsrl_safe(kvm_uret_msrs_list[i], &value);
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700424 msrs->values[i].host = value;
425 msrs->values[i].curr = value;
Sean Christopherson05c19c22019-11-22 12:04:50 -0800426 }
Avi Kivity18863bd2009-09-07 11:12:18 +0300427}
428
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700429int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
Avi Kivity18863bd2009-09-07 11:12:18 +0300430{
Marcelo Tosatti013f6a52013-01-03 11:41:39 -0200431 unsigned int cpu = smp_processor_id();
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700432 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Andy Honig8b3c3102014-08-27 11:16:44 -0700433 int err;
Avi Kivity18863bd2009-09-07 11:12:18 +0300434
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700435 value = (value & mask) | (msrs->values[slot].host & ~mask);
436 if (value == msrs->values[slot].curr)
Andy Honig8b3c3102014-08-27 11:16:44 -0700437 return 0;
Sean Christopherson9cc39a52021-05-04 10:17:31 -0700438 err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
Andy Honig8b3c3102014-08-27 11:16:44 -0700439 if (err)
440 return 1;
441
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700442 msrs->values[slot].curr = value;
443 if (!msrs->registered) {
444 msrs->urn.on_user_return = kvm_on_user_return;
445 user_return_notifier_register(&msrs->urn);
446 msrs->registered = true;
Avi Kivity18863bd2009-09-07 11:12:18 +0300447 }
Andy Honig8b3c3102014-08-27 11:16:44 -0700448 return 0;
Avi Kivity18863bd2009-09-07 11:12:18 +0300449}
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700450EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
Avi Kivity18863bd2009-09-07 11:12:18 +0300451
Radim Krčmář13a34e02014-08-28 15:13:03 +0200452static void drop_user_return_notifiers(void)
Avi Kivity3548bab2009-11-28 14:18:47 +0200453{
Marcelo Tosatti013f6a52013-01-03 11:41:39 -0200454 unsigned int cpu = smp_processor_id();
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700455 struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
Avi Kivity3548bab2009-11-28 14:18:47 +0200456
Sean Christopherson7e34fbd2020-09-23 11:03:55 -0700457 if (msrs->registered)
458 kvm_on_user_return(&msrs->urn);
Avi Kivity3548bab2009-11-28 14:18:47 +0200459}
460
Carsten Otte6866b832007-10-29 16:09:10 +0100461u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
462{
Gleb Natapov8a5a87d2012-08-05 15:58:26 +0300463 return vcpu->arch.apic_base;
Carsten Otte6866b832007-10-29 16:09:10 +0100464}
465EXPORT_SYMBOL_GPL(kvm_get_apic_base);
466
Jim Mattson58871642018-05-09 16:56:04 -0400467enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
468{
469 return kvm_apic_mode(kvm_get_apic_base(vcpu));
470}
471EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
472
Jan Kiszka58cb6282014-01-24 16:48:44 +0100473int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Carsten Otte6866b832007-10-29 16:09:10 +0100474{
Jim Mattson58871642018-05-09 16:56:04 -0400475 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
476 enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
Sean Christophersona8ac8642021-02-03 16:01:15 -0800477 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
Radim Krčmářd6321d42017-08-05 00:12:49 +0200478 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
Jan Kiszka58cb6282014-01-24 16:48:44 +0100479
Jim Mattson58871642018-05-09 16:56:04 -0400480 if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
Jim Mattsond3802282017-08-10 10:14:13 -0700481 return 1;
Jim Mattson58871642018-05-09 16:56:04 -0400482 if (!msr_info->host_initiated) {
483 if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
484 return 1;
485 if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
486 return 1;
487 }
Jan Kiszka58cb6282014-01-24 16:48:44 +0100488
489 kvm_lapic_set_base(vcpu, msr_info->data);
Wanpeng Li4abaffc2020-02-26 10:41:02 +0800490 kvm_recalculate_apic_map(vcpu->kvm);
Jan Kiszka58cb6282014-01-24 16:48:44 +0100491 return 0;
Carsten Otte6866b832007-10-29 16:09:10 +0100492}
493EXPORT_SYMBOL_GPL(kvm_set_apic_base);
494
Sean Christophersonad0577c2021-08-09 10:39:54 -0700495/*
496 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
497 *
498 * Hardware virtualization extension instructions may fault if a reboot turns
499 * off virtualization while processes are running. Usually after catching the
500 * fault we just panic; during reboot instead the instruction is ignored.
501 */
502noinstr void kvm_spurious_fault(void)
Geoff Levande3ba45b2013-04-05 19:20:30 +0000503{
504 /* Fault while not rebooting. We want the trace. */
kbuild test robotb4fdcf62019-09-29 18:43:28 +0200505 BUG_ON(!kvm_rebooting);
Geoff Levande3ba45b2013-04-05 19:20:30 +0000506}
507EXPORT_SYMBOL_GPL(kvm_spurious_fault);
508
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200509#define EXCPT_BENIGN 0
510#define EXCPT_CONTRIBUTORY 1
511#define EXCPT_PF 2
512
513static int exception_class(int vector)
514{
515 switch (vector) {
516 case PF_VECTOR:
517 return EXCPT_PF;
518 case DE_VECTOR:
519 case TS_VECTOR:
520 case NP_VECTOR:
521 case SS_VECTOR:
522 case GP_VECTOR:
523 return EXCPT_CONTRIBUTORY;
524 default:
525 break;
526 }
527 return EXCPT_BENIGN;
528}
529
Nadav Amitd6e8c852014-07-24 14:51:24 +0300530#define EXCPT_FAULT 0
531#define EXCPT_TRAP 1
532#define EXCPT_ABORT 2
533#define EXCPT_INTERRUPT 3
534
535static int exception_type(int vector)
536{
537 unsigned int mask;
538
539 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
540 return EXCPT_INTERRUPT;
541
542 mask = 1 << vector;
543
544 /* #DB is trap, as instruction watchpoints are handled elsewhere */
545 if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
546 return EXCPT_TRAP;
547
548 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
549 return EXCPT_ABORT;
550
551 /* Reserved exceptions will result in fault */
552 return EXCPT_FAULT;
553}
554
Jim Mattsonda998b42018-10-16 14:29:22 -0700555void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
556{
557 unsigned nr = vcpu->arch.exception.nr;
558 bool has_payload = vcpu->arch.exception.has_payload;
559 unsigned long payload = vcpu->arch.exception.payload;
560
561 if (!has_payload)
562 return;
563
564 switch (nr) {
Jim Mattsonf10c7292018-10-16 14:29:23 -0700565 case DB_VECTOR:
566 /*
567 * "Certain debug exceptions may clear bit 0-3. The
568 * remaining contents of the DR6 register are never
569 * cleared by the processor".
570 */
571 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
572 /*
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +0800573 * In order to reflect the #DB exception payload in guest
574 * dr6, three components need to be considered: active low
575 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
576 * DR6_BS and DR6_BT)
577 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
578 * In the target guest dr6:
579 * FIXED_1 bits should always be set.
580 * Active low bits should be cleared if 1-setting in payload.
581 * Active high bits should be set if 1-setting in payload.
582 *
583 * Note, the payload is compatible with the pending debug
584 * exceptions/exit qualification under VMX, that active_low bits
585 * are active high in payload.
586 * So they need to be flipped for DR6.
Jim Mattsonf10c7292018-10-16 14:29:23 -0700587 */
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +0800588 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
Jim Mattsonf10c7292018-10-16 14:29:23 -0700589 vcpu->arch.dr6 |= payload;
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +0800590 vcpu->arch.dr6 ^= payload & DR6_ACTIVE_LOW;
Oliver Upton307f1cf2020-02-07 02:36:04 -0800591
592 /*
593 * The #DB payload is defined as compatible with the 'pending
594 * debug exceptions' field under VMX, not DR6. While bit 12 is
595 * defined in the 'pending debug exceptions' field (enabled
596 * breakpoint), it is reserved and must be zero in DR6.
597 */
598 vcpu->arch.dr6 &= ~BIT(12);
Jim Mattsonf10c7292018-10-16 14:29:23 -0700599 break;
Jim Mattsonda998b42018-10-16 14:29:22 -0700600 case PF_VECTOR:
601 vcpu->arch.cr2 = payload;
602 break;
603 }
604
605 vcpu->arch.exception.has_payload = false;
606 vcpu->arch.exception.payload = 0;
607}
608EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
609
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200610static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
Joerg Roedelce7ddec2010-04-22 12:33:13 +0200611 unsigned nr, bool has_error, u32 error_code,
Jim Mattson91e86d22018-10-16 14:29:21 -0700612 bool has_payload, unsigned long payload, bool reinject)
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200613{
614 u32 prev_nr;
615 int class1, class2;
616
Avi Kivity3842d132010-07-27 12:30:24 +0300617 kvm_make_request(KVM_REQ_EVENT, vcpu);
618
Wanpeng Li664f8e22017-08-24 03:35:09 -0700619 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200620 queue:
Wanpeng Li664f8e22017-08-24 03:35:09 -0700621 if (reinject) {
622 /*
623 * On vmentry, vcpu->arch.exception.pending is only
624 * true if an event injection was blocked by
625 * nested_run_pending. In that case, however,
626 * vcpu_enter_guest requests an immediate exit,
627 * and the guest shouldn't proceed far enough to
628 * need reinjection.
629 */
630 WARN_ON_ONCE(vcpu->arch.exception.pending);
631 vcpu->arch.exception.injected = true;
Jim Mattson91e86d22018-10-16 14:29:21 -0700632 if (WARN_ON_ONCE(has_payload)) {
633 /*
634 * A reinjected event has already
635 * delivered its payload.
636 */
637 has_payload = false;
638 payload = 0;
639 }
Wanpeng Li664f8e22017-08-24 03:35:09 -0700640 } else {
641 vcpu->arch.exception.pending = true;
642 vcpu->arch.exception.injected = false;
643 }
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200644 vcpu->arch.exception.has_error_code = has_error;
645 vcpu->arch.exception.nr = nr;
646 vcpu->arch.exception.error_code = error_code;
Jim Mattson91e86d22018-10-16 14:29:21 -0700647 vcpu->arch.exception.has_payload = has_payload;
648 vcpu->arch.exception.payload = payload;
Oliver Uptona06230b2020-02-07 02:36:06 -0800649 if (!is_guest_mode(vcpu))
Jim Mattsonda998b42018-10-16 14:29:22 -0700650 kvm_deliver_exception_payload(vcpu);
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200651 return;
652 }
653
654 /* to check exception */
655 prev_nr = vcpu->arch.exception.nr;
656 if (prev_nr == DF_VECTOR) {
657 /* triple fault -> shutdown */
Avi Kivitya8eeb042010-05-10 12:34:53 +0300658 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200659 return;
660 }
661 class1 = exception_class(prev_nr);
662 class2 = exception_class(nr);
663 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
664 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
Wanpeng Li664f8e22017-08-24 03:35:09 -0700665 /*
666 * Generate double fault per SDM Table 5-5. Set
667 * exception.pending = true so that the double fault
668 * can trigger a nested vmexit.
669 */
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200670 vcpu->arch.exception.pending = true;
Wanpeng Li664f8e22017-08-24 03:35:09 -0700671 vcpu->arch.exception.injected = false;
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200672 vcpu->arch.exception.has_error_code = true;
673 vcpu->arch.exception.nr = DF_VECTOR;
674 vcpu->arch.exception.error_code = 0;
Jim Mattsonc8514362018-10-16 14:29:19 -0700675 vcpu->arch.exception.has_payload = false;
676 vcpu->arch.exception.payload = 0;
Eddie Dong3fd28fc2009-11-19 17:54:07 +0200677 } else
678 /* replace previous exception with a new one in a hope
679 that instruction re-execution will regenerate lost
680 exception */
681 goto queue;
682}
683
Avi Kivity298101d2007-11-25 13:41:11 +0200684void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
685{
Jim Mattson91e86d22018-10-16 14:29:21 -0700686 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
Avi Kivity298101d2007-11-25 13:41:11 +0200687}
688EXPORT_SYMBOL_GPL(kvm_queue_exception);
689
Joerg Roedelce7ddec2010-04-22 12:33:13 +0200690void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
691{
Jim Mattson91e86d22018-10-16 14:29:21 -0700692 kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
Joerg Roedelce7ddec2010-04-22 12:33:13 +0200693}
694EXPORT_SYMBOL_GPL(kvm_requeue_exception);
695
Paolo Bonzini4d5523c2020-05-05 07:33:20 -0400696void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
697 unsigned long payload)
Jim Mattsonf10c7292018-10-16 14:29:23 -0700698{
699 kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
700}
Paolo Bonzini4d5523c2020-05-05 07:33:20 -0400701EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
Jim Mattsonf10c7292018-10-16 14:29:23 -0700702
Jim Mattsonda998b42018-10-16 14:29:22 -0700703static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
704 u32 error_code, unsigned long payload)
705{
706 kvm_multiple_exception(vcpu, nr, true, error_code,
707 true, payload, false);
708}
709
Kyle Huey6affcbe2016-11-29 12:40:40 -0800710int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
Avi Kivityc3c91fe2007-11-25 14:04:58 +0200711{
Andre Przywaradb8fcef2010-12-21 11:12:01 +0100712 if (err)
713 kvm_inject_gp(vcpu, 0);
714 else
Kyle Huey6affcbe2016-11-29 12:40:40 -0800715 return kvm_skip_emulated_instruction(vcpu);
716
717 return 1;
Andre Przywaradb8fcef2010-12-21 11:12:01 +0100718}
719EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
Joerg Roedel8df25a32010-09-10 17:30:46 +0200720
Hou Wenlongd2f7d492021-11-02 17:15:31 +0800721static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
722{
723 if (err) {
724 kvm_inject_gp(vcpu, 0);
725 return 1;
726 }
727
728 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
729 EMULTYPE_COMPLETE_USER_EXIT);
730}
731
Avi Kivity6389ee92010-11-29 16:12:30 +0200732void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
Avi Kivityc3c91fe2007-11-25 14:04:58 +0200733{
Avi Kivityc3c91fe2007-11-25 14:04:58 +0200734 ++vcpu->stat.pf_guest;
Wanpeng Liadfe20f2017-07-13 18:30:41 -0700735 vcpu->arch.exception.nested_apf =
736 is_guest_mode(vcpu) && fault->async_page_fault;
Jim Mattsonda998b42018-10-16 14:29:22 -0700737 if (vcpu->arch.exception.nested_apf) {
Wanpeng Liadfe20f2017-07-13 18:30:41 -0700738 vcpu->arch.apf.nested_apf_token = fault->address;
Jim Mattsonda998b42018-10-16 14:29:22 -0700739 kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
740 } else {
741 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
742 fault->address);
743 }
Avi Kivityc3c91fe2007-11-25 14:04:58 +0200744}
Nadav Har'El27d6c862011-05-25 23:06:59 +0300745EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
Avi Kivityc3c91fe2007-11-25 14:04:58 +0200746
Sean Christopherson53b3d8e2020-03-20 14:28:01 -0700747bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
748 struct x86_exception *fault)
Joerg Roedeld4f8cf62010-09-10 17:30:55 +0200749{
Paolo Bonzini0cd665b2020-03-25 12:50:03 -0400750 struct kvm_mmu *fault_mmu;
Sean Christopherson53b3d8e2020-03-20 14:28:01 -0700751 WARN_ON_ONCE(fault->vector != PF_VECTOR);
752
Paolo Bonzini0cd665b2020-03-25 12:50:03 -0400753 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
754 vcpu->arch.walk_mmu;
Paolo Bonzinief54bcf2014-09-04 19:46:15 +0200755
Junaid Shahidee1fa202020-03-20 14:28:03 -0700756 /*
757 * Invalidate the TLB entry for the faulting address, if it exists,
758 * else the access will fault indefinitely (and to emulate hardware).
759 */
760 if ((fault->error_code & PFERR_PRESENT_MASK) &&
761 !(fault->error_code & PFERR_RSVD_MASK))
762 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
763 fault_mmu->root_hpa);
764
765 fault_mmu->inject_page_fault(vcpu, fault);
Paolo Bonzinief54bcf2014-09-04 19:46:15 +0200766 return fault->nested_page_fault;
Joerg Roedeld4f8cf62010-09-10 17:30:55 +0200767}
Sean Christopherson53b3d8e2020-03-20 14:28:01 -0700768EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
Joerg Roedeld4f8cf62010-09-10 17:30:55 +0200769
Sheng Yang3419ffc2008-05-15 09:52:48 +0800770void kvm_inject_nmi(struct kvm_vcpu *vcpu)
771{
Avi Kivity7460fb4a2011-09-20 13:43:14 +0300772 atomic_inc(&vcpu->arch.nmi_queued);
773 kvm_make_request(KVM_REQ_NMI, vcpu);
Sheng Yang3419ffc2008-05-15 09:52:48 +0800774}
775EXPORT_SYMBOL_GPL(kvm_inject_nmi);
776
Avi Kivity298101d2007-11-25 13:41:11 +0200777void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
778{
Jim Mattson91e86d22018-10-16 14:29:21 -0700779 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
Avi Kivity298101d2007-11-25 13:41:11 +0200780}
781EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
782
Joerg Roedelce7ddec2010-04-22 12:33:13 +0200783void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
784{
Jim Mattson91e86d22018-10-16 14:29:21 -0700785 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
Joerg Roedelce7ddec2010-04-22 12:33:13 +0200786}
787EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
788
Carsten Ottea03490e2007-10-29 16:09:35 +0100789/*
Avi Kivity0a79b002009-09-01 12:03:25 +0300790 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
791 * a #GP and return false.
792 */
793bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
Carsten Otte043405e2007-10-10 17:16:19 +0200794{
Jason Baronb36464772021-01-14 22:27:56 -0500795 if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
Avi Kivity0a79b002009-09-01 12:03:25 +0300796 return true;
797 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
798 return false;
Carsten Ottea03490e2007-10-29 16:09:35 +0100799}
Avi Kivity0a79b002009-09-01 12:03:25 +0300800EXPORT_SYMBOL_GPL(kvm_require_cpl);
Carsten Ottea03490e2007-10-29 16:09:35 +0100801
Nadav Amit16f8a6f2014-10-03 01:10:05 +0300802bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
803{
804 if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
805 return true;
806
807 kvm_queue_exception(vcpu, UD_VECTOR);
808 return false;
809}
810EXPORT_SYMBOL_GPL(kvm_require_dr);
811
Sean Christopherson16cfacc2019-09-03 16:36:45 -0700812static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
813{
Sean Christopherson5b7f5752021-02-03 16:01:13 -0800814 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
Sean Christopherson16cfacc2019-09-03 16:36:45 -0700815}
816
Joerg Roedelec92fe42010-09-10 17:30:51 +0200817/*
Sean Christopherson16cfacc2019-09-03 16:36:45 -0700818 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
Carsten Ottea03490e2007-10-29 16:09:35 +0100819 */
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +0800820int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
Carsten Ottea03490e2007-10-29 16:09:35 +0100821{
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +0800822 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Carsten Ottea03490e2007-10-29 16:09:35 +0100823 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700824 gpa_t real_gpa;
Carsten Ottea03490e2007-10-29 16:09:35 +0100825 int i;
826 int ret;
Joerg Roedelff03a072010-09-10 17:30:57 +0200827 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
Carsten Ottea03490e2007-10-29 16:09:35 +0100828
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700829 /*
830 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
831 * to an L1 GPA.
832 */
Lai Jiangshanc59a0f52021-11-24 20:20:45 +0800833 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
834 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700835 if (real_gpa == UNMAPPED_GVA)
836 return 0;
837
Sean Christopherson94c641b2021-08-31 09:42:24 -0700838 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700839 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
Sean Christopherson94c641b2021-08-31 09:42:24 -0700840 cr3 & GENMASK(11, 5), sizeof(pdpte));
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700841 if (ret < 0)
842 return 0;
843
Carsten Ottea03490e2007-10-29 16:09:35 +0100844 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
Bandan Das812f30b2016-07-12 18:18:50 -0400845 if ((pdpte[i] & PT_PRESENT_MASK) &&
Sean Christopherson16cfacc2019-09-03 16:36:45 -0700846 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700847 return 0;
Carsten Ottea03490e2007-10-29 16:09:35 +0100848 }
849 }
Carsten Ottea03490e2007-10-29 16:09:35 +0100850
Lai Jiangshan6b123c32021-12-16 10:19:37 +0800851 /*
852 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
853 * Shadow page roots need to be reconstructed instead.
854 */
855 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
856 kvm_mmu_free_roots(vcpu, mmu, KVM_MMU_ROOT_CURRENT);
857
Paolo Bonzini46cbc042021-12-10 18:13:37 -0500858 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
859 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
860 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
Maxim Levitsky158a48e2021-06-07 12:02:03 +0300861 vcpu->arch.pdptrs_from_userspace = false;
862
Sean Christopherson15cabbc2021-08-31 09:42:23 -0700863 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +0100864}
Joerg Roedelcc4b6872008-02-07 13:47:43 +0100865EXPORT_SYMBOL_GPL(load_pdptrs);
Carsten Ottea03490e2007-10-29 16:09:35 +0100866
Tom Lendackyf27ad382020-12-10 11:09:56 -0600867void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
868{
Tom Lendackyf27ad382020-12-10 11:09:56 -0600869 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
870 kvm_clear_async_pf_completion_queue(vcpu);
871 kvm_async_pf_hash_reset(vcpu);
872 }
873
Sean Christopherson20f632b2021-06-22 10:57:02 -0700874 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
Tom Lendackyf27ad382020-12-10 11:09:56 -0600875 kvm_mmu_reset_context(vcpu);
876
877 if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
878 kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
879 !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
880 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
881}
882EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
883
Avi Kivity49a9b072010-06-10 17:02:14 +0300884int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
Carsten Ottea03490e2007-10-29 16:09:35 +0100885{
Sheng Yangaad82702010-05-12 16:40:42 +0800886 unsigned long old_cr0 = kvm_read_cr0(vcpu);
Sheng Yangaad82702010-05-12 16:40:42 +0800887
Avi Kivityf9a48e62010-01-06 19:10:22 +0200888 cr0 |= X86_CR0_ET;
889
Gleb Natapovab344822010-01-21 15:28:46 +0200890#ifdef CONFIG_X86_64
Gleb Natapov0f122442010-04-28 19:15:31 +0300891 if (cr0 & 0xffffffff00000000UL)
892 return 1;
Gleb Natapovab344822010-01-21 15:28:46 +0200893#endif
894
895 cr0 &= ~CR0_RESERVED_BITS;
Carsten Ottea03490e2007-10-29 16:09:35 +0100896
Gleb Natapov0f122442010-04-28 19:15:31 +0300897 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
898 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +0100899
Gleb Natapov0f122442010-04-28 19:15:31 +0300900 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
901 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +0100902
Carsten Ottea03490e2007-10-29 16:09:35 +0100903#ifdef CONFIG_X86_64
Sean Christopherson05487212020-07-13 18:57:32 -0700904 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
905 (cr0 & X86_CR0_PG)) {
906 int cs_db, cs_l;
Carsten Ottea03490e2007-10-29 16:09:35 +0100907
Sean Christopherson05487212020-07-13 18:57:32 -0700908 if (!is_pae(vcpu))
909 return 1;
Jason Baronb36464772021-01-14 22:27:56 -0500910 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
Sean Christopherson05487212020-07-13 18:57:32 -0700911 if (cs_l)
Gleb Natapov0f122442010-04-28 19:15:31 +0300912 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +0100913 }
Sean Christopherson05487212020-07-13 18:57:32 -0700914#endif
915 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
Lai Jiangshane63f3152021-11-08 20:43:58 +0800916 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +0800917 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
Sean Christopherson05487212020-07-13 18:57:32 -0700918 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +0100919
Lai Jiangshan777ab822021-12-07 17:52:30 +0800920 if (!(cr0 & X86_CR0_PG) &&
921 (is_64_bit_mode(vcpu) || kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)))
Mao, Junjiead756a12012-07-02 01:18:48 +0000922 return 1;
923
Jason Baronb36464772021-01-14 22:27:56 -0500924 static_call(kvm_x86_set_cr0)(vcpu, cr0);
Carsten Ottea03490e2007-10-29 16:09:35 +0100925
Tom Lendackyf27ad382020-12-10 11:09:56 -0600926 kvm_post_set_cr0(vcpu, old_cr0, cr0);
Xiao Guangrongb18d5432015-06-15 16:55:21 +0800927
Gleb Natapov0f122442010-04-28 19:15:31 +0300928 return 0;
929}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +0200930EXPORT_SYMBOL_GPL(kvm_set_cr0);
Carsten Ottea03490e2007-10-29 16:09:35 +0100931
Avi Kivity2d3ad1f2008-02-24 11:20:43 +0200932void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
Carsten Ottea03490e2007-10-29 16:09:35 +0100933{
Avi Kivity49a9b072010-06-10 17:02:14 +0300934 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
Carsten Ottea03490e2007-10-29 16:09:35 +0100935}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +0200936EXPORT_SYMBOL_GPL(kvm_lmsw);
Carsten Ottea03490e2007-10-29 16:09:35 +0100937
Aaron Lewis139a12c2019-10-21 16:30:25 -0700938void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
Marcelo Tosatti42bdf992013-04-15 23:30:13 -0300939{
Tom Lendacky16809ec2020-12-10 11:10:08 -0600940 if (vcpu->arch.guest_state_protected)
941 return;
942
Aaron Lewis139a12c2019-10-21 16:30:25 -0700943 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
Marcelo Tosatti42bdf992013-04-15 23:30:13 -0300944
Aaron Lewis139a12c2019-10-21 16:30:25 -0700945 if (vcpu->arch.xcr0 != host_xcr0)
946 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
947
948 if (vcpu->arch.xsaves_enabled &&
949 vcpu->arch.ia32_xss != host_xss)
950 wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
951 }
Babu Moger37486132020-05-12 18:59:06 -0500952
953 if (static_cpu_has(X86_FEATURE_PKU) &&
954 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
955 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU)) &&
956 vcpu->arch.pkru != vcpu->arch.host_pkru)
Thomas Gleixner72a6c082021-06-23 14:02:23 +0200957 write_pkru(vcpu->arch.pkru);
Marcelo Tosatti42bdf992013-04-15 23:30:13 -0300958}
Aaron Lewis139a12c2019-10-21 16:30:25 -0700959EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
960
961void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
962{
Tom Lendacky16809ec2020-12-10 11:10:08 -0600963 if (vcpu->arch.guest_state_protected)
964 return;
965
Babu Moger37486132020-05-12 18:59:06 -0500966 if (static_cpu_has(X86_FEATURE_PKU) &&
967 (kvm_read_cr4_bits(vcpu, X86_CR4_PKE) ||
968 (vcpu->arch.xcr0 & XFEATURE_MASK_PKRU))) {
969 vcpu->arch.pkru = rdpkru();
970 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
Thomas Gleixner72a6c082021-06-23 14:02:23 +0200971 write_pkru(vcpu->arch.host_pkru);
Babu Moger37486132020-05-12 18:59:06 -0500972 }
973
Aaron Lewis139a12c2019-10-21 16:30:25 -0700974 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
975
976 if (vcpu->arch.xcr0 != host_xcr0)
977 xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
978
979 if (vcpu->arch.xsaves_enabled &&
980 vcpu->arch.ia32_xss != host_xss)
981 wrmsrl(MSR_IA32_XSS, host_xss);
982 }
983
984}
985EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
Marcelo Tosatti42bdf992013-04-15 23:30:13 -0300986
Fengguang Wu69b00492015-01-19 22:33:39 +0800987static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
Dexuan Cui2acf9232010-06-10 11:27:12 +0800988{
Liu, Jinsong56c103e2014-02-21 17:39:02 +0000989 u64 xcr0 = xcr;
990 u64 old_xcr0 = vcpu->arch.xcr0;
Paolo Bonzini46c34cb2013-10-17 16:50:46 +0200991 u64 valid_bits;
Dexuan Cui2acf9232010-06-10 11:27:12 +0800992
993 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
994 if (index != XCR_XFEATURE_ENABLED_MASK)
995 return 1;
Dave Hansend91cab72015-09-02 16:31:26 -0700996 if (!(xcr0 & XFEATURE_MASK_FP))
Dexuan Cui2acf9232010-06-10 11:27:12 +0800997 return 1;
Dave Hansend91cab72015-09-02 16:31:26 -0700998 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
Dexuan Cui2acf9232010-06-10 11:27:12 +0800999 return 1;
Paolo Bonzini46c34cb2013-10-17 16:50:46 +02001000
1001 /*
1002 * Do not allow the guest to set bits that we do not support
1003 * saving. However, xcr0 bit 0 is always set, even if the
Sean Christophersone8f65b92021-09-20 17:02:58 -07001004 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
Paolo Bonzini46c34cb2013-10-17 16:50:46 +02001005 */
Dave Hansend91cab72015-09-02 16:31:26 -07001006 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
Paolo Bonzini46c34cb2013-10-17 16:50:46 +02001007 if (xcr0 & ~valid_bits)
Dexuan Cui2acf9232010-06-10 11:27:12 +08001008 return 1;
Paolo Bonzini46c34cb2013-10-17 16:50:46 +02001009
Dave Hansend91cab72015-09-02 16:31:26 -07001010 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1011 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
Liu, Jinsong390bd522014-02-24 10:58:09 +00001012 return 1;
1013
Dave Hansend91cab72015-09-02 16:31:26 -07001014 if (xcr0 & XFEATURE_MASK_AVX512) {
1015 if (!(xcr0 & XFEATURE_MASK_YMM))
Chao Peng612263b2014-10-22 17:35:24 +08001016 return 1;
Dave Hansend91cab72015-09-02 16:31:26 -07001017 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
Chao Peng612263b2014-10-22 17:35:24 +08001018 return 1;
1019 }
Jing Liu86aff7a42022-01-05 04:35:26 -08001020
1021 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1022 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1023 return 1;
1024
Dexuan Cui2acf9232010-06-10 11:27:12 +08001025 vcpu->arch.xcr0 = xcr0;
Liu, Jinsong56c103e2014-02-21 17:39:02 +00001026
Dave Hansend91cab72015-09-02 16:31:26 -07001027 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
Xiaoyao Liaedbaf42020-07-09 12:34:23 +08001028 kvm_update_cpuid_runtime(vcpu);
Dexuan Cui2acf9232010-06-10 11:27:12 +08001029 return 0;
1030}
1031
Sean Christopherson92f98952021-02-04 16:57:46 -08001032int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
Dexuan Cui2acf9232010-06-10 11:27:12 +08001033{
Sean Christopherson92f98952021-02-04 16:57:46 -08001034 if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
1035 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1036 kvm_inject_gp(vcpu, 0);
1037 return 1;
1038 }
Paolo Bonzinibbefd4f2020-12-14 07:49:54 -05001039
Sean Christopherson92f98952021-02-04 16:57:46 -08001040 return kvm_skip_emulated_instruction(vcpu);
Dexuan Cui2acf9232010-06-10 11:27:12 +08001041}
Sean Christopherson92f98952021-02-04 16:57:46 -08001042EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
Dexuan Cui2acf9232010-06-10 11:27:12 +08001043
Sean Christophersonee69c922020-10-06 18:44:16 -07001044bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
Wanpeng Li3ca94192019-09-18 17:50:10 +08001045{
Sean Christophersonb11306b2019-12-10 14:44:13 -08001046 if (cr4 & cr4_reserved_bits)
Sean Christophersonee69c922020-10-06 18:44:16 -07001047 return false;
Wanpeng Li3ca94192019-09-18 17:50:10 +08001048
Krish Sadhukhanb899c132020-07-08 00:39:55 +00001049 if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
Sean Christophersonee69c922020-10-06 18:44:16 -07001050 return false;
Wanpeng Li3ca94192019-09-18 17:50:10 +08001051
Jason Baronb36464772021-01-14 22:27:56 -05001052 return static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
Wanpeng Li3ca94192019-09-18 17:50:10 +08001053}
Sean Christophersonee69c922020-10-06 18:44:16 -07001054EXPORT_SYMBOL_GPL(kvm_is_valid_cr4);
Wanpeng Li3ca94192019-09-18 17:50:10 +08001055
Tom Lendacky5b51cb12020-12-10 11:09:57 -06001056void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1057{
Lai Jiangshan509bfe32021-10-19 19:01:52 +08001058 /*
1059 * If any role bit is changed, the MMU needs to be reset.
1060 *
1061 * If CR4.PCIDE is changed 1 -> 0, the guest TLB must be flushed.
1062 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1063 * according to the SDM; however, stale prev_roots could be reused
1064 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1065 * free them all. KVM_REQ_MMU_RELOAD is fit for the both cases; it
1066 * is slow, but changing CR4.PCIDE is a rare case.
1067 *
1068 * If CR4.PGE is changed, the guest TLB must be flushed.
1069 *
1070 * Note: resetting MMU is a superset of KVM_REQ_MMU_RELOAD and
1071 * KVM_REQ_MMU_RELOAD is a superset of KVM_REQ_TLB_FLUSH_GUEST, hence
1072 * the usage of "else if".
1073 */
Lai Jiangshan55261732021-09-19 10:42:45 +08001074 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
Tom Lendacky5b51cb12020-12-10 11:09:57 -06001075 kvm_mmu_reset_context(vcpu);
Lai Jiangshan509bfe32021-10-19 19:01:52 +08001076 else if ((cr4 ^ old_cr4) & X86_CR4_PCIDE)
1077 kvm_make_request(KVM_REQ_MMU_RELOAD, vcpu);
1078 else if ((cr4 ^ old_cr4) & X86_CR4_PGE)
Lai Jiangshan55261732021-09-19 10:42:45 +08001079 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
Tom Lendacky5b51cb12020-12-10 11:09:57 -06001080}
1081EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
Dexuan Cui2acf9232010-06-10 11:27:12 +08001082
Avi Kivitya83b29c2010-06-10 17:02:15 +03001083int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
Carsten Ottea03490e2007-10-29 16:09:35 +01001084{
Avi Kivityfc78f512009-12-07 12:16:48 +02001085 unsigned long old_cr4 = kvm_read_cr4(vcpu);
Xiao Guangrong0be02262015-05-11 22:55:21 +08001086
Sean Christophersonee69c922020-10-06 18:44:16 -07001087 if (!kvm_is_valid_cr4(vcpu, cr4))
Paolo Bonziniae3e61e2016-07-12 10:36:41 +02001088 return 1;
1089
Carsten Ottea03490e2007-10-29 16:09:35 +01001090 if (is_long_mode(vcpu)) {
Gleb Natapov0f122442010-04-28 19:15:31 +03001091 if (!(cr4 & X86_CR4_PAE))
1092 return 1;
Sean Christophersond74fcfc2020-07-02 19:17:14 -07001093 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1094 return 1;
Avi Kivitya2edf572009-05-24 22:19:00 +03001095 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
Lai Jiangshana37ebdc2021-11-08 20:43:57 +08001096 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +08001097 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
Gleb Natapov0f122442010-04-28 19:15:31 +03001098 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +01001099
Mao, Junjiead756a12012-07-02 01:18:48 +00001100 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
Radim Krčmářd6321d42017-08-05 00:12:49 +02001101 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
Mao, Junjiead756a12012-07-02 01:18:48 +00001102 return 1;
1103
1104 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1105 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1106 return 1;
1107 }
1108
Jason Baronb36464772021-01-14 22:27:56 -05001109 static_call(kvm_x86_set_cr4)(vcpu, cr4);
Gleb Natapov0f122442010-04-28 19:15:31 +03001110
Tom Lendacky5b51cb12020-12-10 11:09:57 -06001111 kvm_post_set_cr4(vcpu, old_cr4, cr4);
Dexuan Cui2acf9232010-06-10 11:27:12 +08001112
Gleb Natapov0f122442010-04-28 19:15:31 +03001113 return 0;
1114}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02001115EXPORT_SYMBOL_GPL(kvm_set_cr4);
Carsten Ottea03490e2007-10-29 16:09:35 +01001116
Sean Christopherson21823fb2021-06-09 16:42:24 -07001117static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1118{
1119 struct kvm_mmu *mmu = vcpu->arch.mmu;
1120 unsigned long roots_to_free = 0;
1121 int i;
1122
1123 /*
Lai Jiangshane45e9e32021-10-19 19:01:51 +08001124 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1125 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1126 * also via the emulator. KVM's TDP page tables are not in the scope of
1127 * the invalidation, but the guest's TLB entries need to be flushed as
1128 * the CPU may have cached entries in its TLB for the target PCID.
1129 */
1130 if (unlikely(tdp_enabled)) {
1131 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1132 return;
1133 }
1134
1135 /*
Sean Christopherson21823fb2021-06-09 16:42:24 -07001136 * If neither the current CR3 nor any of the prev_roots use the given
1137 * PCID, then nothing needs to be done here because a resync will
1138 * happen anyway before switching to any other CR3.
1139 */
1140 if (kvm_get_active_pcid(vcpu) == pcid) {
Sean Christophersone62f1aa2021-06-09 16:42:32 -07001141 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
Sean Christopherson21823fb2021-06-09 16:42:24 -07001142 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1143 }
1144
Lai Jiangshan509bfe32021-10-19 19:01:52 +08001145 /*
1146 * If PCID is disabled, there is no need to free prev_roots even if the
1147 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1148 * with PCIDE=0.
1149 */
1150 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
1151 return;
1152
Sean Christopherson21823fb2021-06-09 16:42:24 -07001153 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1154 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1155 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1156
1157 kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
1158}
1159
Avi Kivity23902182010-06-10 17:02:16 +03001160int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
Carsten Ottea03490e2007-10-29 16:09:35 +01001161{
Junaid Shahidade61e22018-06-27 14:59:15 -07001162 bool skip_tlb_flush = false;
Sean Christopherson21823fb2021-06-09 16:42:24 -07001163 unsigned long pcid = 0;
Paolo Bonziniac146232014-11-10 13:53:25 +01001164#ifdef CONFIG_X86_64
Junaid Shahidc19986f2018-05-04 11:37:13 -07001165 bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
1166
Junaid Shahidade61e22018-06-27 14:59:15 -07001167 if (pcid_enabled) {
Junaid Shahid208320b2018-06-27 14:59:21 -07001168 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1169 cr3 &= ~X86_CR3_PCID_NOFLUSH;
Sean Christopherson21823fb2021-06-09 16:42:24 -07001170 pcid = cr3 & X86_CR3_PCID_MASK;
Junaid Shahidade61e22018-06-27 14:59:15 -07001171 }
Paolo Bonziniac146232014-11-10 13:53:25 +01001172#endif
Nadav Amit9d88fca2014-11-02 11:54:52 +02001173
Sean Christophersonc7313152021-06-07 12:01:58 +03001174 /* PDPTRs are always reloaded for PAE paging. */
Sean Christopherson21823fb2021-06-09 16:42:24 -07001175 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1176 goto handle_tlb_flush;
Avi Kivityd835dfe2007-11-21 02:57:59 +02001177
Sean Christopherson886bbcc2021-04-21 19:21:21 -07001178 /*
1179 * Do not condition the GPA check on long mode, this helper is used to
1180 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1181 * the current vCPU mode is accurate.
1182 */
1183 if (kvm_vcpu_is_illegal_gpa(vcpu, cr3))
Yu Zhangd1cd3ce2017-08-24 20:27:53 +08001184 return 1;
Sean Christopherson886bbcc2021-04-21 19:21:21 -07001185
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +08001186 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
Nadav Amit346874c2014-04-18 03:35:09 +03001187 return 1;
Carsten Ottea03490e2007-10-29 16:09:35 +01001188
Sean Christopherson21823fb2021-06-09 16:42:24 -07001189 if (cr3 != kvm_read_cr3(vcpu))
Sean Christophersonb5129102021-06-09 16:42:27 -07001190 kvm_mmu_new_pgd(vcpu, cr3);
Sean Christopherson21823fb2021-06-09 16:42:24 -07001191
Gleb Natapov0f122442010-04-28 19:15:31 +03001192 vcpu->arch.cr3 = cr3;
Lai Jiangshan3883bc9d2021-11-08 20:44:02 +08001193 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
Michael Roth405329f2021-12-16 11:13:54 -06001194 /* Do not call post_set_cr3, we do not get here for confidential guests. */
Junaid Shahid7c390d32018-06-27 14:59:06 -07001195
Sean Christopherson21823fb2021-06-09 16:42:24 -07001196handle_tlb_flush:
1197 /*
1198 * A load of CR3 that flushes the TLB flushes only the current PCID,
1199 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1200 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1201 * and it's impossible to use a non-zero PCID when PCID is disabled,
1202 * i.e. only PCID=0 can be relevant.
1203 */
1204 if (!skip_tlb_flush)
1205 kvm_invalidate_pcid(vcpu, pcid);
1206
Gleb Natapov0f122442010-04-28 19:15:31 +03001207 return 0;
1208}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02001209EXPORT_SYMBOL_GPL(kvm_set_cr3);
Carsten Ottea03490e2007-10-29 16:09:35 +01001210
Andre Przywaraeea1cff2010-12-21 11:12:00 +01001211int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
Carsten Ottea03490e2007-10-29 16:09:35 +01001212{
Gleb Natapov0f122442010-04-28 19:15:31 +03001213 if (cr8 & CR8_RESERVED_BITS)
1214 return 1;
Paolo Bonzini35754c92015-07-29 12:05:37 +02001215 if (lapic_in_kernel(vcpu))
Carsten Ottea03490e2007-10-29 16:09:35 +01001216 kvm_lapic_set_tpr(vcpu, cr8);
1217 else
Zhang Xiantaoad312c72007-12-13 23:50:52 +08001218 vcpu->arch.cr8 = cr8;
Gleb Natapov0f122442010-04-28 19:15:31 +03001219 return 0;
1220}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02001221EXPORT_SYMBOL_GPL(kvm_set_cr8);
Carsten Ottea03490e2007-10-29 16:09:35 +01001222
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02001223unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
Carsten Ottea03490e2007-10-29 16:09:35 +01001224{
Paolo Bonzini35754c92015-07-29 12:05:37 +02001225 if (lapic_in_kernel(vcpu))
Carsten Ottea03490e2007-10-29 16:09:35 +01001226 return kvm_lapic_get_cr8(vcpu);
1227 else
Zhang Xiantaoad312c72007-12-13 23:50:52 +08001228 return vcpu->arch.cr8;
Carsten Ottea03490e2007-10-29 16:09:35 +01001229}
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02001230EXPORT_SYMBOL_GPL(kvm_get_cr8);
Carsten Ottea03490e2007-10-29 16:09:35 +01001231
Nadav Amitae561ed2015-04-02 03:10:37 +03001232static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1233{
1234 int i;
1235
1236 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1237 for (i = 0; i < KVM_NR_DB_REGS; i++)
1238 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
Nadav Amitae561ed2015-04-02 03:10:37 +03001239 }
1240}
1241
Paolo Bonzini7c866632020-05-16 08:42:28 -04001242void kvm_update_dr7(struct kvm_vcpu *vcpu)
Jan Kiszkac8639012012-09-21 05:42:55 +02001243{
1244 unsigned long dr7;
1245
1246 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1247 dr7 = vcpu->arch.guest_debug_dr7;
1248 else
1249 dr7 = vcpu->arch.dr7;
Jason Baronb36464772021-01-14 22:27:56 -05001250 static_call(kvm_x86_set_dr7)(vcpu, dr7);
Paolo Bonzini360b9482014-02-21 09:55:56 +01001251 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1252 if (dr7 & DR7_BP_EN_MASK)
1253 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
Jan Kiszkac8639012012-09-21 05:42:55 +02001254}
Paolo Bonzini7c866632020-05-16 08:42:28 -04001255EXPORT_SYMBOL_GPL(kvm_update_dr7);
Jan Kiszkac8639012012-09-21 05:42:55 +02001256
Nadav Amit6f43ed02014-07-15 17:37:46 +03001257static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1258{
1259 u64 fixed = DR6_FIXED_1;
1260
Radim Krčmářd6321d42017-08-05 00:12:49 +02001261 if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
Nadav Amit6f43ed02014-07-15 17:37:46 +03001262 fixed |= DR6_RTM;
Chenyi Qiange8ea85f2021-02-02 17:04:32 +08001263
1264 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1265 fixed |= DR6_BUS_LOCK;
Nadav Amit6f43ed02014-07-15 17:37:46 +03001266 return fixed;
1267}
1268
Paolo Bonzini996ff542020-12-14 07:49:54 -05001269int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
Gleb Natapov020df072010-04-13 10:05:23 +03001270{
Marios Pomonisea740052019-12-11 12:47:52 -08001271 size_t size = ARRAY_SIZE(vcpu->arch.db);
1272
Gleb Natapov020df072010-04-13 10:05:23 +03001273 switch (dr) {
1274 case 0 ... 3:
Marios Pomonisea740052019-12-11 12:47:52 -08001275 vcpu->arch.db[array_index_nospec(dr, size)] = val;
Gleb Natapov020df072010-04-13 10:05:23 +03001276 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1277 vcpu->arch.eff_db[dr] = val;
1278 break;
1279 case 4:
Gleb Natapov020df072010-04-13 10:05:23 +03001280 case 6:
Krish Sadhukhanf5f61452020-05-22 18:19:51 -04001281 if (!kvm_dr6_valid(val))
Paolo Bonzini996ff542020-12-14 07:49:54 -05001282 return 1; /* #GP */
Nadav Amit6f43ed02014-07-15 17:37:46 +03001283 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
Gleb Natapov020df072010-04-13 10:05:23 +03001284 break;
1285 case 5:
Gleb Natapov020df072010-04-13 10:05:23 +03001286 default: /* 7 */
Krish Sadhukhanb91991b2020-01-15 19:54:32 -05001287 if (!kvm_dr7_valid(val))
Paolo Bonzini996ff542020-12-14 07:49:54 -05001288 return 1; /* #GP */
Gleb Natapov020df072010-04-13 10:05:23 +03001289 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
Jan Kiszkac8639012012-09-21 05:42:55 +02001290 kvm_update_dr7(vcpu);
Gleb Natapov020df072010-04-13 10:05:23 +03001291 break;
1292 }
1293
1294 return 0;
1295}
1296EXPORT_SYMBOL_GPL(kvm_set_dr);
1297
Paolo Bonzini29d6ca42021-02-03 03:42:41 -05001298void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
Gleb Natapov020df072010-04-13 10:05:23 +03001299{
Marios Pomonisea740052019-12-11 12:47:52 -08001300 size_t size = ARRAY_SIZE(vcpu->arch.db);
1301
Gleb Natapov020df072010-04-13 10:05:23 +03001302 switch (dr) {
1303 case 0 ... 3:
Marios Pomonisea740052019-12-11 12:47:52 -08001304 *val = vcpu->arch.db[array_index_nospec(dr, size)];
Gleb Natapov020df072010-04-13 10:05:23 +03001305 break;
1306 case 4:
Gleb Natapov020df072010-04-13 10:05:23 +03001307 case 6:
Paolo Bonzini5679b802020-05-04 11:28:25 -04001308 *val = vcpu->arch.dr6;
Gleb Natapov020df072010-04-13 10:05:23 +03001309 break;
1310 case 5:
Gleb Natapov020df072010-04-13 10:05:23 +03001311 default: /* 7 */
1312 *val = vcpu->arch.dr7;
1313 break;
1314 }
Gleb Natapov338dbc92010-04-28 19:15:32 +03001315}
Gleb Natapov020df072010-04-13 10:05:23 +03001316EXPORT_SYMBOL_GPL(kvm_get_dr);
1317
Sean Christophersonc483c452021-02-04 16:57:48 -08001318int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
Avi Kivity022cd0e2011-11-10 14:57:23 +02001319{
Sean Christophersonde3cd112019-04-30 10:36:17 -07001320 u32 ecx = kvm_rcx_read(vcpu);
Avi Kivity022cd0e2011-11-10 14:57:23 +02001321 u64 data;
Avi Kivity022cd0e2011-11-10 14:57:23 +02001322
Sean Christophersonc483c452021-02-04 16:57:48 -08001323 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1324 kvm_inject_gp(vcpu, 0);
1325 return 1;
1326 }
1327
Sean Christophersonde3cd112019-04-30 10:36:17 -07001328 kvm_rax_write(vcpu, (u32)data);
1329 kvm_rdx_write(vcpu, data >> 32);
Sean Christophersonc483c452021-02-04 16:57:48 -08001330 return kvm_skip_emulated_instruction(vcpu);
Avi Kivity022cd0e2011-11-10 14:57:23 +02001331}
Sean Christophersonc483c452021-02-04 16:57:48 -08001332EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
Avi Kivity022cd0e2011-11-10 14:57:23 +02001333
Carsten Otte043405e2007-10-10 17:16:19 +02001334/*
1335 * List of msr numbers which we expose to userspace through KVM_GET_MSRS
1336 * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
1337 *
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001338 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
1339 * extract the supported MSRs from the related const lists.
1340 * msrs_to_save is selected from the msrs_to_save_all to reflect the
Glauber Costae3267cb2009-10-06 13:24:50 -04001341 * capabilities of the host cpu. This capabilities test skips MSRs that are
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001342 * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02001343 * may depend on host virtualization features rather than host cpu features.
Carsten Otte043405e2007-10-10 17:16:19 +02001344 */
Glauber Costae3267cb2009-10-06 13:24:50 -04001345
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001346static const u32 msrs_to_save_all[] = {
Carsten Otte043405e2007-10-10 17:16:19 +02001347 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
Brian Gerst8c065852010-07-17 09:03:26 -04001348 MSR_STAR,
Carsten Otte043405e2007-10-10 17:16:19 +02001349#ifdef CONFIG_X86_64
1350 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1351#endif
Nadav Har'Elb3897a42013-07-08 19:12:35 +08001352 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
Sean Christopherson32ad73d2019-12-20 20:44:55 -08001353 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
Xiaoyao Li2bdb76c2019-03-08 15:57:20 +08001354 MSR_IA32_SPEC_CTRL,
Chao Pengbf8c55d2018-10-24 16:05:14 +08001355 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
1356 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
1357 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
1358 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
1359 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
1360 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
Tao Xu6e3ba4a2019-07-16 14:55:50 +08001361 MSR_IA32_UMWAIT_CONTROL,
1362
Jim Mattsone2ada662019-08-21 11:20:04 -07001363 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
Wei Wang9fb12fe2021-12-17 07:49:34 -05001364 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
Jim Mattsone2ada662019-08-21 11:20:04 -07001365 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
1366 MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1367 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
1368 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
1369 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
1370 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
1371 MSR_ARCH_PERFMON_PERFCTR0 + 8, MSR_ARCH_PERFMON_PERFCTR0 + 9,
1372 MSR_ARCH_PERFMON_PERFCTR0 + 10, MSR_ARCH_PERFMON_PERFCTR0 + 11,
1373 MSR_ARCH_PERFMON_PERFCTR0 + 12, MSR_ARCH_PERFMON_PERFCTR0 + 13,
1374 MSR_ARCH_PERFMON_PERFCTR0 + 14, MSR_ARCH_PERFMON_PERFCTR0 + 15,
1375 MSR_ARCH_PERFMON_PERFCTR0 + 16, MSR_ARCH_PERFMON_PERFCTR0 + 17,
Jim Mattsone2ada662019-08-21 11:20:04 -07001376 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
1377 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
1378 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
1379 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
1380 MSR_ARCH_PERFMON_EVENTSEL0 + 8, MSR_ARCH_PERFMON_EVENTSEL0 + 9,
1381 MSR_ARCH_PERFMON_EVENTSEL0 + 10, MSR_ARCH_PERFMON_EVENTSEL0 + 11,
1382 MSR_ARCH_PERFMON_EVENTSEL0 + 12, MSR_ARCH_PERFMON_EVENTSEL0 + 13,
1383 MSR_ARCH_PERFMON_EVENTSEL0 + 14, MSR_ARCH_PERFMON_EVENTSEL0 + 15,
1384 MSR_ARCH_PERFMON_EVENTSEL0 + 16, MSR_ARCH_PERFMON_EVENTSEL0 + 17,
Fares Mehannae1fc1552021-09-15 13:39:50 +00001385
1386 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
1387 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
1388 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
1389 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
1390 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
1391 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
Jing Liu548e8362022-01-05 04:35:24 -08001392 MSR_IA32_XFD, MSR_IA32_XFD_ERR,
Carsten Otte043405e2007-10-10 17:16:19 +02001393};
1394
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001395static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
Carsten Otte043405e2007-10-10 17:16:19 +02001396static unsigned num_msrs_to_save;
1397
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001398static const u32 emulated_msrs_all[] = {
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02001399 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1400 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1401 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1402 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
Ladi Prosek72c139b2017-07-26 13:32:59 +02001403 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
Andrey Smetanine7d95132015-07-03 15:01:37 +03001404 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1405 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
Andrey Smetanine516ceb2015-09-16 12:29:48 +03001406 HV_X64_MSR_RESET,
Andrey Smetanin11c4b1c2015-09-16 12:29:49 +03001407 HV_X64_MSR_VP_INDEX,
Andrey Smetanin9eec50b2015-09-16 12:29:50 +03001408 HV_X64_MSR_VP_RUNTIME,
Andrey Smetanin5c9194122015-11-10 15:36:34 +03001409 HV_X64_MSR_SCONTROL,
Andrey Smetanin1f4b34f2015-11-30 19:22:21 +03001410 HV_X64_MSR_STIMER0_CONFIG,
Ladi Prosekd4abc572018-03-20 15:02:07 +01001411 HV_X64_MSR_VP_ASSIST_PAGE,
Vitaly Kuznetsova2e164e2018-03-01 15:15:12 +01001412 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
1413 HV_X64_MSR_TSC_EMULATION_STATUS,
Jon Doronf97f5a52020-05-29 16:45:40 +03001414 HV_X64_MSR_SYNDBG_OPTIONS,
1415 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
1416 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
1417 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
Vitaly Kuznetsova2e164e2018-03-01 15:15:12 +01001418
1419 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02001420 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02001421
Will Auldba904632012-11-29 12:42:50 -08001422 MSR_IA32_TSC_ADJUST,
Dave Hansen09141ec2020-03-05 09:47:06 -08001423 MSR_IA32_TSC_DEADLINE,
Xiaoyao Li2bdb76c2019-03-08 15:57:20 +08001424 MSR_IA32_ARCH_CAPABILITIES,
Like Xu27461da32020-05-29 15:43:45 +08001425 MSR_IA32_PERF_CAPABILITIES,
Carsten Otte043405e2007-10-10 17:16:19 +02001426 MSR_IA32_MISC_ENABLE,
Avi Kivity908e75f2010-07-07 14:09:38 +03001427 MSR_IA32_MCG_STATUS,
1428 MSR_IA32_MCG_CTL,
Ashok Rajc45dcc72016-06-22 14:59:56 +08001429 MSR_IA32_MCG_EXT_CTL,
Paolo Bonzini64d60672015-05-07 11:36:11 +02001430 MSR_IA32_SMBASE,
Liran Alon52797bf2017-11-15 13:43:14 +02001431 MSR_SMI_COUNT,
Kyle Hueydb2336a2017-03-20 01:16:28 -07001432 MSR_PLATFORM_INFO,
1433 MSR_MISC_FEATURES_ENABLES,
Tom Lendackybc226f02018-05-10 22:06:39 +02001434 MSR_AMD64_VIRT_SPEC_CTRL,
Maxim Levitsky5228eb92021-09-14 18:48:24 +03001435 MSR_AMD64_TSC_RATIO,
Liran Alon6c6a2ab2019-04-15 18:45:26 +03001436 MSR_IA32_POWER_CTL,
Paolo Bonzini99634e32020-01-20 14:22:55 +01001437 MSR_IA32_UCODE_REV,
Borislav Petkov191c8132019-04-18 18:32:50 +02001438
Paolo Bonzini95c5c7c2019-07-02 14:45:24 +02001439 /*
1440 * The following list leaves out MSRs whose values are determined
1441 * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
1442 * We always support the "true" VMX control MSRs, even if the host
1443 * processor does not, so I am putting these registers here rather
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001444 * than in msrs_to_save_all.
Paolo Bonzini95c5c7c2019-07-02 14:45:24 +02001445 */
1446 MSR_IA32_VMX_BASIC,
1447 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1448 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1449 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1450 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1451 MSR_IA32_VMX_MISC,
1452 MSR_IA32_VMX_CR0_FIXED0,
1453 MSR_IA32_VMX_CR4_FIXED0,
1454 MSR_IA32_VMX_VMCS_ENUM,
1455 MSR_IA32_VMX_PROCBASED_CTLS2,
1456 MSR_IA32_VMX_EPT_VPID_CAP,
1457 MSR_IA32_VMX_VMFUNC,
1458
Borislav Petkov191c8132019-04-18 18:32:50 +02001459 MSR_K7_HWCR,
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -03001460 MSR_KVM_POLL_CONTROL,
Carsten Otte043405e2007-10-10 17:16:19 +02001461};
1462
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001463static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02001464static unsigned num_emulated_msrs;
1465
Tom Lendacky801e4592018-02-21 13:39:51 -06001466/*
1467 * List of msr numbers which are used to expose MSR-based features that
1468 * can be used by a hypervisor to validate requested CPU features.
1469 */
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001470static const u32 msr_based_features_all[] = {
Paolo Bonzini13893092018-02-26 13:40:09 +01001471 MSR_IA32_VMX_BASIC,
1472 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
1473 MSR_IA32_VMX_PINBASED_CTLS,
1474 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
1475 MSR_IA32_VMX_PROCBASED_CTLS,
1476 MSR_IA32_VMX_TRUE_EXIT_CTLS,
1477 MSR_IA32_VMX_EXIT_CTLS,
1478 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
1479 MSR_IA32_VMX_ENTRY_CTLS,
1480 MSR_IA32_VMX_MISC,
1481 MSR_IA32_VMX_CR0_FIXED0,
1482 MSR_IA32_VMX_CR0_FIXED1,
1483 MSR_IA32_VMX_CR4_FIXED0,
1484 MSR_IA32_VMX_CR4_FIXED1,
1485 MSR_IA32_VMX_VMCS_ENUM,
1486 MSR_IA32_VMX_PROCBASED_CTLS2,
1487 MSR_IA32_VMX_EPT_VPID_CAP,
1488 MSR_IA32_VMX_VMFUNC,
1489
Tom Lendackyd1d93fa2018-02-24 00:18:20 +01001490 MSR_F10H_DECFG,
Wanpeng Li518e7b92018-02-28 14:03:31 +08001491 MSR_IA32_UCODE_REV,
Paolo Bonzinicd283252018-06-25 14:04:37 +02001492 MSR_IA32_ARCH_CAPABILITIES,
Like Xu27461da32020-05-29 15:43:45 +08001493 MSR_IA32_PERF_CAPABILITIES,
Tom Lendacky801e4592018-02-21 13:39:51 -06001494};
1495
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08001496static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
Tom Lendacky801e4592018-02-21 13:39:51 -06001497static unsigned int num_msr_based_features;
1498
Xiaoyao Li4d22c172019-04-19 10:16:24 +08001499static u64 kvm_get_arch_capabilities(void)
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001500{
Xiaoyao Li4d22c172019-04-19 10:16:24 +08001501 u64 data = 0;
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001502
Xiaoyao Li4d22c172019-04-19 10:16:24 +08001503 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1504 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001505
1506 /*
Paolo Bonzinib8e8c832019-11-04 12:22:02 +01001507 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1508 * the nested hypervisor runs with NX huge pages. If it is not,
Ingo Molnard9f6e122021-03-18 15:28:01 +01001509 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
Paolo Bonzinib8e8c832019-11-04 12:22:02 +01001510 * L1 guests, so it need not worry about its own (L2) guests.
1511 */
1512 data |= ARCH_CAP_PSCHANGE_MC_NO;
1513
1514 /*
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001515 * If we're doing cache flushes (either "always" or "cond")
1516 * we will do one whenever the guest does a vmlaunch/vmresume.
1517 * If an outer hypervisor is doing the cache flush for us
1518 * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
1519 * capability to the guest too, and if EPT is disabled we're not
1520 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1521 * require a nested hypervisor to do a flush of its own.
1522 */
1523 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1524 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1525
Paolo Bonzini0c549142019-08-19 17:24:07 +02001526 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1527 data |= ARCH_CAP_RDCL_NO;
1528 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1529 data |= ARCH_CAP_SSB_NO;
1530 if (!boot_cpu_has_bug(X86_BUG_MDS))
1531 data |= ARCH_CAP_MDS_NO;
1532
Paolo Bonzini71316362021-01-28 11:45:00 -05001533 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1534 /*
1535 * If RTM=0 because the kernel has disabled TSX, the host might
1536 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1537 * and therefore knows that there cannot be TAA) but keep
1538 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1539 * and we want to allow migrating those guests to tsx=off hosts.
1540 */
1541 data &= ~ARCH_CAP_TAA_NO;
1542 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
Paolo Bonzinicbbaa272019-11-18 18:58:26 +01001543 data |= ARCH_CAP_TAA_NO;
Paolo Bonzini71316362021-01-28 11:45:00 -05001544 } else {
1545 /*
1546 * Nothing to do here; we emulate TSX_CTRL if present on the
1547 * host so the guest can choose between disabling TSX or
1548 * using VERW to clear CPU buffers.
1549 */
1550 }
Pawan Guptae1d38b62019-10-23 12:23:33 +02001551
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001552 return data;
1553}
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001554
Wanpeng Li66421c12018-02-28 14:03:30 +08001555static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
1556{
1557 switch (msr->index) {
Paolo Bonzinicd283252018-06-25 14:04:37 +02001558 case MSR_IA32_ARCH_CAPABILITIES:
Paolo Bonzini5b76a3c2018-08-05 16:07:47 +02001559 msr->data = kvm_get_arch_capabilities();
1560 break;
1561 case MSR_IA32_UCODE_REV:
Paolo Bonzinicd283252018-06-25 14:04:37 +02001562 rdmsrl_safe(msr->index, &msr->data);
Wanpeng Li518e7b92018-02-28 14:03:31 +08001563 break;
Wanpeng Li66421c12018-02-28 14:03:30 +08001564 default:
Jason Baronb36464772021-01-14 22:27:56 -05001565 return static_call(kvm_x86_get_msr_feature)(msr);
Wanpeng Li66421c12018-02-28 14:03:30 +08001566 }
1567 return 0;
1568}
1569
Tom Lendacky801e4592018-02-21 13:39:51 -06001570static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1571{
1572 struct kvm_msr_entry msr;
Wanpeng Li66421c12018-02-28 14:03:30 +08001573 int r;
Tom Lendacky801e4592018-02-21 13:39:51 -06001574
1575 msr.index = index;
Wanpeng Li66421c12018-02-28 14:03:30 +08001576 r = kvm_get_msr_feature(&msr);
Peter Xu12bc2132020-06-22 18:04:42 -04001577
1578 if (r == KVM_MSR_RET_INVALID) {
1579 /* Unconditionally clear the output for simplicity */
1580 *data = 0;
Haiwei Lid6328262021-03-13 13:10:32 +08001581 if (kvm_msr_ignored_check(index, 0, false))
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001582 r = 0;
Peter Xu12bc2132020-06-22 18:04:42 -04001583 }
1584
Wanpeng Li66421c12018-02-28 14:03:30 +08001585 if (r)
1586 return r;
Tom Lendacky801e4592018-02-21 13:39:51 -06001587
1588 *data = msr.data;
1589
1590 return 0;
1591}
1592
Sean Christopherson11988492019-04-02 08:19:15 -07001593static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1594{
1595 if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1596 return false;
1597
1598 if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1599 return false;
1600
Sean Christopherson0a629562019-04-02 08:19:16 -07001601 if (efer & (EFER_LME | EFER_LMA) &&
1602 !guest_cpuid_has(vcpu, X86_FEATURE_LM))
1603 return false;
1604
1605 if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
1606 return false;
1607
Sean Christopherson11988492019-04-02 08:19:15 -07001608 return true;
1609
1610}
Jan Kiszka384bb782013-04-20 10:52:36 +02001611bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
Carsten Otte15c4a642007-10-30 18:44:17 +01001612{
Roedel, Joergb69e8ca2010-05-06 11:38:43 +02001613 if (efer & efer_reserved_bits)
Jan Kiszka384bb782013-04-20 10:52:36 +02001614 return false;
Carsten Otte15c4a642007-10-30 18:44:17 +01001615
Sean Christopherson11988492019-04-02 08:19:15 -07001616 return __kvm_valid_efer(vcpu, efer);
Jan Kiszka384bb782013-04-20 10:52:36 +02001617}
1618EXPORT_SYMBOL_GPL(kvm_valid_efer);
1619
Sean Christopherson11988492019-04-02 08:19:15 -07001620static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Jan Kiszka384bb782013-04-20 10:52:36 +02001621{
1622 u64 old_efer = vcpu->arch.efer;
Sean Christopherson11988492019-04-02 08:19:15 -07001623 u64 efer = msr_info->data;
Maxim Levitsky72f211e2020-10-01 14:29:53 +03001624 int r;
Jan Kiszka384bb782013-04-20 10:52:36 +02001625
Sean Christopherson11988492019-04-02 08:19:15 -07001626 if (efer & efer_reserved_bits)
Paolo Bonzini66f61c92019-05-24 21:52:46 +02001627 return 1;
Jan Kiszka384bb782013-04-20 10:52:36 +02001628
Sean Christopherson11988492019-04-02 08:19:15 -07001629 if (!msr_info->host_initiated) {
1630 if (!__kvm_valid_efer(vcpu, efer))
1631 return 1;
1632
1633 if (is_paging(vcpu) &&
1634 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1635 return 1;
1636 }
Jan Kiszka384bb782013-04-20 10:52:36 +02001637
Carsten Otte15c4a642007-10-30 18:44:17 +01001638 efer &= ~EFER_LMA;
Avi Kivityf6801df2010-01-21 15:31:50 +02001639 efer |= vcpu->arch.efer & EFER_LMA;
Carsten Otte15c4a642007-10-30 18:44:17 +01001640
Jason Baronb36464772021-01-14 22:27:56 -05001641 r = static_call(kvm_x86_set_efer)(vcpu, efer);
Maxim Levitsky72f211e2020-10-01 14:29:53 +03001642 if (r) {
1643 WARN_ON(r > 0);
1644 return r;
1645 }
Sheng Yanga3d204e2010-05-12 16:40:40 +08001646
Sheng Yangaad82702010-05-12 16:40:42 +08001647 /* Update reserved bits */
1648 if ((efer ^ old_efer) & EFER_NX)
1649 kvm_mmu_reset_context(vcpu);
1650
Roedel, Joergb69e8ca2010-05-06 11:38:43 +02001651 return 0;
Carsten Otte15c4a642007-10-30 18:44:17 +01001652}
1653
Joerg Roedelf2b4b7d2008-01-31 14:57:37 +01001654void kvm_enable_efer_bits(u64 mask)
1655{
1656 efer_reserved_bits &= ~mask;
1657}
1658EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1659
Alexander Graf51de8152020-09-25 16:34:17 +02001660bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1661{
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001662 struct kvm_x86_msr_filter *msr_filter;
1663 struct msr_bitmap_range *ranges;
Alexander Graf1a1552542020-09-25 16:34:21 +02001664 struct kvm *kvm = vcpu->kvm;
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001665 bool allowed;
Alexander Graf1a1552542020-09-25 16:34:21 +02001666 int idx;
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001667 u32 i;
Alexander Graf1a1552542020-09-25 16:34:21 +02001668
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001669 /* x2APIC MSRs do not support filtering. */
1670 if (index >= 0x800 && index <= 0x8ff)
Alexander Graf1a1552542020-09-25 16:34:21 +02001671 return true;
1672
Alexander Graf1a1552542020-09-25 16:34:21 +02001673 idx = srcu_read_lock(&kvm->srcu);
1674
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001675 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1676 if (!msr_filter) {
1677 allowed = true;
1678 goto out;
1679 }
1680
1681 allowed = msr_filter->default_allow;
1682 ranges = msr_filter->ranges;
1683
1684 for (i = 0; i < msr_filter->count; i++) {
Alexander Graf1a1552542020-09-25 16:34:21 +02001685 u32 start = ranges[i].base;
1686 u32 end = start + ranges[i].nmsrs;
1687 u32 flags = ranges[i].flags;
1688 unsigned long *bitmap = ranges[i].bitmap;
1689
1690 if ((index >= start) && (index < end) && (flags & type)) {
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001691 allowed = !!test_bit(index - start, bitmap);
Alexander Graf1a1552542020-09-25 16:34:21 +02001692 break;
1693 }
1694 }
1695
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001696out:
Alexander Graf1a1552542020-09-25 16:34:21 +02001697 srcu_read_unlock(&kvm->srcu, idx);
1698
Sean Christophersonb318e8d2021-03-16 11:44:33 -07001699 return allowed;
Alexander Graf51de8152020-09-25 16:34:17 +02001700}
1701EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1702
Carsten Otte15c4a642007-10-30 18:44:17 +01001703/*
Sean Christophersonf20935d2019-09-05 14:22:54 -07001704 * Write @data into the MSR specified by @index. Select MSR specific fault
1705 * checks are bypassed if @host_initiated is %true.
Carsten Otte15c4a642007-10-30 18:44:17 +01001706 * Returns 0 on success, non-0 otherwise.
1707 * Assumes vcpu_load() was already called.
1708 */
Sean Christophersonf20935d2019-09-05 14:22:54 -07001709static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1710 bool host_initiated)
Carsten Otte15c4a642007-10-30 18:44:17 +01001711{
Sean Christophersonf20935d2019-09-05 14:22:54 -07001712 struct msr_data msr;
1713
Alexander Graf1a1552542020-09-25 16:34:21 +02001714 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001715 return KVM_MSR_RET_FILTERED;
Alexander Graf1a1552542020-09-25 16:34:21 +02001716
Sean Christophersonf20935d2019-09-05 14:22:54 -07001717 switch (index) {
Nadav Amit854e8bb2014-09-16 03:24:05 +03001718 case MSR_FS_BASE:
1719 case MSR_GS_BASE:
1720 case MSR_KERNEL_GS_BASE:
1721 case MSR_CSTAR:
1722 case MSR_LSTAR:
Sean Christophersonf20935d2019-09-05 14:22:54 -07001723 if (is_noncanonical_address(data, vcpu))
Nadav Amit854e8bb2014-09-16 03:24:05 +03001724 return 1;
1725 break;
1726 case MSR_IA32_SYSENTER_EIP:
1727 case MSR_IA32_SYSENTER_ESP:
1728 /*
1729 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1730 * non-canonical address is written on Intel but not on
1731 * AMD (which ignores the top 32-bits, because it does
1732 * not implement 64-bit SYSENTER).
1733 *
1734 * 64-bit code should hence be able to write a non-canonical
1735 * value on AMD. Making the address canonical ensures that
1736 * vmentry does not fail on Intel after writing a non-canonical
1737 * value, and that something deterministic happens if the guest
1738 * invokes 64-bit SYSENTER.
1739 */
Sean Christophersonf20935d2019-09-05 14:22:54 -07001740 data = get_canonical(data, vcpu_virt_addr_bits(vcpu));
Sean Christopherson61a05d42021-05-04 10:17:33 -07001741 break;
1742 case MSR_TSC_AUX:
1743 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1744 return 1;
1745
1746 if (!host_initiated &&
1747 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1748 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1749 return 1;
1750
1751 /*
1752 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1753 * incomplete and conflicting architectural behavior. Current
1754 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1755 * reserved and always read as zeros. Enforce Intel's reserved
1756 * bits check if and only if the guest CPU is Intel, and clear
1757 * the bits in all other cases. This ensures cross-vendor
1758 * migration will provide consistent behavior for the guest.
1759 */
1760 if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
1761 return 1;
1762
1763 data = (u32)data;
1764 break;
Nadav Amit854e8bb2014-09-16 03:24:05 +03001765 }
Sean Christophersonf20935d2019-09-05 14:22:54 -07001766
1767 msr.data = data;
1768 msr.index = index;
1769 msr.host_initiated = host_initiated;
1770
Jason Baronb36464772021-01-14 22:27:56 -05001771 return static_call(kvm_x86_set_msr)(vcpu, &msr);
Sean Christophersonf20935d2019-09-05 14:22:54 -07001772}
1773
Peter Xu6abe9c12020-06-22 18:04:41 -04001774static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1775 u32 index, u64 data, bool host_initiated)
1776{
1777 int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
1778
1779 if (ret == KVM_MSR_RET_INVALID)
Haiwei Lid6328262021-03-13 13:10:32 +08001780 if (kvm_msr_ignored_check(index, data, true))
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001781 ret = 0;
Peter Xu6abe9c12020-06-22 18:04:41 -04001782
1783 return ret;
1784}
1785
Sean Christophersonf20935d2019-09-05 14:22:54 -07001786/*
1787 * Read the MSR specified by @index into @data. Select MSR specific fault
1788 * checks are bypassed if @host_initiated is %true.
1789 * Returns 0 on success, non-0 otherwise.
1790 * Assumes vcpu_load() was already called.
1791 */
Paolo Bonziniedef5c32019-11-18 12:23:00 -05001792int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1793 bool host_initiated)
Sean Christophersonf20935d2019-09-05 14:22:54 -07001794{
1795 struct msr_data msr;
1796 int ret;
1797
Alexander Graf1a1552542020-09-25 16:34:21 +02001798 if (!host_initiated && !kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001799 return KVM_MSR_RET_FILTERED;
Alexander Graf1a1552542020-09-25 16:34:21 +02001800
Sean Christopherson61a05d42021-05-04 10:17:33 -07001801 switch (index) {
1802 case MSR_TSC_AUX:
1803 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1804 return 1;
1805
1806 if (!host_initiated &&
1807 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
1808 !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
1809 return 1;
1810 break;
1811 }
1812
Sean Christophersonf20935d2019-09-05 14:22:54 -07001813 msr.index = index;
1814 msr.host_initiated = host_initiated;
1815
Jason Baronb36464772021-01-14 22:27:56 -05001816 ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
Sean Christophersonf20935d2019-09-05 14:22:54 -07001817 if (!ret)
1818 *data = msr.data;
1819 return ret;
1820}
1821
Peter Xu6abe9c12020-06-22 18:04:41 -04001822static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1823 u32 index, u64 *data, bool host_initiated)
1824{
1825 int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
1826
1827 if (ret == KVM_MSR_RET_INVALID) {
1828 /* Unconditionally clear *data for simplicity */
1829 *data = 0;
Haiwei Lid6328262021-03-13 13:10:32 +08001830 if (kvm_msr_ignored_check(index, 0, false))
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001831 ret = 0;
Peter Xu6abe9c12020-06-22 18:04:41 -04001832 }
1833
1834 return ret;
1835}
1836
Sean Christophersonf20935d2019-09-05 14:22:54 -07001837int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1838{
Peter Xu6abe9c12020-06-22 18:04:41 -04001839 return kvm_get_msr_ignored_check(vcpu, index, data, false);
Sean Christophersonf20935d2019-09-05 14:22:54 -07001840}
1841EXPORT_SYMBOL_GPL(kvm_get_msr);
1842
1843int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1844{
Peter Xu6abe9c12020-06-22 18:04:41 -04001845 return kvm_set_msr_ignored_check(vcpu, index, data, false);
Carsten Otte15c4a642007-10-30 18:44:17 +01001846}
Nadav Amit854e8bb2014-09-16 03:24:05 +03001847EXPORT_SYMBOL_GPL(kvm_set_msr);
Carsten Otte15c4a642007-10-30 18:44:17 +01001848
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001849static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
Alexander Graf1ae09952020-09-25 16:34:16 +02001850{
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001851 if (!vcpu->run->msr.error) {
Alexander Graf1ae09952020-09-25 16:34:16 +02001852 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1853 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1854 }
Alexander Graf1ae09952020-09-25 16:34:16 +02001855}
1856
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001857static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1858{
1859 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1860}
1861
1862static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1863{
1864 complete_userspace_rdmsr(vcpu);
1865 return complete_emulated_msr_access(vcpu);
1866}
1867
1868static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
Alexander Graf1ae09952020-09-25 16:34:16 +02001869{
Jason Baronb36464772021-01-14 22:27:56 -05001870 return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
Alexander Graf1ae09952020-09-25 16:34:16 +02001871}
1872
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001873static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1874{
1875 complete_userspace_rdmsr(vcpu);
1876 return complete_fast_msr_access(vcpu);
1877}
1878
Alexander Graf1ae09952020-09-25 16:34:16 +02001879static u64 kvm_msr_reason(int r)
1880{
1881 switch (r) {
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001882 case KVM_MSR_RET_INVALID:
Alexander Graf1ae09952020-09-25 16:34:16 +02001883 return KVM_MSR_EXIT_REASON_UNKNOWN;
Maxim Levitskycc4cb012020-11-01 13:55:23 +02001884 case KVM_MSR_RET_FILTERED:
Alexander Graf1a1552542020-09-25 16:34:21 +02001885 return KVM_MSR_EXIT_REASON_FILTER;
Alexander Graf1ae09952020-09-25 16:34:16 +02001886 default:
1887 return KVM_MSR_EXIT_REASON_INVAL;
1888 }
1889}
1890
1891static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
1892 u32 exit_reason, u64 data,
1893 int (*completion)(struct kvm_vcpu *vcpu),
1894 int r)
1895{
1896 u64 msr_reason = kvm_msr_reason(r);
1897
1898 /* Check if the user wanted to know about this MSR fault */
1899 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
1900 return 0;
1901
1902 vcpu->run->exit_reason = exit_reason;
1903 vcpu->run->msr.error = 0;
1904 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
1905 vcpu->run->msr.reason = msr_reason;
1906 vcpu->run->msr.index = index;
1907 vcpu->run->msr.data = data;
1908 vcpu->arch.complete_userspace_io = completion;
1909
1910 return 1;
1911}
1912
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001913int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
1914{
1915 u32 ecx = kvm_rcx_read(vcpu);
1916 u64 data;
Alexander Graf1ae09952020-09-25 16:34:16 +02001917 int r;
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001918
Alexander Graf1ae09952020-09-25 16:34:16 +02001919 r = kvm_get_msr(vcpu, ecx, &data);
1920
Paolo Bonzini8b474422020-12-14 07:44:46 -05001921 if (!r) {
1922 trace_kvm_msr_read(ecx, data);
1923
1924 kvm_rax_write(vcpu, data & -1u);
1925 kvm_rdx_write(vcpu, (data >> 32) & -1u);
1926 } else {
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001927 /* MSR read failed? See if we should ask user space */
1928 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
1929 complete_fast_rdmsr, r))
1930 return 0;
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001931 trace_kvm_msr_read_ex(ecx);
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001932 }
1933
Jason Baronb36464772021-01-14 22:27:56 -05001934 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001935}
1936EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
1937
1938int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
1939{
1940 u32 ecx = kvm_rcx_read(vcpu);
1941 u64 data = kvm_read_edx_eax(vcpu);
Alexander Graf1ae09952020-09-25 16:34:16 +02001942 int r;
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001943
Alexander Graf1ae09952020-09-25 16:34:16 +02001944 r = kvm_set_msr(vcpu, ecx, data);
1945
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001946 if (!r) {
Paolo Bonzini8b474422020-12-14 07:44:46 -05001947 trace_kvm_msr_write(ecx, data);
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001948 } else {
1949 /* MSR write failed? See if we should ask user space */
1950 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
1951 complete_fast_msr_access, r))
1952 return 0;
1953 /* Signal all other negative errors to userspace */
1954 if (r < 0)
1955 return r;
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001956 trace_kvm_msr_write_ex(ecx, data);
Hou Wenlongd2f7d492021-11-02 17:15:31 +08001957 }
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001958
Jason Baronb36464772021-01-14 22:27:56 -05001959 return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
Sean Christopherson1edce0a2019-09-05 14:22:55 -07001960}
1961EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
1962
Sean Christopherson5ff3a352021-02-04 16:57:47 -08001963int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
1964{
1965 return kvm_skip_emulated_instruction(vcpu);
1966}
1967EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
1968
1969int kvm_emulate_invd(struct kvm_vcpu *vcpu)
1970{
1971 /* Treat an INVD instruction as a NOP and just skip it. */
1972 return kvm_emulate_as_nop(vcpu);
1973}
1974EXPORT_SYMBOL_GPL(kvm_emulate_invd);
1975
1976int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
1977{
1978 pr_warn_once("kvm: MWAIT instruction emulated as NOP!\n");
1979 return kvm_emulate_as_nop(vcpu);
1980}
1981EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
1982
1983int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
1984{
1985 kvm_queue_exception(vcpu, UD_VECTOR);
1986 return 1;
1987}
1988EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
1989
1990int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
1991{
1992 pr_warn_once("kvm: MONITOR instruction emulated as NOP!\n");
1993 return kvm_emulate_as_nop(vcpu);
1994}
1995EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
1996
Paolo Bonzinid89d04a2021-02-02 10:44:23 -05001997static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
Wanpeng Li5a9f5442020-04-28 14:23:26 +08001998{
Frederic Weisbecker4ae7dc92021-02-01 00:05:48 +01001999 xfer_to_guest_mode_prepare();
Wanpeng Li5a9f5442020-04-28 14:23:26 +08002000 return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
Thomas Gleixner72c3c0f2020-07-23 00:00:09 +02002001 xfer_to_guest_mode_work_pending();
Wanpeng Li5a9f5442020-04-28 14:23:26 +08002002}
Wanpeng Li5a9f5442020-04-28 14:23:26 +08002003
Carsten Otte313a3dc2007-10-11 19:16:52 +02002004/*
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002005 * The fast path for frequent and performance sensitive wrmsr emulation,
2006 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2007 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2008 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2009 * other cases which must be called after interrupts are enabled on the host.
2010 */
2011static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2012{
Wanpeng Lie1be9ac2020-03-26 10:20:01 +08002013 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2014 return 1;
2015
2016 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002017 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
Wanpeng Li4064a4c2020-04-02 16:20:26 +08002018 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2019 ((u32)(data >> 32) != X2APIC_BROADCAST)) {
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002020
Wanpeng Lid5361672020-03-26 10:20:02 +08002021 data &= ~(1 << 12);
2022 kvm_apic_send_ipi(vcpu->arch.apic, (u32)data, (u32)(data >> 32));
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002023 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
Wanpeng Lid5361672020-03-26 10:20:02 +08002024 kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR, (u32)data);
2025 trace_kvm_apic_write(APIC_ICR, (u32)data);
2026 return 0;
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002027 }
2028
2029 return 1;
2030}
2031
Wanpeng Liae95f562020-04-28 14:23:28 +08002032static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2033{
2034 if (!kvm_can_use_hv_timer(vcpu))
2035 return 1;
2036
2037 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2038 return 0;
2039}
2040
Wanpeng Li404d5d72020-04-28 14:23:25 +08002041fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002042{
2043 u32 msr = kvm_rcx_read(vcpu);
Wanpeng Li8a1038d2020-03-26 10:20:00 +08002044 u64 data;
Wanpeng Li404d5d72020-04-28 14:23:25 +08002045 fastpath_t ret = EXIT_FASTPATH_NONE;
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002046
2047 switch (msr) {
2048 case APIC_BASE_MSR + (APIC_ICR >> 4):
Wanpeng Li8a1038d2020-03-26 10:20:00 +08002049 data = kvm_read_edx_eax(vcpu);
Wanpeng Li404d5d72020-04-28 14:23:25 +08002050 if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
2051 kvm_skip_emulated_instruction(vcpu);
2052 ret = EXIT_FASTPATH_EXIT_HANDLED;
Haiwei Li80bc97f2020-05-18 09:31:38 +08002053 }
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002054 break;
Dave Hansen09141ec2020-03-05 09:47:06 -08002055 case MSR_IA32_TSC_DEADLINE:
Wanpeng Liae95f562020-04-28 14:23:28 +08002056 data = kvm_read_edx_eax(vcpu);
2057 if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
2058 kvm_skip_emulated_instruction(vcpu);
2059 ret = EXIT_FASTPATH_REENTER_GUEST;
2060 }
2061 break;
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002062 default:
Wanpeng Li404d5d72020-04-28 14:23:25 +08002063 break;
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002064 }
2065
Wanpeng Li404d5d72020-04-28 14:23:25 +08002066 if (ret != EXIT_FASTPATH_NONE)
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002067 trace_kvm_msr_write(msr, data);
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002068
Wanpeng Li404d5d72020-04-28 14:23:25 +08002069 return ret;
Wanpeng Li1e9e2622019-11-21 11:17:11 +08002070}
2071EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2072
2073/*
Carsten Otte313a3dc2007-10-11 19:16:52 +02002074 * Adapt set_msr() to msr_io()'s calling convention
2075 */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02002076static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2077{
Peter Xu6abe9c12020-06-22 18:04:41 -04002078 return kvm_get_msr_ignored_check(vcpu, index, data, true);
Paolo Bonzini609e36d2015-04-08 15:30:38 +02002079}
2080
Carsten Otte313a3dc2007-10-11 19:16:52 +02002081static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2082{
Peter Xu6abe9c12020-06-22 18:04:41 -04002083 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
Carsten Otte313a3dc2007-10-11 19:16:52 +02002084}
2085
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002086#ifdef CONFIG_X86_64
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002087struct pvclock_clock {
2088 int vclock_mode;
2089 u64 cycle_last;
2090 u64 mask;
2091 u32 mult;
2092 u32 shift;
Paolo Bonzini917f9472020-01-22 14:32:20 +01002093 u64 base_cycles;
2094 u64 offset;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002095};
2096
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002097struct pvclock_gtod_data {
2098 seqcount_t seq;
2099
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002100 struct pvclock_clock clock; /* extract of a clocksource struct */
2101 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002102
Paolo Bonzini917f9472020-01-22 14:32:20 +01002103 ktime_t offs_boot;
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002104 u64 wall_time_sec;
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002105};
2106
2107static struct pvclock_gtod_data pvclock_gtod_data;
2108
2109static void update_pvclock_gtod(struct timekeeper *tk)
2110{
2111 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2112
2113 write_seqcount_begin(&vdata->seq);
2114
2115 /* copy pvclock gtod data */
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002116 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
Peter Zijlstra876e7882015-03-19 10:09:06 +01002117 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2118 vdata->clock.mask = tk->tkr_mono.mask;
2119 vdata->clock.mult = tk->tkr_mono.mult;
2120 vdata->clock.shift = tk->tkr_mono.shift;
Paolo Bonzini917f9472020-01-22 14:32:20 +01002121 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2122 vdata->clock.offset = tk->tkr_mono.base;
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002123
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002124 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002125 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2126 vdata->raw_clock.mask = tk->tkr_raw.mask;
2127 vdata->raw_clock.mult = tk->tkr_raw.mult;
2128 vdata->raw_clock.shift = tk->tkr_raw.shift;
Paolo Bonzini917f9472020-01-22 14:32:20 +01002129 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2130 vdata->raw_clock.offset = tk->tkr_raw.base;
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002131
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002132 vdata->wall_time_sec = tk->xtime_sec;
2133
Paolo Bonzini917f9472020-01-22 14:32:20 +01002134 vdata->offs_boot = tk->offs_boot;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002135
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002136 write_seqcount_end(&vdata->seq);
2137}
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002138
2139static s64 get_kvmclock_base_ns(void)
2140{
2141 /* Count up from boot time, but with the frequency of the raw clock. */
2142 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2143}
2144#else
2145static s64 get_kvmclock_base_ns(void)
2146{
2147 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2148 return ktime_get_boottime_ns();
2149}
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002150#endif
2151
David Woodhouse55749762021-12-10 16:36:24 +00002152static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002153{
Avi Kivity9ed3c442010-05-04 15:00:37 +03002154 int version;
2155 int r;
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002156 struct pvclock_wall_clock wc;
Joao Martins629b5342018-06-28 15:06:43 -04002157 u32 wc_sec_hi;
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002158 u64 wall_nsec;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002159
2160 if (!wall_clock)
2161 return;
2162
Avi Kivity9ed3c442010-05-04 15:00:37 +03002163 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2164 if (r)
2165 return;
2166
2167 if (version & 1)
2168 ++version; /* first time write, random junk */
2169
2170 ++version;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002171
Nicholas Krause1dab1342015-12-30 13:08:46 -05002172 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2173 return;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002174
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002175 /*
2176 * The guest calculates current wall clock time by adding
Zachary Amsden34c238a2010-09-18 14:38:14 -10002177 * system time (updated by kvm_guest_time_update below) to the
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002178 * wall clock specified here. We do the reverse here.
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002179 */
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002180 wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002181
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002182 wc.nsec = do_div(wall_nsec, 1000000000);
2183 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002184 wc.version = version;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002185
2186 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2187
Joao Martins629b5342018-06-28 15:06:43 -04002188 if (sec_hi_ofs) {
2189 wc_sec_hi = wall_nsec >> 32;
2190 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2191 &wc_sec_hi, sizeof(wc_sec_hi));
2192 }
2193
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002194 version++;
2195 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002196}
2197
Oliver Upton5b9bb0e2020-08-18 15:24:26 +00002198static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2199 bool old_msr, bool host_initiated)
2200{
2201 struct kvm_arch *ka = &vcpu->kvm->arch;
2202
2203 if (vcpu->vcpu_id == 0 && !host_initiated) {
Oliver Upton1e293d12020-10-27 16:10:43 -07002204 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
Oliver Upton5b9bb0e2020-08-18 15:24:26 +00002205 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2206
2207 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2208 }
2209
2210 vcpu->arch.time = system_time;
2211 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2212
2213 /* we verify if the enable bit is set... */
2214 vcpu->arch.pv_time_enabled = false;
2215 if (!(system_time & 1))
2216 return;
2217
2218 if (!kvm_gfn_to_hva_cache_init(vcpu->kvm,
2219 &vcpu->arch.pv_time, system_time & ~1ULL,
2220 sizeof(struct pvclock_vcpu_time_info)))
2221 vcpu->arch.pv_time_enabled = true;
2222
2223 return;
2224}
2225
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002226static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2227{
Paolo Bonzinib51012d2016-01-22 11:39:22 +01002228 do_shl32_div32(dividend, divisor);
2229 return dividend;
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002230}
2231
Paolo Bonzini3ae13fa2016-02-08 15:11:15 +01002232static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
Zachary Amsden5f4e3f82010-09-18 14:38:13 -10002233 s8 *pshift, u32 *pmultiplier)
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002234{
Zachary Amsden5f4e3f82010-09-18 14:38:13 -10002235 uint64_t scaled64;
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002236 int32_t shift = 0;
2237 uint64_t tps64;
2238 uint32_t tps32;
2239
Paolo Bonzini3ae13fa2016-02-08 15:11:15 +01002240 tps64 = base_hz;
2241 scaled64 = scaled_hz;
Jan Kiszka50933622010-09-26 13:00:53 +02002242 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002243 tps64 >>= 1;
2244 shift--;
2245 }
2246
2247 tps32 = (uint32_t)tps64;
Jan Kiszka50933622010-09-26 13:00:53 +02002248 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2249 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
Zachary Amsden5f4e3f82010-09-18 14:38:13 -10002250 scaled64 >>= 1;
2251 else
2252 tps32 <<= 1;
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002253 shift++;
2254 }
2255
Zachary Amsden5f4e3f82010-09-18 14:38:13 -10002256 *pshift = shift;
2257 *pmultiplier = div_frac(scaled64, tps32);
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002258}
2259
Marcelo Tosattid8281992012-11-27 23:29:01 -02002260#ifdef CONFIG_X86_64
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002261static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
Marcelo Tosattid8281992012-11-27 23:29:01 -02002262#endif
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02002263
Gerd Hoffmannc8076602009-02-04 17:52:04 +01002264static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
Fengguang Wu69b00492015-01-19 22:33:39 +08002265static unsigned long max_tsc_khz;
Gerd Hoffmannc8076602009-02-04 17:52:04 +01002266
Zachary Amsdencc578282012-02-03 15:43:50 -02002267static u32 adjust_tsc_khz(u32 khz, s32 ppm)
Zachary Amsdenc2855452010-09-18 14:38:15 -10002268{
Zachary Amsdencc578282012-02-03 15:43:50 -02002269 u64 v = (u64)khz * (1000000 + ppm);
2270 do_div(v, 1000000);
2271 return v;
2272}
2273
Ilias Stamatis1ab92872021-06-07 11:54:38 +01002274static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2275
Haozhong Zhang381d5852015-10-20 15:39:04 +08002276static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2277{
2278 u64 ratio;
2279
2280 /* Guest TSC same frequency as host TSC? */
2281 if (!scale) {
Ilias Stamatis1ab92872021-06-07 11:54:38 +01002282 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_default_tsc_scaling_ratio);
Haozhong Zhang381d5852015-10-20 15:39:04 +08002283 return 0;
2284 }
2285
2286 /* TSC scaling supported? */
2287 if (!kvm_has_tsc_control) {
2288 if (user_tsc_khz > tsc_khz) {
2289 vcpu->arch.tsc_catchup = 1;
2290 vcpu->arch.tsc_always_catchup = 1;
2291 return 0;
2292 } else {
Paolo Bonzini3f16a5c2019-06-26 14:16:13 +02002293 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
Haozhong Zhang381d5852015-10-20 15:39:04 +08002294 return -1;
2295 }
2296 }
2297
2298 /* TSC scaling required - calculate ratio */
2299 ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
2300 user_tsc_khz, tsc_khz);
2301
2302 if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
Paolo Bonzini3f16a5c2019-06-26 14:16:13 +02002303 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2304 user_tsc_khz);
Haozhong Zhang381d5852015-10-20 15:39:04 +08002305 return -1;
2306 }
2307
Ilias Stamatis1ab92872021-06-07 11:54:38 +01002308 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
Haozhong Zhang381d5852015-10-20 15:39:04 +08002309 return 0;
2310}
2311
Paolo Bonzini4941b8c2016-02-08 14:51:12 +01002312static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
Zachary Amsdencc578282012-02-03 15:43:50 -02002313{
2314 u32 thresh_lo, thresh_hi;
2315 int use_scaling = 0;
2316
Marcelo Tosatti03ba32c2013-03-11 23:10:24 -03002317 /* tsc_khz can be zero if TSC calibration fails */
Paolo Bonzini4941b8c2016-02-08 14:51:12 +01002318 if (user_tsc_khz == 0) {
Haozhong Zhangad7218832015-10-20 15:39:02 +08002319 /* set tsc_scaling_ratio to a safe value */
Ilias Stamatis1ab92872021-06-07 11:54:38 +01002320 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_default_tsc_scaling_ratio);
Haozhong Zhang381d5852015-10-20 15:39:04 +08002321 return -1;
Haozhong Zhangad7218832015-10-20 15:39:02 +08002322 }
Marcelo Tosatti03ba32c2013-03-11 23:10:24 -03002323
Zachary Amsdenc2855452010-09-18 14:38:15 -10002324 /* Compute a scale to convert nanoseconds in TSC cycles */
Paolo Bonzini3ae13fa2016-02-08 15:11:15 +01002325 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
Zachary Amsdencc578282012-02-03 15:43:50 -02002326 &vcpu->arch.virtual_tsc_shift,
2327 &vcpu->arch.virtual_tsc_mult);
Paolo Bonzini4941b8c2016-02-08 14:51:12 +01002328 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
Zachary Amsdencc578282012-02-03 15:43:50 -02002329
2330 /*
2331 * Compute the variation in TSC rate which is acceptable
2332 * within the range of tolerance and decide if the
2333 * rate being applied is within that bounds of the hardware
2334 * rate. If so, no scaling or compensation need be done.
2335 */
2336 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2337 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
Paolo Bonzini4941b8c2016-02-08 14:51:12 +01002338 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2339 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
Zachary Amsdencc578282012-02-03 15:43:50 -02002340 use_scaling = 1;
2341 }
Paolo Bonzini4941b8c2016-02-08 14:51:12 +01002342 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
Zachary Amsdenc2855452010-09-18 14:38:15 -10002343}
2344
2345static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2346{
Zachary Amsdene26101b2012-02-03 15:43:57 -02002347 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
Zachary Amsdencc578282012-02-03 15:43:50 -02002348 vcpu->arch.virtual_tsc_mult,
2349 vcpu->arch.virtual_tsc_shift);
Zachary Amsdene26101b2012-02-03 15:43:57 -02002350 tsc += vcpu->arch.this_tsc_write;
Zachary Amsdenc2855452010-09-18 14:38:15 -10002351 return tsc;
2352}
2353
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002354static inline int gtod_is_based_on_tsc(int mode)
2355{
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002356 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002357}
2358
Fengguang Wu69b00492015-01-19 22:33:39 +08002359static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002360{
2361#ifdef CONFIG_X86_64
2362 bool vcpus_matched;
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002363 struct kvm_arch *ka = &vcpu->kvm->arch;
2364 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2365
2366 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2367 atomic_read(&vcpu->kvm->online_vcpus));
2368
Marcelo Tosatti7f187922014-11-04 21:30:44 -02002369 /*
2370 * Once the masterclock is enabled, always perform request in
2371 * order to update it.
2372 *
2373 * In order to enable masterclock, the host clocksource must be TSC
2374 * and the vcpus need to have matched TSCs. When that happens,
2375 * perform request to enable masterclock.
2376 */
2377 if (ka->use_master_clock ||
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002378 (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002379 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2380
2381 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2382 atomic_read(&vcpu->kvm->online_vcpus),
2383 ka->use_master_clock, gtod->clock.vclock_mode);
2384#endif
2385}
2386
Haozhong Zhang35181e82015-10-20 15:39:03 +08002387/*
2388 * Multiply tsc by a fixed point number represented by ratio.
2389 *
2390 * The most significant 64-N bits (mult) of ratio represent the
2391 * integral part of the fixed point number; the remaining N bits
2392 * (frac) represent the fractional part, ie. ratio represents a fixed
2393 * point number (mult + frac * 2^(-N)).
2394 *
2395 * N equals to kvm_tsc_scaling_ratio_frac_bits.
2396 */
2397static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2398{
2399 return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
2400}
2401
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01002402u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc, u64 ratio)
Haozhong Zhang35181e82015-10-20 15:39:03 +08002403{
2404 u64 _tsc = tsc;
Haozhong Zhang35181e82015-10-20 15:39:03 +08002405
2406 if (ratio != kvm_default_tsc_scaling_ratio)
2407 _tsc = __scale_tsc(ratio, tsc);
2408
2409 return _tsc;
2410}
2411EXPORT_SYMBOL_GPL(kvm_scale_tsc);
2412
Ilias Stamatis9b399df2021-05-26 19:44:10 +01002413static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
Haozhong Zhang07c14192015-10-20 15:39:05 +08002414{
2415 u64 tsc;
2416
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01002417 tsc = kvm_scale_tsc(vcpu, rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
Haozhong Zhang07c14192015-10-20 15:39:05 +08002418
2419 return target_tsc - tsc;
2420}
2421
Haozhong Zhang4ba76532015-10-20 15:39:07 +08002422u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2423{
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01002424 return vcpu->arch.l1_tsc_offset +
2425 kvm_scale_tsc(vcpu, host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
Haozhong Zhang4ba76532015-10-20 15:39:07 +08002426}
2427EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2428
Ilias Stamatis83150f22021-05-26 19:44:14 +01002429u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2430{
2431 u64 nested_offset;
2432
2433 if (l2_multiplier == kvm_default_tsc_scaling_ratio)
2434 nested_offset = l1_offset;
2435 else
2436 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2437 kvm_tsc_scaling_ratio_frac_bits);
2438
2439 nested_offset += l2_offset;
2440 return nested_offset;
2441}
2442EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2443
2444u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2445{
2446 if (l2_multiplier != kvm_default_tsc_scaling_ratio)
2447 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2448 kvm_tsc_scaling_ratio_frac_bits);
2449
2450 return l1_multiplier;
2451}
2452EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2453
Ilias Stamatisedcfe542021-05-26 19:44:15 +01002454static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
Luiz Capitulinoa545ab62016-09-07 14:47:19 -04002455{
Ilias Stamatisedcfe542021-05-26 19:44:15 +01002456 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2457 vcpu->arch.l1_tsc_offset,
2458 l1_offset);
2459
2460 vcpu->arch.l1_tsc_offset = l1_offset;
2461
2462 /*
2463 * If we are here because L1 chose not to trap WRMSR to TSC then
2464 * according to the spec this should set L1's TSC (as opposed to
2465 * setting L1's offset for L2).
2466 */
2467 if (is_guest_mode(vcpu))
2468 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2469 l1_offset,
2470 static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
2471 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2472 else
2473 vcpu->arch.tsc_offset = l1_offset;
2474
2475 static_call(kvm_x86_write_tsc_offset)(vcpu, vcpu->arch.tsc_offset);
Luiz Capitulinoa545ab62016-09-07 14:47:19 -04002476}
2477
Ilias Stamatis1ab92872021-06-07 11:54:38 +01002478static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2479{
2480 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2481
2482 /* Userspace is changing the multiplier while L2 is active */
2483 if (is_guest_mode(vcpu))
2484 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2485 l1_multiplier,
2486 static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
2487 else
2488 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2489
2490 if (kvm_has_tsc_control)
2491 static_call(kvm_x86_write_tsc_multiplier)(
2492 vcpu, vcpu->arch.tsc_scaling_ratio);
2493}
2494
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002495static inline bool kvm_check_tsc_unstable(void)
2496{
2497#ifdef CONFIG_X86_64
2498 /*
2499 * TSC is marked unstable when we're running on Hyper-V,
2500 * 'TSC page' clocksource is good.
2501 */
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002502 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002503 return false;
2504#endif
2505 return check_tsc_unstable();
2506}
2507
Oliver Upton58d42772021-09-16 18:15:37 +00002508/*
2509 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2510 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2511 * participates in.
2512 */
2513static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2514 u64 ns, bool matched)
2515{
2516 struct kvm *kvm = vcpu->kvm;
2517
2518 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2519
2520 /*
2521 * We also track th most recent recorded KHZ, write and time to
2522 * allow the matching interval to be extended at each write.
2523 */
2524 kvm->arch.last_tsc_nsec = ns;
2525 kvm->arch.last_tsc_write = tsc;
2526 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
Oliver Upton828ca892021-09-16 18:15:38 +00002527 kvm->arch.last_tsc_offset = offset;
Oliver Upton58d42772021-09-16 18:15:37 +00002528
2529 vcpu->arch.last_guest_tsc = tsc;
2530
2531 kvm_vcpu_write_tsc_offset(vcpu, offset);
2532
2533 if (!matched) {
2534 /*
2535 * We split periods of matched TSC writes into generations.
2536 * For each generation, we track the original measured
2537 * nanosecond time, offset, and write, so if TSCs are in
2538 * sync, we can match exact offset, and if not, we can match
2539 * exact software computation in compute_guest_tsc()
2540 *
2541 * These values are tracked in kvm->arch.cur_xxx variables.
2542 */
2543 kvm->arch.cur_tsc_generation++;
2544 kvm->arch.cur_tsc_nsec = ns;
2545 kvm->arch.cur_tsc_write = tsc;
2546 kvm->arch.cur_tsc_offset = offset;
2547 kvm->arch.nr_vcpus_matched_tsc = 0;
2548 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2549 kvm->arch.nr_vcpus_matched_tsc++;
2550 }
2551
2552 /* Keep track of which generation this VCPU has synchronized to */
2553 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2554 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2555 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2556
2557 kvm_track_tsc_matching(vcpu);
2558}
2559
Paolo Bonzini0c899c22020-09-24 14:45:27 +02002560static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
Zachary Amsden99e3e302010-08-19 22:07:17 -10002561{
2562 struct kvm *kvm = vcpu->kvm;
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002563 u64 offset, ns, elapsed;
Zachary Amsden99e3e302010-08-19 22:07:17 -10002564 unsigned long flags;
Oliver Upton58d42772021-09-16 18:15:37 +00002565 bool matched = false;
Denis Plotnikovc5e8ec82017-04-07 12:09:52 +03002566 bool synchronizing = false;
Zachary Amsden99e3e302010-08-19 22:07:17 -10002567
Jan Kiszka038f8c12011-02-04 10:49:11 +01002568 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
Ilias Stamatis9b399df2021-05-26 19:44:10 +01002569 offset = kvm_compute_l1_tsc_offset(vcpu, data);
Paolo Bonzini8171cd62020-01-22 14:36:09 +01002570 ns = get_kvmclock_base_ns();
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002571 elapsed = ns - kvm->arch.last_tsc_nsec;
Zachary Amsden5d3cb0f62012-02-03 15:43:51 -02002572
Marcelo Tosatti03ba32c2013-03-11 23:10:24 -03002573 if (vcpu->arch.virtual_tsc_khz) {
Paolo Bonzini0c899c22020-09-24 14:45:27 +02002574 if (data == 0) {
Denis Plotnikovbd8fab32017-04-07 12:09:53 +03002575 /*
2576 * detection of vcpu initialization -- need to sync
2577 * with other vCPUs. This particularly helps to keep
2578 * kvm_clock stable after CPU hotplug
2579 */
2580 synchronizing = true;
2581 } else {
2582 u64 tsc_exp = kvm->arch.last_tsc_write +
2583 nsec_to_cycles(vcpu, elapsed);
2584 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2585 /*
2586 * Special case: TSC write with a small delta (1 second)
2587 * of virtual cycle time against real time is
2588 * interpreted as an attempt to synchronize the CPU.
2589 */
2590 synchronizing = data < tsc_exp + tsc_hz &&
2591 data + tsc_hz > tsc_exp;
2592 }
Denis Plotnikovc5e8ec82017-04-07 12:09:52 +03002593 }
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002594
2595 /*
Zachary Amsden5d3cb0f62012-02-03 15:43:51 -02002596 * For a reliable TSC, we can match TSC offsets, and for an unstable
2597 * TSC, we add elapsed time in this computation. We could let the
2598 * compensation code attempt to catch up if we fall behind, but
2599 * it's better to try to match offsets from the beginning.
2600 */
Denis Plotnikovc5e8ec82017-04-07 12:09:52 +03002601 if (synchronizing &&
Zachary Amsden5d3cb0f62012-02-03 15:43:51 -02002602 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002603 if (!kvm_check_tsc_unstable()) {
Zachary Amsdene26101b2012-02-03 15:43:57 -02002604 offset = kvm->arch.cur_tsc_offset;
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002605 } else {
Joerg Roedel857e4092011-03-25 09:44:50 +01002606 u64 delta = nsec_to_cycles(vcpu, elapsed);
Zachary Amsden5d3cb0f62012-02-03 15:43:51 -02002607 data += delta;
Ilias Stamatis9b399df2021-05-26 19:44:10 +01002608 offset = kvm_compute_l1_tsc_offset(vcpu, data);
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002609 }
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002610 matched = true;
Zachary Amsdenf38e0982010-08-19 22:07:20 -10002611 }
Zachary Amsdene26101b2012-02-03 15:43:57 -02002612
Oliver Upton58d42772021-09-16 18:15:37 +00002613 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
Zachary Amsdene26101b2012-02-03 15:43:57 -02002614 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
Zachary Amsden99e3e302010-08-19 22:07:17 -10002615}
Zachary Amsdene26101b2012-02-03 15:43:57 -02002616
Haozhong Zhang58ea6762015-10-20 15:39:06 +08002617static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2618 s64 adjustment)
2619{
Sean Christopherson56ba77a2020-05-01 21:32:25 -07002620 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
Leonid Shatz326e7422018-11-06 12:14:25 +02002621 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
Haozhong Zhang58ea6762015-10-20 15:39:06 +08002622}
2623
2624static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2625{
Ilias Stamatis805d7052021-05-26 19:44:09 +01002626 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
Haozhong Zhang58ea6762015-10-20 15:39:06 +08002627 WARN_ON(adjustment < 0);
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01002628 adjustment = kvm_scale_tsc(vcpu, (u64) adjustment,
2629 vcpu->arch.l1_tsc_scaling_ratio);
Paolo Bonziniea26e4e2016-11-01 00:39:48 +01002630 adjust_tsc_offset_guest(vcpu, adjustment);
Haozhong Zhang58ea6762015-10-20 15:39:06 +08002631}
2632
Marcelo Tosattid8281992012-11-27 23:29:01 -02002633#ifdef CONFIG_X86_64
2634
Thomas Gleixnera5a1d1c2016-12-21 20:32:01 +01002635static u64 read_tsc(void)
Marcelo Tosattid8281992012-11-27 23:29:01 -02002636{
Thomas Gleixnera5a1d1c2016-12-21 20:32:01 +01002637 u64 ret = (u64)rdtsc_ordered();
Andy Lutomirski03b97302015-06-25 18:44:08 +02002638 u64 last = pvclock_gtod_data.clock.cycle_last;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002639
2640 if (likely(ret >= last))
2641 return ret;
2642
2643 /*
2644 * GCC likes to generate cmov here, but this branch is extremely
Adam Buchbinder6a6256f2016-02-23 15:34:30 -08002645 * predictable (it's just a function of time and the likely is
Marcelo Tosattid8281992012-11-27 23:29:01 -02002646 * very likely) and there's a data dependence, so force GCC
2647 * to generate a branch instead. I don't barrier() because
2648 * we don't actually need a barrier, and if this function
2649 * ever gets inlined it will generate worse code.
2650 */
2651 asm volatile ("");
2652 return last;
2653}
2654
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002655static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2656 int *mode)
Marcelo Tosattid8281992012-11-27 23:29:01 -02002657{
2658 long v;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002659 u64 tsc_pg_val;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002660
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002661 switch (clock->vclock_mode) {
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002662 case VDSO_CLOCKMODE_HVCLOCK:
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002663 tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
2664 tsc_timestamp);
2665 if (tsc_pg_val != U64_MAX) {
2666 /* TSC page valid */
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002667 *mode = VDSO_CLOCKMODE_HVCLOCK;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002668 v = (tsc_pg_val - clock->cycle_last) &
2669 clock->mask;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002670 } else {
2671 /* TSC page invalid */
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002672 *mode = VDSO_CLOCKMODE_NONE;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002673 }
2674 break;
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002675 case VDSO_CLOCKMODE_TSC:
2676 *mode = VDSO_CLOCKMODE_TSC;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002677 *tsc_timestamp = read_tsc();
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002678 v = (*tsc_timestamp - clock->cycle_last) &
2679 clock->mask;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002680 break;
2681 default:
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002682 *mode = VDSO_CLOCKMODE_NONE;
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002683 }
Marcelo Tosattid8281992012-11-27 23:29:01 -02002684
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01002685 if (*mode == VDSO_CLOCKMODE_NONE)
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002686 *tsc_timestamp = v = 0;
2687
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002688 return v * clock->mult;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002689}
2690
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002691static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
Marcelo Tosattid8281992012-11-27 23:29:01 -02002692{
Marcelo Tosattid8281992012-11-27 23:29:01 -02002693 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
Thomas Gleixnercbcf2dd2014-07-16 21:04:54 +00002694 unsigned long seq;
2695 int mode;
2696 u64 ns;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002697
Marcelo Tosattid8281992012-11-27 23:29:01 -02002698 do {
2699 seq = read_seqcount_begin(&gtod->seq);
Paolo Bonzini917f9472020-01-22 14:32:20 +01002700 ns = gtod->raw_clock.base_cycles;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002701 ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
Paolo Bonzini917f9472020-01-22 14:32:20 +01002702 ns >>= gtod->raw_clock.shift;
2703 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
Marcelo Tosattid8281992012-11-27 23:29:01 -02002704 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
Thomas Gleixnercbcf2dd2014-07-16 21:04:54 +00002705 *t = ns;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002706
2707 return mode;
2708}
2709
Arnd Bergmann899a31f2018-04-23 10:04:26 +02002710static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002711{
2712 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2713 unsigned long seq;
2714 int mode;
2715 u64 ns;
2716
2717 do {
2718 seq = read_seqcount_begin(&gtod->seq);
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002719 ts->tv_sec = gtod->wall_time_sec;
Paolo Bonzini917f9472020-01-22 14:32:20 +01002720 ns = gtod->clock.base_cycles;
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002721 ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002722 ns >>= gtod->clock.shift;
2723 } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2724
2725 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2726 ts->tv_nsec = ns;
2727
2728 return mode;
2729}
2730
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002731/* returns true if host is using TSC based clocksource */
2732static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
Marcelo Tosattid8281992012-11-27 23:29:01 -02002733{
Marcelo Tosattid8281992012-11-27 23:29:01 -02002734 /* checked again under seqlock below */
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002735 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
Marcelo Tosattid8281992012-11-27 23:29:01 -02002736 return false;
2737
Marcelo Tosatti53fafdb2019-10-28 12:36:22 -02002738 return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002739 tsc_timestamp));
Marcelo Tosattid8281992012-11-27 23:29:01 -02002740}
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002741
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002742/* returns true if host is using TSC based clocksource */
Arnd Bergmann899a31f2018-04-23 10:04:26 +02002743static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002744 u64 *tsc_timestamp)
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002745{
2746 /* checked again under seqlock below */
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002747 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002748 return false;
2749
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01002750 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02002751}
Marcelo Tosattid8281992012-11-27 23:29:01 -02002752#endif
2753
2754/*
2755 *
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002756 * Assuming a stable TSC across physical CPUS, and a stable TSC
2757 * across virtual CPUs, the following condition is possible.
2758 * Each numbered line represents an event visible to both
Marcelo Tosattid8281992012-11-27 23:29:01 -02002759 * CPUs at the next numbered event.
2760 *
2761 * "timespecX" represents host monotonic time. "tscX" represents
2762 * RDTSC value.
2763 *
2764 * VCPU0 on CPU0 | VCPU1 on CPU1
2765 *
2766 * 1. read timespec0,tsc0
2767 * 2. | timespec1 = timespec0 + N
2768 * | tsc1 = tsc0 + M
2769 * 3. transition to guest | transition to guest
2770 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2771 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2772 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2773 *
2774 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2775 *
2776 * - ret0 < ret1
2777 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2778 * ...
2779 * - 0 < N - M => M < N
2780 *
2781 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2782 * always the case (the difference between two distinct xtime instances
2783 * might be smaller then the difference between corresponding TSC reads,
2784 * when updating guest vcpus pvclock areas).
2785 *
2786 * To avoid that problem, do not allow visibility of distinct
2787 * system_timestamp/tsc_timestamp values simultaneously: use a master
2788 * copy of host monotonic time values. Update that master copy
2789 * in lockstep.
2790 *
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002791 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
Marcelo Tosattid8281992012-11-27 23:29:01 -02002792 *
2793 */
2794
2795static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
2796{
2797#ifdef CONFIG_X86_64
2798 struct kvm_arch *ka = &kvm->arch;
2799 int vclock_mode;
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002800 bool host_tsc_clocksource, vcpus_matched;
2801
Paolo Bonzini869b4422021-09-16 18:15:36 +00002802 lockdep_assert_held(&kvm->arch.tsc_write_lock);
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002803 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
2804 atomic_read(&kvm->online_vcpus));
Marcelo Tosattid8281992012-11-27 23:29:01 -02002805
2806 /*
2807 * If the host uses TSC clock, then passthrough TSC as stable
2808 * to the guest.
2809 */
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002810 host_tsc_clocksource = kvm_get_time_and_clockread(
Marcelo Tosattid8281992012-11-27 23:29:01 -02002811 &ka->master_kernel_ns,
2812 &ka->master_cycle_now);
2813
Marcelo Tosatti16a96022014-05-14 12:43:24 -03002814 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
Ladi Proseka826faf2017-06-26 09:56:43 +02002815 && !ka->backwards_tsc_observed
Marcelo Tosatti54750f22015-01-20 15:54:52 -02002816 && !ka->boot_vcpu_runs_old_kvmclock;
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002817
Marcelo Tosattid8281992012-11-27 23:29:01 -02002818 if (ka->use_master_clock)
2819 atomic_set(&kvm_guest_has_master_clock, 1);
2820
2821 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
Marcelo Tosattib48aa972012-11-27 23:29:03 -02002822 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
2823 vcpus_matched);
Marcelo Tosattid8281992012-11-27 23:29:01 -02002824#endif
2825}
2826
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002827static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
Paolo Bonzini2860c4b2016-01-07 15:05:10 +01002828{
2829 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
2830}
2831
Paolo Bonzini869b4422021-09-16 18:15:36 +00002832static void __kvm_start_pvclock_update(struct kvm *kvm)
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002833{
Paolo Bonzini869b4422021-09-16 18:15:36 +00002834 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
2835 write_seqcount_begin(&kvm->arch.pvclock_sc);
2836}
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002837
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002838static void kvm_start_pvclock_update(struct kvm *kvm)
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002839{
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002840 kvm_make_mclock_inprogress_request(kvm);
Paolo Bonzinic2c647f2021-03-25 14:05:11 -04002841
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002842 /* no guest entries from this point */
Paolo Bonzini869b4422021-09-16 18:15:36 +00002843 __kvm_start_pvclock_update(kvm);
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002844}
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002845
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002846static void kvm_end_pvclock_update(struct kvm *kvm)
2847{
2848 struct kvm_arch *ka = &kvm->arch;
2849 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +00002850 unsigned long i;
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002851
Paolo Bonzini869b4422021-09-16 18:15:36 +00002852 write_seqcount_end(&ka->pvclock_sc);
2853 raw_spin_unlock_irq(&ka->tsc_write_lock);
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002854 kvm_for_each_vcpu(i, vcpu, kvm)
Guo Hui Liu105b21b2014-09-12 13:43:19 +08002855 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002856
2857 /* guest entries allowed */
2858 kvm_for_each_vcpu(i, vcpu, kvm)
Radim Krčmář72875d82017-04-26 22:32:19 +02002859 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
Marcelo Tosatti2e762ff2013-08-27 23:55:29 -03002860}
2861
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00002862static void kvm_update_masterclock(struct kvm *kvm)
2863{
2864 kvm_hv_invalidate_tsc_page(kvm);
2865 kvm_start_pvclock_update(kvm);
2866 pvclock_update_vm_gtod_copy(kvm);
2867 kvm_end_pvclock_update(kvm);
Zachary Amsden99e3e302010-08-19 22:07:17 -10002868}
2869
Paolo Bonzini869b4422021-09-16 18:15:36 +00002870/* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
2871static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
Paolo Bonzini108b2492016-09-01 14:21:03 +02002872{
Paolo Bonzini108b2492016-09-01 14:21:03 +02002873 struct kvm_arch *ka = &kvm->arch;
Paolo Bonzini8b953442016-11-16 18:31:30 +01002874 struct pvclock_vcpu_time_info hv_clock;
Paolo Bonzini8b953442016-11-16 18:31:30 +01002875
Wanpeng Lie2c22062017-05-11 18:12:05 -07002876 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
2877 get_cpu();
2878
Paolo Bonzini869b4422021-09-16 18:15:36 +00002879 data->flags = 0;
2880 if (ka->use_master_clock && __this_cpu_read(cpu_tsc_khz)) {
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00002881#ifdef CONFIG_X86_64
2882 struct timespec64 ts;
2883
2884 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
2885 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
2886 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
2887 } else
2888#endif
2889 data->host_tsc = rdtsc();
2890
Paolo Bonzini869b4422021-09-16 18:15:36 +00002891 data->flags |= KVM_CLOCK_TSC_STABLE;
2892 hv_clock.tsc_timestamp = ka->master_cycle_now;
2893 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
Wanpeng Lie70b57a2017-11-20 14:55:05 -08002894 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
2895 &hv_clock.tsc_shift,
2896 &hv_clock.tsc_to_system_mul);
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00002897 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
Oliver Upton55c0cef2021-09-16 18:15:34 +00002898 } else {
2899 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
2900 }
Wanpeng Lie2c22062017-05-11 18:12:05 -07002901
2902 put_cpu();
Oliver Upton55c0cef2021-09-16 18:15:34 +00002903}
Wanpeng Lie2c22062017-05-11 18:12:05 -07002904
Paolo Bonzini869b4422021-09-16 18:15:36 +00002905static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
2906{
2907 struct kvm_arch *ka = &kvm->arch;
2908 unsigned seq;
2909
2910 do {
2911 seq = read_seqcount_begin(&ka->pvclock_sc);
2912 __get_kvmclock(kvm, data);
2913 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
2914}
2915
Oliver Upton55c0cef2021-09-16 18:15:34 +00002916u64 get_kvmclock_ns(struct kvm *kvm)
2917{
2918 struct kvm_clock_data data;
2919
Oliver Upton55c0cef2021-09-16 18:15:34 +00002920 get_kvmclock(kvm, &data);
2921 return data.clock;
Paolo Bonzini108b2492016-09-01 14:21:03 +02002922}
2923
Joao Martinsaa096aa2019-02-01 13:01:45 -05002924static void kvm_setup_pvclock_page(struct kvm_vcpu *v,
2925 struct gfn_to_hva_cache *cache,
2926 unsigned int offset)
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002927{
2928 struct kvm_vcpu_arch *vcpu = &v->arch;
2929 struct pvclock_vcpu_time_info guest_hv_clock;
2930
Joao Martinsaa096aa2019-02-01 13:01:45 -05002931 if (unlikely(kvm_read_guest_offset_cached(v->kvm, cache,
2932 &guest_hv_clock, offset, sizeof(guest_hv_clock))))
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002933 return;
2934
2935 /* This VCPU is paused, but it's legal for a guest to read another
2936 * VCPU's kvmclock, so we really have to follow the specification where
2937 * it says that version is odd if data is being modified, and even after
2938 * it is consistent.
2939 *
2940 * Version field updates must be kept separate. This is because
2941 * kvm_write_guest_cached might use a "rep movs" instruction, and
2942 * writes within a string instruction are weakly ordered. So there
2943 * are three writes overall.
2944 *
2945 * As a small optimization, only write the version field in the first
2946 * and third write. The vcpu->pv_time cache is still valid, because the
2947 * version field is the first in the struct.
2948 */
2949 BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
2950
Liran Alon51c4b8b2017-11-05 16:11:30 +02002951 if (guest_hv_clock.version & 1)
2952 ++guest_hv_clock.version; /* first time write, random junk */
2953
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002954 vcpu->hv_clock.version = guest_hv_clock.version + 1;
Joao Martinsaa096aa2019-02-01 13:01:45 -05002955 kvm_write_guest_offset_cached(v->kvm, cache,
2956 &vcpu->hv_clock, offset,
2957 sizeof(vcpu->hv_clock.version));
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002958
2959 smp_wmb();
2960
2961 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
2962 vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
2963
2964 if (vcpu->pvclock_set_guest_stopped_request) {
2965 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
2966 vcpu->pvclock_set_guest_stopped_request = false;
2967 }
2968
2969 trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
2970
Joao Martinsaa096aa2019-02-01 13:01:45 -05002971 kvm_write_guest_offset_cached(v->kvm, cache,
2972 &vcpu->hv_clock, offset,
2973 sizeof(vcpu->hv_clock));
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002974
2975 smp_wmb();
2976
2977 vcpu->hv_clock.version++;
Joao Martinsaa096aa2019-02-01 13:01:45 -05002978 kvm_write_guest_offset_cached(v->kvm, cache,
2979 &vcpu->hv_clock, offset,
2980 sizeof(vcpu->hv_clock.version));
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02002981}
2982
Zachary Amsden34c238a2010-09-18 14:38:14 -10002983static int kvm_guest_time_update(struct kvm_vcpu *v)
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002984{
Paolo Bonzini78db6a52016-02-08 14:51:40 +01002985 unsigned long flags, tgt_tsc_khz;
Paolo Bonzini869b4422021-09-16 18:15:36 +00002986 unsigned seq;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02002987 struct kvm_vcpu_arch *vcpu = &v->arch;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002988 struct kvm_arch *ka = &v->kvm->arch;
Marcelo Tosattif25e6562014-01-06 12:18:59 -02002989 s64 kernel_ns;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002990 u64 tsc_timestamp, host_tsc;
Marcelo Tosatti51d59c62012-08-03 15:57:49 -03002991 u8 pvclock_flags;
Marcelo Tosattid8281992012-11-27 23:29:01 -02002992 bool use_master_clock;
2993
2994 kernel_ns = 0;
2995 host_tsc = 0;
Gerd Hoffmann50d0a0f2008-06-03 16:17:31 +02002996
Zachary Amsden1d5f0662010-08-19 22:07:30 -10002997 /*
Marcelo Tosattid8281992012-11-27 23:29:01 -02002998 * If the host uses TSC clock, then passthrough TSC as stable
2999 * to the guest.
3000 */
Paolo Bonzini869b4422021-09-16 18:15:36 +00003001 do {
3002 seq = read_seqcount_begin(&ka->pvclock_sc);
3003 use_master_clock = ka->use_master_clock;
3004 if (use_master_clock) {
3005 host_tsc = ka->master_cycle_now;
3006 kernel_ns = ka->master_kernel_ns;
3007 }
3008 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
Marcelo Tosattic09664b2013-03-18 13:54:32 -03003009
3010 /* Keep irq disabled to prevent changes to the clock */
3011 local_irq_save(flags);
Paolo Bonzini78db6a52016-02-08 14:51:40 +01003012 tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
3013 if (unlikely(tgt_tsc_khz == 0)) {
Marcelo Tosattic09664b2013-03-18 13:54:32 -03003014 local_irq_restore(flags);
3015 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3016 return 1;
3017 }
Marcelo Tosattid8281992012-11-27 23:29:01 -02003018 if (!use_master_clock) {
Andy Lutomirski4ea16362015-06-25 18:44:07 +02003019 host_tsc = rdtsc();
Paolo Bonzini8171cd62020-01-22 14:36:09 +01003020 kernel_ns = get_kvmclock_base_ns();
Marcelo Tosattid8281992012-11-27 23:29:01 -02003021 }
3022
Haozhong Zhang4ba76532015-10-20 15:39:07 +08003023 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
Marcelo Tosattid8281992012-11-27 23:29:01 -02003024
3025 /*
Zachary Amsdenc2855452010-09-18 14:38:15 -10003026 * We may have to catch up the TSC to match elapsed wall clock
3027 * time for two reasons, even if kvmclock is used.
3028 * 1) CPU could have been running below the maximum TSC rate
3029 * 2) Broken TSC compensation resets the base at each VCPU
3030 * entry to avoid unknown leaps of TSC even when running
3031 * again on the same CPU. This may cause apparent elapsed
3032 * time to disappear, and the guest to stand still or run
3033 * very slowly.
3034 */
3035 if (vcpu->tsc_catchup) {
3036 u64 tsc = compute_guest_tsc(v, kernel_ns);
3037 if (tsc > tsc_timestamp) {
Marcelo Tosattif1e2b262012-02-03 15:43:55 -02003038 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
Zachary Amsdenc2855452010-09-18 14:38:15 -10003039 tsc_timestamp = tsc;
3040 }
3041 }
3042
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003043 local_irq_restore(flags);
3044
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02003045 /* With all the info we got, fill in the values */
Zachary Amsdenc2855452010-09-18 14:38:15 -10003046
Paolo Bonzini78db6a52016-02-08 14:51:40 +01003047 if (kvm_has_tsc_control)
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01003048 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz,
3049 v->arch.l1_tsc_scaling_ratio);
Paolo Bonzini78db6a52016-02-08 14:51:40 +01003050
3051 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
Paolo Bonzini3ae13fa2016-02-08 15:11:15 +01003052 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
Zachary Amsden5f4e3f82010-09-18 14:38:13 -10003053 &vcpu->hv_clock.tsc_shift,
3054 &vcpu->hv_clock.tsc_to_system_mul);
Paolo Bonzini78db6a52016-02-08 14:51:40 +01003055 vcpu->hw_tsc_khz = tgt_tsc_khz;
Zachary Amsden8cfdc002010-08-19 22:07:21 -10003056 }
3057
Zachary Amsden1d5f0662010-08-19 22:07:30 -10003058 vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
Zachary Amsden759379d2010-08-19 22:07:25 -10003059 vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
Zachary Amsden28e46392010-09-18 14:38:12 -10003060 vcpu->last_guest_tsc = tsc_timestamp;
Marcelo Tosatti51d59c62012-08-03 15:57:49 -03003061
Marcelo Tosattid8281992012-11-27 23:29:01 -02003062 /* If the host uses TSC clocksource, then it is stable */
Paolo Bonzini0d6dd2f2016-09-01 14:20:09 +02003063 pvclock_flags = 0;
Marcelo Tosattid8281992012-11-27 23:29:01 -02003064 if (use_master_clock)
3065 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
3066
Marcelo Tosatti78c03372012-11-27 23:28:47 -02003067 vcpu->hv_clock.flags = pvclock_flags;
3068
Paolo Bonzini095cf552016-02-08 12:54:12 +01003069 if (vcpu->pv_time_enabled)
Joao Martinsaa096aa2019-02-01 13:01:45 -05003070 kvm_setup_pvclock_page(v, &vcpu->pv_time, 0);
3071 if (vcpu->xen.vcpu_info_set)
3072 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_info_cache,
3073 offsetof(struct compat_vcpu_info, time));
Joao Martinsf2340cd2018-07-23 11:20:57 -04003074 if (vcpu->xen.vcpu_time_info_set)
3075 kvm_setup_pvclock_page(v, &vcpu->xen.vcpu_time_info_cache, 0);
Sean Christopherson94c245a2021-09-10 11:32:20 -07003076 if (!v->vcpu_idx)
Paolo Bonzini095cf552016-02-08 12:54:12 +01003077 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
Zachary Amsden8cfdc002010-08-19 22:07:21 -10003078 return 0;
Gerd Hoffmannc8076602009-02-04 17:52:04 +01003079}
3080
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03003081/*
3082 * kvmclock updates which are isolated to a given vcpu, such as
3083 * vcpu->cpu migration, should not allow system_timestamp from
3084 * the rest of the vcpus to remain static. Otherwise ntp frequency
3085 * correction applies to one vcpu's system_timestamp but not
3086 * the others.
3087 *
3088 * So in those cases, request a kvmclock update for all vcpus.
Andrew Jones7e44e442014-02-28 12:52:54 +01003089 * We need to rate-limit these requests though, as they can
3090 * considerably slow guests that have a large number of vcpus.
3091 * The time for a remote vcpu to update its kvmclock is bound
3092 * by the delay we use to rate-limit the updates.
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03003093 */
3094
Andrew Jones7e44e442014-02-28 12:52:54 +01003095#define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3096
3097static void kvmclock_update_fn(struct work_struct *work)
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03003098{
Marc Zyngier46808a42021-11-16 16:04:02 +00003099 unsigned long i;
Andrew Jones7e44e442014-02-28 12:52:54 +01003100 struct delayed_work *dwork = to_delayed_work(work);
3101 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3102 kvmclock_update_work);
3103 struct kvm *kvm = container_of(ka, struct kvm, arch);
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03003104 struct kvm_vcpu *vcpu;
3105
3106 kvm_for_each_vcpu(i, vcpu, kvm) {
Guo Hui Liu105b21b2014-09-12 13:43:19 +08003107 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03003108 kvm_vcpu_kick(vcpu);
3109 }
3110}
3111
Andrew Jones7e44e442014-02-28 12:52:54 +01003112static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3113{
3114 struct kvm *kvm = v->kvm;
3115
Guo Hui Liu105b21b2014-09-12 13:43:19 +08003116 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
Andrew Jones7e44e442014-02-28 12:52:54 +01003117 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3118 KVMCLOCK_UPDATE_DELAY);
3119}
3120
Andrew Jones332967a2014-02-28 12:52:55 +01003121#define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3122
3123static void kvmclock_sync_fn(struct work_struct *work)
3124{
3125 struct delayed_work *dwork = to_delayed_work(work);
3126 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3127 kvmclock_sync_work);
3128 struct kvm *kvm = container_of(ka, struct kvm, arch);
3129
Marcelo Tosatti630994b2015-05-12 22:42:04 -03003130 if (!kvmclock_periodic_sync)
3131 return;
3132
Andrew Jones332967a2014-02-28 12:52:55 +01003133 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3134 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3135 KVMCLOCK_SYNC_PERIOD);
3136}
3137
Borislav Petkov191c8132019-04-18 18:32:50 +02003138/*
3139 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3140 */
3141static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3142{
3143 /* McStatusWrEn enabled? */
Sean Christopherson23493d02020-03-04 17:34:33 -08003144 if (guest_cpuid_is_amd_or_hygon(vcpu))
Borislav Petkov191c8132019-04-18 18:32:50 +02003145 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3146
3147 return false;
3148}
3149
Wanpeng Li9ffd9862017-10-19 06:47:56 -07003150static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Huang Ying890ca9a2009-05-11 16:48:15 +08003151{
3152 u64 mcg_cap = vcpu->arch.mcg_cap;
3153 unsigned bank_num = mcg_cap & 0xff;
Wanpeng Li9ffd9862017-10-19 06:47:56 -07003154 u32 msr = msr_info->index;
3155 u64 data = msr_info->data;
Huang Ying890ca9a2009-05-11 16:48:15 +08003156
3157 switch (msr) {
3158 case MSR_IA32_MCG_STATUS:
3159 vcpu->arch.mcg_status = data;
3160 break;
3161 case MSR_IA32_MCG_CTL:
Paolo Bonzini44883f02018-07-26 13:01:52 +02003162 if (!(mcg_cap & MCG_CTL_P) &&
3163 (data || !msr_info->host_initiated))
Huang Ying890ca9a2009-05-11 16:48:15 +08003164 return 1;
3165 if (data != 0 && data != ~(u64)0)
Paolo Bonzini44883f02018-07-26 13:01:52 +02003166 return 1;
Huang Ying890ca9a2009-05-11 16:48:15 +08003167 vcpu->arch.mcg_ctl = data;
3168 break;
3169 default:
3170 if (msr >= MSR_IA32_MC0_CTL &&
Chen Yucong81760dc2014-09-23 10:44:35 +08003171 msr < MSR_IA32_MCx_CTL(bank_num)) {
Marios Pomonis6ec4c5e2019-12-11 12:47:49 -08003172 u32 offset = array_index_nospec(
3173 msr - MSR_IA32_MC0_CTL,
3174 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3175
Andre Przywara114be422010-03-24 17:46:42 +01003176 /* only 0 or all 1s can be written to IA32_MCi_CTL
3177 * some Linux kernels though clear bit 10 in bank 4 to
3178 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
3179 * this to avoid an uncatched #GP in the guest
3180 */
Huang Ying890ca9a2009-05-11 16:48:15 +08003181 if ((offset & 0x3) == 0 &&
Andre Przywara114be422010-03-24 17:46:42 +01003182 data != 0 && (data | (1 << 10)) != ~(u64)0)
Huang Ying890ca9a2009-05-11 16:48:15 +08003183 return -1;
Borislav Petkov191c8132019-04-18 18:32:50 +02003184
3185 /* MCi_STATUS */
Wanpeng Li9ffd9862017-10-19 06:47:56 -07003186 if (!msr_info->host_initiated &&
Borislav Petkov191c8132019-04-18 18:32:50 +02003187 (offset & 0x3) == 1 && data != 0) {
3188 if (!can_set_mci_status(vcpu))
3189 return -1;
3190 }
3191
Huang Ying890ca9a2009-05-11 16:48:15 +08003192 vcpu->arch.mce_banks[offset] = data;
3193 break;
3194 }
3195 return 1;
3196 }
3197 return 0;
3198}
3199
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003200static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3201{
3202 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3203
3204 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3205}
3206
Gleb Natapov344d9582010-10-14 11:22:50 +02003207static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3208{
3209 gpa_t gpa = data & ~0x3f;
3210
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003211 /* Bits 4:5 are reserved, Should be zero */
3212 if (data & 0x30)
Gleb Natapov344d9582010-10-14 11:22:50 +02003213 return 1;
3214
Oliver Upton66570e92020-08-18 15:24:28 +00003215 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3216 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3217 return 1;
3218
3219 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3220 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3221 return 1;
3222
Wanpeng Li9d3c4472020-06-29 18:26:31 +08003223 if (!lapic_in_kernel(vcpu))
Vitaly Kuznetsovd831de12020-09-11 11:31:47 +02003224 return data ? 1 : 0;
Wanpeng Li9d3c4472020-06-29 18:26:31 +08003225
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003226 vcpu->arch.apf.msr_en_val = data;
Gleb Natapov344d9582010-10-14 11:22:50 +02003227
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003228 if (!kvm_pv_async_pf_enabled(vcpu)) {
Gleb Natapov344d9582010-10-14 11:22:50 +02003229 kvm_clear_async_pf_completion_queue(vcpu);
3230 kvm_async_pf_hash_reset(vcpu);
3231 return 0;
3232 }
3233
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003234 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
Vitaly Kuznetsov68fd66f2020-05-25 16:41:17 +02003235 sizeof(u64)))
Gleb Natapov344d9582010-10-14 11:22:50 +02003236 return 1;
3237
Gleb Natapov6adba522010-10-14 11:22:55 +02003238 vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
Wanpeng Li52a5c152017-07-13 18:30:42 -07003239 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003240
Gleb Natapov344d9582010-10-14 11:22:50 +02003241 kvm_async_pf_wakeup_all(vcpu);
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003242
3243 return 0;
3244}
3245
3246static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3247{
3248 /* Bits 8-63 are reserved */
3249 if (data >> 8)
3250 return 1;
3251
3252 if (!lapic_in_kernel(vcpu))
3253 return 1;
3254
3255 vcpu->arch.apf.msr_int_val = data;
3256
3257 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3258
Gleb Natapov344d9582010-10-14 11:22:50 +02003259 return 0;
3260}
3261
Glauber Costa12f9a482011-02-01 14:16:40 -05003262static void kvmclock_reset(struct kvm_vcpu *vcpu)
3263{
Andy Honig0b794592013-02-20 14:48:10 -08003264 vcpu->arch.pv_time_enabled = false;
Paolo Bonzini49dedf02019-10-10 12:49:22 +02003265 vcpu->arch.time = 0;
Glauber Costa12f9a482011-02-01 14:16:40 -05003266}
3267
Sean Christopherson77809382020-03-20 14:28:18 -07003268static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
Wanpeng Lif38a7b72017-12-12 17:33:04 -08003269{
3270 ++vcpu->stat.tlb_flush;
Jason Baronb36464772021-01-14 22:27:56 -05003271 static_call(kvm_x86_tlb_flush_all)(vcpu);
Wanpeng Lif38a7b72017-12-12 17:33:04 -08003272}
3273
Vitaly Kuznetsov0baedd72020-03-25 12:28:24 -04003274static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3275{
3276 ++vcpu->stat.tlb_flush;
Lai Jiangshanb53e84e2021-06-01 01:22:56 +08003277
3278 if (!tdp_enabled) {
Lai Jiangshan61b05a9f2021-10-19 19:01:54 +08003279 /*
Lai Jiangshanb53e84e2021-06-01 01:22:56 +08003280 * A TLB flush on behalf of the guest is equivalent to
3281 * INVPCID(all), toggling CR4.PGE, etc., which requires
Lai Jiangshan61b05a9f2021-10-19 19:01:54 +08003282 * a forced sync of the shadow page tables. Ensure all the
3283 * roots are synced and the guest TLB in hardware is clean.
Lai Jiangshanb53e84e2021-06-01 01:22:56 +08003284 */
Lai Jiangshan61b05a9f2021-10-19 19:01:54 +08003285 kvm_mmu_sync_roots(vcpu);
3286 kvm_mmu_sync_prev_roots(vcpu);
Lai Jiangshanb53e84e2021-06-01 01:22:56 +08003287 }
3288
Jason Baronb36464772021-01-14 22:27:56 -05003289 static_call(kvm_x86_tlb_flush_guest)(vcpu);
Vitaly Kuznetsov0baedd72020-03-25 12:28:24 -04003290}
3291
Sean Christopherson40e5f9082021-11-25 01:49:43 +00003292
3293static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3294{
3295 ++vcpu->stat.tlb_flush;
3296 static_call(kvm_x86_tlb_flush_current)(vcpu);
3297}
3298
3299/*
3300 * Service "local" TLB flush requests, which are specific to the current MMU
3301 * context. In addition to the generic event handling in vcpu_enter_guest(),
3302 * TLB flushes that are targeted at an MMU context also need to be serviced
3303 * prior before nested VM-Enter/VM-Exit.
3304 */
3305void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3306{
3307 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3308 kvm_vcpu_flush_tlb_current(vcpu);
3309
3310 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3311 kvm_vcpu_flush_tlb_guest(vcpu);
3312}
3313EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3314
Glauber Costac9aaa892011-07-11 15:28:14 -04003315static void record_steal_time(struct kvm_vcpu *vcpu)
3316{
David Woodhouse7e2175e2021-11-02 17:36:39 +00003317 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3318 struct kvm_steal_time __user *st;
3319 struct kvm_memslots *slots;
3320 u64 steal;
3321 u32 version;
Boris Ostrovskyb0431382019-12-05 03:45:32 +00003322
David Woodhouse30b5c852021-03-01 12:53:09 +00003323 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3324 kvm_xen_runstate_set_running(vcpu);
3325 return;
3326 }
3327
Glauber Costac9aaa892011-07-11 15:28:14 -04003328 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3329 return;
3330
David Woodhouse7e2175e2021-11-02 17:36:39 +00003331 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
Glauber Costac9aaa892011-07-11 15:28:14 -04003332 return;
3333
David Woodhouse7e2175e2021-11-02 17:36:39 +00003334 slots = kvm_memslots(vcpu->kvm);
3335
3336 if (unlikely(slots->generation != ghc->generation ||
3337 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3338 gfn_t gfn = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3339
3340 /* We rely on the fact that it fits in a single page. */
3341 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3342
3343 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gfn, sizeof(*st)) ||
3344 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3345 return;
3346 }
3347
3348 st = (struct kvm_steal_time __user *)ghc->hva;
Wanpeng Lif38a7b72017-12-12 17:33:04 -08003349 /*
3350 * Doing a TLB flush here, on the guest's behalf, can avoid
3351 * expensive IPIs.
3352 */
Oliver Upton66570e92020-08-18 15:24:28 +00003353 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
David Woodhouse7e2175e2021-11-02 17:36:39 +00003354 u8 st_preempted = 0;
3355 int err = -EFAULT;
3356
Paolo Bonzini3e067fd2021-11-12 02:53:41 -05003357 if (!user_access_begin(st, sizeof(*st)))
3358 return;
3359
David Woodhouse7e2175e2021-11-02 17:36:39 +00003360 asm volatile("1: xchgb %0, %2\n"
3361 "xor %1, %1\n"
3362 "2:\n"
3363 _ASM_EXTABLE_UA(1b, 2b)
David Woodhouse964b7aa2021-11-14 08:59:02 +00003364 : "+q" (st_preempted),
3365 "+&r" (err),
3366 "+m" (st->preempted));
David Woodhouse7e2175e2021-11-02 17:36:39 +00003367 if (err)
3368 goto out;
3369
3370 user_access_end();
3371
3372 vcpu->arch.st.preempted = 0;
Lai Jiangshanaf3511f2021-06-01 01:46:28 +08003373
Oliver Upton66570e92020-08-18 15:24:28 +00003374 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
Lai Jiangshanaf3511f2021-06-01 01:46:28 +08003375 st_preempted & KVM_VCPU_FLUSH_TLB);
3376 if (st_preempted & KVM_VCPU_FLUSH_TLB)
Oliver Upton66570e92020-08-18 15:24:28 +00003377 kvm_vcpu_flush_tlb_guest(vcpu);
David Woodhouse7e2175e2021-11-02 17:36:39 +00003378
3379 if (!user_access_begin(st, sizeof(*st)))
3380 goto dirty;
Wanpeng Li1eff0ad2021-05-18 05:00:33 -07003381 } else {
Paolo Bonzini3e067fd2021-11-12 02:53:41 -05003382 if (!user_access_begin(st, sizeof(*st)))
3383 return;
3384
David Woodhouse7e2175e2021-11-02 17:36:39 +00003385 unsafe_put_user(0, &st->preempted, out);
3386 vcpu->arch.st.preempted = 0;
Oliver Upton66570e92020-08-18 15:24:28 +00003387 }
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04003388
David Woodhouse7e2175e2021-11-02 17:36:39 +00003389 unsafe_get_user(version, &st->version, out);
3390 if (version & 1)
3391 version += 1; /* first time write, random junk */
Wanpeng Li35f3fae12016-05-03 11:43:10 +08003392
David Woodhouse7e2175e2021-11-02 17:36:39 +00003393 version += 1;
3394 unsafe_put_user(version, &st->version, out);
Wanpeng Li35f3fae12016-05-03 11:43:10 +08003395
3396 smp_wmb();
3397
David Woodhouse7e2175e2021-11-02 17:36:39 +00003398 unsafe_get_user(steal, &st->steal, out);
3399 steal += current->sched_info.run_delay -
Liang Chenc54cdf12016-03-16 19:33:16 +08003400 vcpu->arch.st.last_steal;
3401 vcpu->arch.st.last_steal = current->sched_info.run_delay;
David Woodhouse7e2175e2021-11-02 17:36:39 +00003402 unsafe_put_user(steal, &st->steal, out);
Wanpeng Li35f3fae12016-05-03 11:43:10 +08003403
David Woodhouse7e2175e2021-11-02 17:36:39 +00003404 version += 1;
3405 unsafe_put_user(version, &st->version, out);
Wanpeng Li35f3fae12016-05-03 11:43:10 +08003406
David Woodhouse7e2175e2021-11-02 17:36:39 +00003407 out:
3408 user_access_end();
3409 dirty:
3410 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
Glauber Costac9aaa892011-07-11 15:28:14 -04003411}
3412
Will Auld8fe8ab42012-11-29 12:42:12 -08003413int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Carsten Otte15c4a642007-10-30 18:44:17 +01003414{
Gleb Natapov57537852012-01-15 14:17:22 +02003415 bool pr = false;
Will Auld8fe8ab42012-11-29 12:42:12 -08003416 u32 msr = msr_info->index;
3417 u64 data = msr_info->data;
Gleb Natapov57537852012-01-15 14:17:22 +02003418
Joao Martins1232f8e2018-06-13 06:10:37 -04003419 if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
Joao Martins23200b72018-06-13 09:55:44 -04003420 return kvm_xen_write_hypercall_page(vcpu, data);
Joao Martins1232f8e2018-06-13 06:10:37 -04003421
Carsten Otte15c4a642007-10-30 18:44:17 +01003422 switch (msr) {
Borislav Petkov2e32b712013-02-19 19:33:13 +01003423 case MSR_AMD64_NB_CFG:
Borislav Petkov2e32b712013-02-19 19:33:13 +01003424 case MSR_IA32_UCODE_WRITE:
3425 case MSR_VM_HSAVE_PA:
3426 case MSR_AMD64_PATCH_LOADER:
3427 case MSR_AMD64_BU_CFG2:
Ladi Prosek405a3532017-04-06 15:22:20 +02003428 case MSR_AMD64_DC_CFG:
Eduardo Habkost0e1b8692018-12-17 22:34:18 -02003429 case MSR_F15H_EX_CFG:
Borislav Petkov2e32b712013-02-19 19:33:13 +01003430 break;
3431
Wanpeng Li518e7b92018-02-28 14:03:31 +08003432 case MSR_IA32_UCODE_REV:
3433 if (msr_info->host_initiated)
3434 vcpu->arch.microcode_version = data;
3435 break;
Sean Christopherson0cf91352019-03-07 15:43:02 -08003436 case MSR_IA32_ARCH_CAPABILITIES:
3437 if (!msr_info->host_initiated)
3438 return 1;
3439 vcpu->arch.arch_capabilities = data;
3440 break;
Vitaly Kuznetsovd574c532020-07-10 17:25:59 +02003441 case MSR_IA32_PERF_CAPABILITIES: {
3442 struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
3443
3444 if (!msr_info->host_initiated)
3445 return 1;
Vitaly Kuznetsov1aa2abb2021-12-16 17:52:13 +01003446 if (kvm_get_msr_feature(&msr_ent))
Vitaly Kuznetsovd574c532020-07-10 17:25:59 +02003447 return 1;
3448 if (data & ~msr_ent.data)
3449 return 1;
3450
3451 vcpu->arch.perf_capabilities = data;
3452
3453 return 0;
3454 }
Carsten Otte15c4a642007-10-30 18:44:17 +01003455 case MSR_EFER:
Sean Christopherson11988492019-04-02 08:19:15 -07003456 return set_efer(vcpu, msr_info);
Andre Przywara8f1589d2009-06-24 12:44:33 +02003457 case MSR_K7_HWCR:
3458 data &= ~(u64)0x40; /* ignore flush filter disable */
Joerg Roedel82494022010-02-24 18:59:16 +01003459 data &= ~(u64)0x100; /* ignore ignne emulation enable */
Nicolae Mogoreanua223c312012-02-21 13:44:21 -08003460 data &= ~(u64)0x8; /* ignore TLB cache disable */
Borislav Petkov191c8132019-04-18 18:32:50 +02003461
3462 /* Handle McStatusWrEn */
3463 if (data == BIT_ULL(18)) {
3464 vcpu->arch.msr_hwcr = data;
3465 } else if (data != 0) {
Christoffer Dalla737f252012-06-03 21:17:48 +03003466 vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
3467 data);
Andre Przywara8f1589d2009-06-24 12:44:33 +02003468 return 1;
3469 }
Carsten Otte15c4a642007-10-30 18:44:17 +01003470 break;
Andre Przywaraf7c6d142009-07-02 15:04:14 +02003471 case MSR_FAM10H_MMIO_CONF_BASE:
3472 if (data != 0) {
Christoffer Dalla737f252012-06-03 21:17:48 +03003473 vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
3474 "0x%llx\n", data);
Andre Przywaraf7c6d142009-07-02 15:04:14 +02003475 return 1;
3476 }
Carsten Otte15c4a642007-10-30 18:44:17 +01003477 break;
Avi Kivity9ba075a2008-05-26 20:06:35 +03003478 case 0x200 ... 0x2ff:
Xiao Guangrongff536042015-06-15 16:55:22 +08003479 return kvm_mtrr_set_msr(vcpu, msr, data);
Carsten Otte15c4a642007-10-30 18:44:17 +01003480 case MSR_IA32_APICBASE:
Jan Kiszka58cb6282014-01-24 16:48:44 +01003481 return kvm_set_apic_base(vcpu, msr_info);
Xiaoyao Libf10bd02020-06-16 15:33:07 +08003482 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
Gleb Natapov0105d1a2009-07-05 17:39:36 +03003483 return kvm_x2apic_msr_write(vcpu, msr, data);
Dave Hansen09141ec2020-03-05 09:47:06 -08003484 case MSR_IA32_TSC_DEADLINE:
Liu, Jinsonga3e06bb2011-09-22 16:55:52 +08003485 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3486 break;
Will Auldba904632012-11-29 12:42:50 -08003487 case MSR_IA32_TSC_ADJUST:
Radim Krčmářd6321d42017-08-05 00:12:49 +02003488 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
Will Auldba904632012-11-29 12:42:50 -08003489 if (!msr_info->host_initiated) {
Chris J Argesd913b902014-11-12 21:00:39 -06003490 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
Haozhong Zhangd7add052015-08-07 11:24:32 +08003491 adjust_tsc_offset_guest(vcpu, adj);
Zelin Dengd9130a22021-04-28 10:22:01 +08003492 /* Before back to guest, tsc_timestamp must be adjusted
3493 * as well, otherwise guest's percpu pvclock time could jump.
3494 */
3495 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Will Auldba904632012-11-29 12:42:50 -08003496 }
3497 vcpu->arch.ia32_tsc_adjust_msr = data;
3498 }
3499 break;
Carsten Otte15c4a642007-10-30 18:44:17 +01003500 case MSR_IA32_MISC_ENABLE:
Wanpeng Li511a85562019-05-21 14:06:54 +08003501 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3502 ((vcpu->arch.ia32_misc_enable_msr ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3503 if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
3504 return 1;
3505 vcpu->arch.ia32_misc_enable_msr = data;
Xiaoyao Liaedbaf42020-07-09 12:34:23 +08003506 kvm_update_cpuid_runtime(vcpu);
Wanpeng Li511a85562019-05-21 14:06:54 +08003507 } else {
3508 vcpu->arch.ia32_misc_enable_msr = data;
3509 }
Carsten Otte15c4a642007-10-30 18:44:17 +01003510 break;
Paolo Bonzini64d60672015-05-07 11:36:11 +02003511 case MSR_IA32_SMBASE:
3512 if (!msr_info->host_initiated)
3513 return 1;
3514 vcpu->arch.smbase = data;
3515 break;
Paolo Bonzini73f624f2019-06-06 14:32:59 +02003516 case MSR_IA32_POWER_CTL:
3517 vcpu->arch.msr_ia32_power_ctl = data;
3518 break;
Paolo Bonzinidd259932018-04-13 11:38:35 +02003519 case MSR_IA32_TSC:
Paolo Bonzini0c899c22020-09-24 14:45:27 +02003520 if (msr_info->host_initiated) {
3521 kvm_synchronize_tsc(vcpu, data);
3522 } else {
Ilias Stamatis9b399df2021-05-26 19:44:10 +01003523 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
Paolo Bonzini0c899c22020-09-24 14:45:27 +02003524 adjust_tsc_offset_guest(vcpu, adj);
3525 vcpu->arch.ia32_tsc_adjust_msr += adj;
3526 }
Paolo Bonzinidd259932018-04-13 11:38:35 +02003527 break;
Aaron Lewis864e2ab2019-10-21 16:30:26 -07003528 case MSR_IA32_XSS:
3529 if (!msr_info->host_initiated &&
3530 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3531 return 1;
3532 /*
Sean Christophersona1bead22020-03-02 15:57:00 -08003533 * KVM supports exposing PT to the guest, but does not support
3534 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3535 * XSAVES/XRSTORS to save/restore PT MSRs.
Aaron Lewis864e2ab2019-10-21 16:30:26 -07003536 */
Paolo Bonzini408e9a32020-03-05 16:11:56 +01003537 if (data & ~supported_xss)
Aaron Lewis864e2ab2019-10-21 16:30:26 -07003538 return 1;
3539 vcpu->arch.ia32_xss = data;
Like Xu4c282e52022-01-26 17:22:25 +00003540 kvm_update_cpuid_runtime(vcpu);
Aaron Lewis864e2ab2019-10-21 16:30:26 -07003541 break;
Liran Alon52797bf2017-11-15 13:43:14 +02003542 case MSR_SMI_COUNT:
3543 if (!msr_info->host_initiated)
3544 return 1;
3545 vcpu->arch.smi_count = data;
3546 break;
Glauber Costa11c6bff2010-05-11 12:17:41 -04003547 case MSR_KVM_WALL_CLOCK_NEW:
Oliver Upton66570e92020-08-18 15:24:28 +00003548 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3549 return 1;
3550
Joao Martins629b5342018-06-28 15:06:43 -04003551 vcpu->kvm->arch.wall_clock = data;
3552 kvm_write_wall_clock(vcpu->kvm, data, 0);
Oliver Upton66570e92020-08-18 15:24:28 +00003553 break;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003554 case MSR_KVM_WALL_CLOCK:
Oliver Upton66570e92020-08-18 15:24:28 +00003555 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3556 return 1;
3557
Joao Martins629b5342018-06-28 15:06:43 -04003558 vcpu->kvm->arch.wall_clock = data;
3559 kvm_write_wall_clock(vcpu->kvm, data, 0);
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003560 break;
Glauber Costa11c6bff2010-05-11 12:17:41 -04003561 case MSR_KVM_SYSTEM_TIME_NEW:
Oliver Upton66570e92020-08-18 15:24:28 +00003562 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3563 return 1;
3564
Oliver Upton5b9bb0e2020-08-18 15:24:26 +00003565 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003566 break;
Oliver Upton5b9bb0e2020-08-18 15:24:26 +00003567 case MSR_KVM_SYSTEM_TIME:
Oliver Upton66570e92020-08-18 15:24:28 +00003568 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3569 return 1;
3570
3571 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
Oliver Upton5b9bb0e2020-08-18 15:24:26 +00003572 break;
Gleb Natapov344d9582010-10-14 11:22:50 +02003573 case MSR_KVM_ASYNC_PF_EN:
Oliver Upton66570e92020-08-18 15:24:28 +00003574 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3575 return 1;
3576
Gleb Natapov344d9582010-10-14 11:22:50 +02003577 if (kvm_pv_enable_async_pf(vcpu, data))
3578 return 1;
3579 break;
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003580 case MSR_KVM_ASYNC_PF_INT:
Oliver Upton66570e92020-08-18 15:24:28 +00003581 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3582 return 1;
3583
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003584 if (kvm_pv_enable_async_pf_int(vcpu, data))
3585 return 1;
3586 break;
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02003587 case MSR_KVM_ASYNC_PF_ACK:
Vitaly Kuznetsov0a31df62021-07-22 14:30:18 +02003588 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
Oliver Upton66570e92020-08-18 15:24:28 +00003589 return 1;
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02003590 if (data & 0x1) {
3591 vcpu->arch.apf.pageready_pending = false;
3592 kvm_check_async_pf_completion(vcpu);
3593 }
3594 break;
Glauber Costac9aaa892011-07-11 15:28:14 -04003595 case MSR_KVM_STEAL_TIME:
Oliver Upton66570e92020-08-18 15:24:28 +00003596 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3597 return 1;
Glauber Costac9aaa892011-07-11 15:28:14 -04003598
3599 if (unlikely(!sched_info_on()))
3600 return 1;
3601
3602 if (data & KVM_STEAL_RESERVED_MASK)
3603 return 1;
3604
Glauber Costac9aaa892011-07-11 15:28:14 -04003605 vcpu->arch.st.msr_val = data;
3606
3607 if (!(data & KVM_MSR_ENABLED))
3608 break;
3609
Glauber Costac9aaa892011-07-11 15:28:14 -04003610 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3611
3612 break;
Michael S. Tsirkinae7a2a32012-06-24 19:25:07 +03003613 case MSR_KVM_PV_EOI_EN:
Oliver Upton66570e92020-08-18 15:24:28 +00003614 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3615 return 1;
3616
Vitaly Kuznetsov77c33232021-11-08 16:28:18 +01003617 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
Michael S. Tsirkinae7a2a32012-06-24 19:25:07 +03003618 return 1;
3619 break;
Glauber Costac9aaa892011-07-11 15:28:14 -04003620
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -03003621 case MSR_KVM_POLL_CONTROL:
Oliver Upton66570e92020-08-18 15:24:28 +00003622 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3623 return 1;
3624
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -03003625 /* only enable bit supported */
3626 if (data & (-1ULL << 1))
3627 return 1;
3628
3629 vcpu->arch.msr_kvm_poll_control = data;
3630 break;
3631
Huang Ying890ca9a2009-05-11 16:48:15 +08003632 case MSR_IA32_MCG_CTL:
3633 case MSR_IA32_MCG_STATUS:
Chen Yucong81760dc2014-09-23 10:44:35 +08003634 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
Wanpeng Li9ffd9862017-10-19 06:47:56 -07003635 return set_msr_mce(vcpu, msr_info);
Andre Przywara71db6022009-06-12 22:01:29 +02003636
Wei Huang6912ac32015-06-12 01:34:56 -04003637 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3638 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05003639 pr = true;
3640 fallthrough;
Wei Huang6912ac32015-06-12 01:34:56 -04003641 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3642 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
Wei Huangc6702c92015-06-19 13:44:45 +02003643 if (kvm_pmu_is_valid_msr(vcpu, msr))
Paolo Bonziniafd80d82013-03-28 17:18:35 +01003644 return kvm_pmu_set_msr(vcpu, msr_info);
Gleb Natapov57537852012-01-15 14:17:22 +02003645
3646 if (pr || data != 0)
Christoffer Dalla737f252012-06-03 21:17:48 +03003647 vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
3648 "0x%x data 0x%llx\n", msr, data);
Gleb Natapov57537852012-01-15 14:17:22 +02003649 break;
Jes Sorensen84e0cef2010-09-01 11:42:04 +02003650 case MSR_K7_CLK_CTL:
3651 /*
3652 * Ignore all writes to this no longer documented MSR.
3653 * Writes are only relevant for old K7 processors,
3654 * all pre-dating SVM, but a recommended workaround from
Guo Chao4a969982012-06-28 15:17:27 +08003655 * AMD for these chips. It is possible to specify the
Jes Sorensen84e0cef2010-09-01 11:42:04 +02003656 * affected processor models on the command line, hence
3657 * the need to ignore the workaround.
3658 */
3659 break;
Gleb Natapov55cd8e52010-01-17 15:51:22 +02003660 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
Jon Doronf97f5a52020-05-29 16:45:40 +03003661 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3662 case HV_X64_MSR_SYNDBG_OPTIONS:
Andrey Smetanine7d95132015-07-03 15:01:37 +03003663 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3664 case HV_X64_MSR_CRASH_CTL:
Andrey Smetanin1f4b34f2015-11-30 19:22:21 +03003665 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
Vitaly Kuznetsova2e164e2018-03-01 15:15:12 +01003666 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3667 case HV_X64_MSR_TSC_EMULATION_CONTROL:
3668 case HV_X64_MSR_TSC_EMULATION_STATUS:
Andrey Smetanine7d95132015-07-03 15:01:37 +03003669 return kvm_hv_set_msr_common(vcpu, msr, data,
3670 msr_info->host_initiated);
john cooper91c9c3e2011-01-21 00:21:00 -05003671 case MSR_IA32_BBL_CR_CTL3:
3672 /* Drop writes to this legacy MSR -- see rdmsr
3673 * counterpart for further detail.
3674 */
Eyal Moscovicifab0aa32017-11-08 14:32:08 +02003675 if (report_ignored_msrs)
3676 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
3677 msr, data);
john cooper91c9c3e2011-01-21 00:21:00 -05003678 break;
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05003679 case MSR_AMD64_OSVW_ID_LENGTH:
Radim Krčmářd6321d42017-08-05 00:12:49 +02003680 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05003681 return 1;
3682 vcpu->arch.osvw.length = data;
3683 break;
3684 case MSR_AMD64_OSVW_STATUS:
Radim Krčmářd6321d42017-08-05 00:12:49 +02003685 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05003686 return 1;
3687 vcpu->arch.osvw.status = data;
3688 break;
Kyle Hueydb2336a2017-03-20 01:16:28 -07003689 case MSR_PLATFORM_INFO:
3690 if (!msr_info->host_initiated ||
Kyle Hueydb2336a2017-03-20 01:16:28 -07003691 (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
3692 cpuid_fault_enabled(vcpu)))
3693 return 1;
3694 vcpu->arch.msr_platform_info = data;
3695 break;
3696 case MSR_MISC_FEATURES_ENABLES:
3697 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
3698 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3699 !supports_cpuid_fault(vcpu)))
3700 return 1;
3701 vcpu->arch.msr_misc_features_enables = data;
3702 break;
Jing Liu820a6ee2022-01-05 04:35:21 -08003703#ifdef CONFIG_X86_64
3704 case MSR_IA32_XFD:
3705 if (!msr_info->host_initiated &&
3706 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3707 return 1;
3708
3709 if (data & ~(XFEATURE_MASK_USER_DYNAMIC &
3710 vcpu->arch.guest_supported_xcr0))
3711 return 1;
3712
3713 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
3714 break;
Jing Liu548e8362022-01-05 04:35:24 -08003715 case MSR_IA32_XFD_ERR:
3716 if (!msr_info->host_initiated &&
3717 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
3718 return 1;
3719
3720 if (data & ~(XFEATURE_MASK_USER_DYNAMIC &
3721 vcpu->arch.guest_supported_xcr0))
3722 return 1;
3723
3724 vcpu->arch.guest_fpu.xfd_err = data;
3725 break;
Jing Liu820a6ee2022-01-05 04:35:21 -08003726#endif
Carsten Otte15c4a642007-10-30 18:44:17 +01003727 default:
Wei Huangc6702c92015-06-19 13:44:45 +02003728 if (kvm_pmu_is_valid_msr(vcpu, msr))
Paolo Bonziniafd80d82013-03-28 17:18:35 +01003729 return kvm_pmu_set_msr(vcpu, msr_info);
Peter Xu6abe9c12020-06-22 18:04:41 -04003730 return KVM_MSR_RET_INVALID;
Carsten Otte15c4a642007-10-30 18:44:17 +01003731 }
3732 return 0;
3733}
3734EXPORT_SYMBOL_GPL(kvm_set_msr_common);
3735
Paolo Bonzini44883f02018-07-26 13:01:52 +02003736static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
Huang Ying890ca9a2009-05-11 16:48:15 +08003737{
3738 u64 data;
3739 u64 mcg_cap = vcpu->arch.mcg_cap;
3740 unsigned bank_num = mcg_cap & 0xff;
3741
3742 switch (msr) {
3743 case MSR_IA32_P5_MC_ADDR:
3744 case MSR_IA32_P5_MC_TYPE:
3745 data = 0;
3746 break;
3747 case MSR_IA32_MCG_CAP:
3748 data = vcpu->arch.mcg_cap;
3749 break;
3750 case MSR_IA32_MCG_CTL:
Paolo Bonzini44883f02018-07-26 13:01:52 +02003751 if (!(mcg_cap & MCG_CTL_P) && !host)
Huang Ying890ca9a2009-05-11 16:48:15 +08003752 return 1;
3753 data = vcpu->arch.mcg_ctl;
3754 break;
3755 case MSR_IA32_MCG_STATUS:
3756 data = vcpu->arch.mcg_status;
3757 break;
3758 default:
3759 if (msr >= MSR_IA32_MC0_CTL &&
Chen Yucong81760dc2014-09-23 10:44:35 +08003760 msr < MSR_IA32_MCx_CTL(bank_num)) {
Marios Pomonis6ec4c5e2019-12-11 12:47:49 -08003761 u32 offset = array_index_nospec(
3762 msr - MSR_IA32_MC0_CTL,
3763 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
3764
Huang Ying890ca9a2009-05-11 16:48:15 +08003765 data = vcpu->arch.mce_banks[offset];
3766 break;
3767 }
3768 return 1;
3769 }
3770 *pdata = data;
3771 return 0;
3772}
3773
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003774int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
Carsten Otte15c4a642007-10-30 18:44:17 +01003775{
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003776 switch (msr_info->index) {
Carsten Otte15c4a642007-10-30 18:44:17 +01003777 case MSR_IA32_PLATFORM_ID:
Carsten Otte15c4a642007-10-30 18:44:17 +01003778 case MSR_IA32_EBL_CR_POWERON:
Alexander Grafb5e2fec2008-07-22 08:00:45 +02003779 case MSR_IA32_LASTBRANCHFROMIP:
3780 case MSR_IA32_LASTBRANCHTOIP:
3781 case MSR_IA32_LASTINTFROMIP:
3782 case MSR_IA32_LASTINTTOIP:
Brijesh Singh059e5c32021-04-27 06:16:36 -05003783 case MSR_AMD64_SYSCFG:
Paolo Bonzini3afb1122015-09-18 17:33:04 +02003784 case MSR_K8_TSEG_ADDR:
3785 case MSR_K8_TSEG_MASK:
Avi Kivity61a6bd62008-12-29 17:32:28 +02003786 case MSR_VM_HSAVE_PA:
Andre Przywara1fdbd482009-06-24 12:44:34 +02003787 case MSR_K8_INT_PENDING_MSG:
Andre Przywarac323c0e2009-06-24 15:37:05 +02003788 case MSR_AMD64_NB_CFG:
Andre Przywaraf7c6d142009-07-02 15:04:14 +02003789 case MSR_FAM10H_MMIO_CONF_BASE:
Borislav Petkov2e32b712013-02-19 19:33:13 +01003790 case MSR_AMD64_BU_CFG2:
Dmitry Bilunov0c2df2a2016-05-31 17:38:24 +03003791 case MSR_IA32_PERF_CTL:
Ladi Prosek405a3532017-04-06 15:22:20 +02003792 case MSR_AMD64_DC_CFG:
Eduardo Habkost0e1b8692018-12-17 22:34:18 -02003793 case MSR_F15H_EX_CFG:
Venkatesh Srinivas2ca1a062020-04-16 11:42:54 -07003794 /*
3795 * Intel Sandy Bridge CPUs must support the RAPL (running average power
3796 * limit) MSRs. Just return 0, as we do not want to expose the host
3797 * data here. Do not conditionalize this on CPUID, as KVM does not do
3798 * so for existing CPU-specific MSRs.
3799 */
3800 case MSR_RAPL_POWER_UNIT:
3801 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
3802 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
3803 case MSR_PKG_ENERGY_STATUS: /* Total package */
3804 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003805 msr_info->data = 0;
Carsten Otte15c4a642007-10-30 18:44:17 +01003806 break;
Janakarajan Natarajanc51eb522018-02-05 13:24:52 -06003807 case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
Vitaly Kuznetsovc28fa562021-03-29 14:48:04 +02003808 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3809 return kvm_pmu_get_msr(vcpu, msr_info);
3810 if (!msr_info->host_initiated)
3811 return 1;
3812 msr_info->data = 0;
3813 break;
Wei Huang6912ac32015-06-12 01:34:56 -04003814 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
3815 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
3816 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
3817 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
Wei Huangc6702c92015-06-19 13:44:45 +02003818 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
Wei Wangcbd71752020-05-29 15:43:44 +08003819 return kvm_pmu_get_msr(vcpu, msr_info);
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003820 msr_info->data = 0;
Gleb Natapov57537852012-01-15 14:17:22 +02003821 break;
Marcelo Tosatti742bc672011-07-29 19:44:21 -03003822 case MSR_IA32_UCODE_REV:
Wanpeng Li518e7b92018-02-28 14:03:31 +08003823 msr_info->data = vcpu->arch.microcode_version;
Marcelo Tosatti742bc672011-07-29 19:44:21 -03003824 break;
Sean Christopherson0cf91352019-03-07 15:43:02 -08003825 case MSR_IA32_ARCH_CAPABILITIES:
3826 if (!msr_info->host_initiated &&
3827 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3828 return 1;
3829 msr_info->data = vcpu->arch.arch_capabilities;
3830 break;
Vitaly Kuznetsovd574c532020-07-10 17:25:59 +02003831 case MSR_IA32_PERF_CAPABILITIES:
3832 if (!msr_info->host_initiated &&
3833 !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
3834 return 1;
3835 msr_info->data = vcpu->arch.perf_capabilities;
3836 break;
Paolo Bonzini73f624f2019-06-06 14:32:59 +02003837 case MSR_IA32_POWER_CTL:
3838 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
3839 break;
Maxim Levitskycc5b54d2020-09-21 13:38:05 +03003840 case MSR_IA32_TSC: {
3841 /*
3842 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
3843 * even when not intercepted. AMD manual doesn't explicitly
3844 * state this but appears to behave the same.
3845 *
Maxim Levitskyee6fa052020-09-21 13:38:05 +03003846 * On userspace reads and writes, however, we unconditionally
Paolo Bonzinic0623f52020-10-21 18:05:58 -04003847 * return L1's TSC value to ensure backwards-compatible
Maxim Levitskyee6fa052020-09-21 13:38:05 +03003848 * behavior for migration.
Maxim Levitskycc5b54d2020-09-21 13:38:05 +03003849 */
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01003850 u64 offset, ratio;
Maxim Levitskycc5b54d2020-09-21 13:38:05 +03003851
Ilias Stamatisfe3eb502021-05-26 19:44:11 +01003852 if (msr_info->host_initiated) {
3853 offset = vcpu->arch.l1_tsc_offset;
3854 ratio = vcpu->arch.l1_tsc_scaling_ratio;
3855 } else {
3856 offset = vcpu->arch.tsc_offset;
3857 ratio = vcpu->arch.tsc_scaling_ratio;
3858 }
3859
3860 msr_info->data = kvm_scale_tsc(vcpu, rdtsc(), ratio) + offset;
Paolo Bonzinidd259932018-04-13 11:38:35 +02003861 break;
Maxim Levitskycc5b54d2020-09-21 13:38:05 +03003862 }
Avi Kivity9ba075a2008-05-26 20:06:35 +03003863 case MSR_MTRRcap:
Avi Kivity9ba075a2008-05-26 20:06:35 +03003864 case 0x200 ... 0x2ff:
Xiao Guangrongff536042015-06-15 16:55:22 +08003865 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
Carsten Otte15c4a642007-10-30 18:44:17 +01003866 case 0xcd: /* fsb frequency */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003867 msr_info->data = 3;
Carsten Otte15c4a642007-10-30 18:44:17 +01003868 break;
Jes Sorensen7b914092010-09-09 12:06:46 +02003869 /*
3870 * MSR_EBC_FREQUENCY_ID
3871 * Conservative value valid for even the basic CPU models.
3872 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3873 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3874 * and 266MHz for model 3, or 4. Set Core Clock
3875 * Frequency to System Bus Frequency Ratio to 1 (bits
3876 * 31:24) even though these are only valid for CPU
3877 * models > 2, however guests may end up dividing or
3878 * multiplying by zero otherwise.
3879 */
3880 case MSR_EBC_FREQUENCY_ID:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003881 msr_info->data = 1 << 24;
Jes Sorensen7b914092010-09-09 12:06:46 +02003882 break;
Carsten Otte15c4a642007-10-30 18:44:17 +01003883 case MSR_IA32_APICBASE:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003884 msr_info->data = kvm_get_apic_base(vcpu);
Carsten Otte15c4a642007-10-30 18:44:17 +01003885 break;
Xiaoyao Libf10bd02020-06-16 15:33:07 +08003886 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003887 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
Dave Hansen09141ec2020-03-05 09:47:06 -08003888 case MSR_IA32_TSC_DEADLINE:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003889 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
Liu, Jinsonga3e06bb2011-09-22 16:55:52 +08003890 break;
Will Auldba904632012-11-29 12:42:50 -08003891 case MSR_IA32_TSC_ADJUST:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003892 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
Will Auldba904632012-11-29 12:42:50 -08003893 break;
Carsten Otte15c4a642007-10-30 18:44:17 +01003894 case MSR_IA32_MISC_ENABLE:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003895 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
Carsten Otte15c4a642007-10-30 18:44:17 +01003896 break;
Paolo Bonzini64d60672015-05-07 11:36:11 +02003897 case MSR_IA32_SMBASE:
3898 if (!msr_info->host_initiated)
3899 return 1;
3900 msr_info->data = vcpu->arch.smbase;
Carsten Otte15c4a642007-10-30 18:44:17 +01003901 break;
Liran Alon52797bf2017-11-15 13:43:14 +02003902 case MSR_SMI_COUNT:
3903 msr_info->data = vcpu->arch.smi_count;
3904 break;
Alexander Graf847f0ad2008-02-21 12:11:01 +01003905 case MSR_IA32_PERF_STATUS:
3906 /* TSC increment by tick */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003907 msr_info->data = 1000ULL;
Alexander Graf847f0ad2008-02-21 12:11:01 +01003908 /* CPU multiplier */
Nicolas Ioossb0996ae2015-06-29 18:39:23 +08003909 msr_info->data |= (((uint64_t)4ULL) << 40);
Alexander Graf847f0ad2008-02-21 12:11:01 +01003910 break;
Carsten Otte15c4a642007-10-30 18:44:17 +01003911 case MSR_EFER:
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003912 msr_info->data = vcpu->arch.efer;
Carsten Otte15c4a642007-10-30 18:44:17 +01003913 break;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003914 case MSR_KVM_WALL_CLOCK:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003915 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3916 return 1;
3917
3918 msr_info->data = vcpu->kvm->arch.wall_clock;
3919 break;
Glauber Costa11c6bff2010-05-11 12:17:41 -04003920 case MSR_KVM_WALL_CLOCK_NEW:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003921 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3922 return 1;
3923
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003924 msr_info->data = vcpu->kvm->arch.wall_clock;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003925 break;
3926 case MSR_KVM_SYSTEM_TIME:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003927 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3928 return 1;
3929
3930 msr_info->data = vcpu->arch.time;
3931 break;
Glauber Costa11c6bff2010-05-11 12:17:41 -04003932 case MSR_KVM_SYSTEM_TIME_NEW:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003933 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3934 return 1;
3935
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003936 msr_info->data = vcpu->arch.time;
Glauber de Oliveira Costa18068522008-02-15 17:52:47 -02003937 break;
Gleb Natapov344d9582010-10-14 11:22:50 +02003938 case MSR_KVM_ASYNC_PF_EN:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003939 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
3940 return 1;
3941
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003942 msr_info->data = vcpu->arch.apf.msr_en_val;
3943 break;
3944 case MSR_KVM_ASYNC_PF_INT:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003945 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
3946 return 1;
3947
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +02003948 msr_info->data = vcpu->arch.apf.msr_int_val;
Gleb Natapov344d9582010-10-14 11:22:50 +02003949 break;
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02003950 case MSR_KVM_ASYNC_PF_ACK:
Vitaly Kuznetsov0a31df62021-07-22 14:30:18 +02003951 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
Oliver Upton1930e5d2020-10-27 16:10:41 -07003952 return 1;
3953
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02003954 msr_info->data = 0;
3955 break;
Glauber Costac9aaa892011-07-11 15:28:14 -04003956 case MSR_KVM_STEAL_TIME:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003957 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
3958 return 1;
3959
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003960 msr_info->data = vcpu->arch.st.msr_val;
Glauber Costac9aaa892011-07-11 15:28:14 -04003961 break;
Michael S. Tsirkin1d921282012-08-26 18:00:29 +03003962 case MSR_KVM_PV_EOI_EN:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003963 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
3964 return 1;
3965
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003966 msr_info->data = vcpu->arch.pv_eoi.msr_val;
Michael S. Tsirkin1d921282012-08-26 18:00:29 +03003967 break;
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -03003968 case MSR_KVM_POLL_CONTROL:
Oliver Upton1930e5d2020-10-27 16:10:41 -07003969 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
3970 return 1;
3971
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -03003972 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3973 break;
Huang Ying890ca9a2009-05-11 16:48:15 +08003974 case MSR_IA32_P5_MC_ADDR:
3975 case MSR_IA32_P5_MC_TYPE:
3976 case MSR_IA32_MCG_CAP:
3977 case MSR_IA32_MCG_CTL:
3978 case MSR_IA32_MCG_STATUS:
Chen Yucong81760dc2014-09-23 10:44:35 +08003979 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
Paolo Bonzini44883f02018-07-26 13:01:52 +02003980 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3981 msr_info->host_initiated);
Aaron Lewis864e2ab2019-10-21 16:30:26 -07003982 case MSR_IA32_XSS:
3983 if (!msr_info->host_initiated &&
3984 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3985 return 1;
3986 msr_info->data = vcpu->arch.ia32_xss;
3987 break;
Jes Sorensen84e0cef2010-09-01 11:42:04 +02003988 case MSR_K7_CLK_CTL:
3989 /*
3990 * Provide expected ramp-up count for K7. All other
3991 * are set to zero, indicating minimum divisors for
3992 * every field.
3993 *
3994 * This prevents guest kernels on AMD host with CPU
3995 * type 6, model 8 and higher from exploding due to
3996 * the rdmsr failing.
3997 */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02003998 msr_info->data = 0x20000000;
Jes Sorensen84e0cef2010-09-01 11:42:04 +02003999 break;
Gleb Natapov55cd8e52010-01-17 15:51:22 +02004000 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
Jon Doronf97f5a52020-05-29 16:45:40 +03004001 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4002 case HV_X64_MSR_SYNDBG_OPTIONS:
Andrey Smetanine7d95132015-07-03 15:01:37 +03004003 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4004 case HV_X64_MSR_CRASH_CTL:
Andrey Smetanin1f4b34f2015-11-30 19:22:21 +03004005 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
Vitaly Kuznetsova2e164e2018-03-01 15:15:12 +01004006 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4007 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4008 case HV_X64_MSR_TSC_EMULATION_STATUS:
Andrey Smetanine83d5882015-07-03 15:01:34 +03004009 return kvm_hv_get_msr_common(vcpu,
Paolo Bonzini44883f02018-07-26 13:01:52 +02004010 msr_info->index, &msr_info->data,
4011 msr_info->host_initiated);
john cooper91c9c3e2011-01-21 00:21:00 -05004012 case MSR_IA32_BBL_CR_CTL3:
4013 /* This legacy MSR exists but isn't fully documented in current
4014 * silicon. It is however accessed by winxp in very narrow
4015 * scenarios where it sets bit #19, itself documented as
4016 * a "reserved" bit. Best effort attempt to source coherent
4017 * read data here should the balance of the register be
4018 * interpreted by the guest:
4019 *
4020 * L2 cache control register 3: 64GB range, 256KB size,
4021 * enabled, latency 0x1, configured
4022 */
Paolo Bonzini609e36d2015-04-08 15:30:38 +02004023 msr_info->data = 0xbe702111;
john cooper91c9c3e2011-01-21 00:21:00 -05004024 break;
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05004025 case MSR_AMD64_OSVW_ID_LENGTH:
Radim Krčmářd6321d42017-08-05 00:12:49 +02004026 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05004027 return 1;
Paolo Bonzini609e36d2015-04-08 15:30:38 +02004028 msr_info->data = vcpu->arch.osvw.length;
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05004029 break;
4030 case MSR_AMD64_OSVW_STATUS:
Radim Krčmářd6321d42017-08-05 00:12:49 +02004031 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05004032 return 1;
Paolo Bonzini609e36d2015-04-08 15:30:38 +02004033 msr_info->data = vcpu->arch.osvw.status;
Boris Ostrovsky2b036c62012-01-09 14:00:35 -05004034 break;
Kyle Hueydb2336a2017-03-20 01:16:28 -07004035 case MSR_PLATFORM_INFO:
Drew Schmitt6fbbde92018-08-20 10:32:15 -07004036 if (!msr_info->host_initiated &&
4037 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4038 return 1;
Kyle Hueydb2336a2017-03-20 01:16:28 -07004039 msr_info->data = vcpu->arch.msr_platform_info;
4040 break;
4041 case MSR_MISC_FEATURES_ENABLES:
4042 msr_info->data = vcpu->arch.msr_misc_features_enables;
4043 break;
Borislav Petkov191c8132019-04-18 18:32:50 +02004044 case MSR_K7_HWCR:
4045 msr_info->data = vcpu->arch.msr_hwcr;
4046 break;
Jing Liu820a6ee2022-01-05 04:35:21 -08004047#ifdef CONFIG_X86_64
4048 case MSR_IA32_XFD:
4049 if (!msr_info->host_initiated &&
4050 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4051 return 1;
4052
4053 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4054 break;
Jing Liu548e8362022-01-05 04:35:24 -08004055 case MSR_IA32_XFD_ERR:
4056 if (!msr_info->host_initiated &&
4057 !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
4058 return 1;
4059
4060 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4061 break;
Jing Liu820a6ee2022-01-05 04:35:21 -08004062#endif
Carsten Otte15c4a642007-10-30 18:44:17 +01004063 default:
Wei Huangc6702c92015-06-19 13:44:45 +02004064 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
Wei Wangcbd71752020-05-29 15:43:44 +08004065 return kvm_pmu_get_msr(vcpu, msr_info);
Peter Xu6abe9c12020-06-22 18:04:41 -04004066 return KVM_MSR_RET_INVALID;
Carsten Otte15c4a642007-10-30 18:44:17 +01004067 }
Carsten Otte15c4a642007-10-30 18:44:17 +01004068 return 0;
4069}
4070EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4071
Carsten Otte313a3dc2007-10-11 19:16:52 +02004072/*
4073 * Read or write a bunch of msrs. All parameters are kernel addresses.
4074 *
4075 * @return number of msrs set successfully.
4076 */
4077static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4078 struct kvm_msr_entry *entries,
4079 int (*do_msr)(struct kvm_vcpu *vcpu,
4080 unsigned index, u64 *data))
4081{
Tom Lendacky801e4592018-02-21 13:39:51 -06004082 int i;
Carsten Otte313a3dc2007-10-11 19:16:52 +02004083
Carsten Otte313a3dc2007-10-11 19:16:52 +02004084 for (i = 0; i < msrs->nmsrs; ++i)
4085 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4086 break;
4087
Carsten Otte313a3dc2007-10-11 19:16:52 +02004088 return i;
4089}
4090
4091/*
4092 * Read or write a bunch of msrs. Parameters are user addresses.
4093 *
4094 * @return number of msrs set successfully.
4095 */
4096static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4097 int (*do_msr)(struct kvm_vcpu *vcpu,
4098 unsigned index, u64 *data),
4099 int writeback)
4100{
4101 struct kvm_msrs msrs;
4102 struct kvm_msr_entry *entries;
4103 int r, n;
4104 unsigned size;
4105
4106 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00004107 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
Carsten Otte313a3dc2007-10-11 19:16:52 +02004108 goto out;
4109
4110 r = -E2BIG;
4111 if (msrs.nmsrs >= MAX_IO_MSRS)
4112 goto out;
4113
Carsten Otte313a3dc2007-10-11 19:16:52 +02004114 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
Sasha Levinff5c2c02011-12-04 19:36:29 +02004115 entries = memdup_user(user_msrs->entries, size);
4116 if (IS_ERR(entries)) {
4117 r = PTR_ERR(entries);
Carsten Otte313a3dc2007-10-11 19:16:52 +02004118 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02004119 }
Carsten Otte313a3dc2007-10-11 19:16:52 +02004120
4121 r = n = __msr_io(vcpu, &msrs, entries, do_msr);
4122 if (r < 0)
4123 goto out_free;
4124
4125 r = -EFAULT;
4126 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4127 goto out_free;
4128
4129 r = n;
4130
4131out_free:
Avi Kivity7a73c022010-07-22 23:24:52 +03004132 kfree(entries);
Carsten Otte313a3dc2007-10-11 19:16:52 +02004133out:
4134 return r;
4135}
4136
Wanpeng Li4d5422c2018-03-12 04:53:02 -07004137static inline bool kvm_can_mwait_in_guest(void)
4138{
4139 return boot_cpu_has(X86_FEATURE_MWAIT) &&
KarimAllah Ahmed8e9b29b2018-04-11 11:16:03 +02004140 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4141 boot_cpu_has(X86_FEATURE_ARAT);
Wanpeng Li4d5422c2018-03-12 04:53:02 -07004142}
4143
Vitaly Kuznetsovc21d54f2020-09-29 17:09:43 +02004144static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4145 struct kvm_cpuid2 __user *cpuid_arg)
4146{
4147 struct kvm_cpuid2 cpuid;
4148 int r;
4149
4150 r = -EFAULT;
4151 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4152 return r;
4153
4154 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4155 if (r)
4156 return r;
4157
4158 r = -EFAULT;
4159 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4160 return r;
4161
4162 return 0;
4163}
4164
Alexander Graf784aa3d2014-07-14 18:27:35 +02004165int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004166{
Wanpeng Li4d5422c2018-03-12 04:53:02 -07004167 int r = 0;
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004168
4169 switch (ext) {
4170 case KVM_CAP_IRQCHIP:
4171 case KVM_CAP_HLT:
4172 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004173 case KVM_CAP_SET_TSS_ADDR:
Dan Kenigsberg07716712007-11-21 17:10:04 +02004174 case KVM_CAP_EXT_CPUID:
Borislav Petkov9c15bb12013-09-22 16:44:50 +02004175 case KVM_CAP_EXT_EMUL_CPUID:
Gerd Hoffmannc8076602009-02-04 17:52:04 +01004176 case KVM_CAP_CLOCKSOURCE:
Sheng Yang78376992008-01-28 05:10:22 +08004177 case KVM_CAP_PIT:
Marcelo Tosattia28e4f52008-02-22 12:21:36 -05004178 case KVM_CAP_NOP_IO_DELAY:
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03004179 case KVM_CAP_MP_STATE:
Avi Kivityed848622008-07-29 11:30:57 +03004180 case KVM_CAP_SYNC_MMU:
Lai Jiangshana355c852010-12-14 17:57:47 +08004181 case KVM_CAP_USER_NMI:
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02004182 case KVM_CAP_REINJECT_CONTROL:
Gleb Natapov49256632009-02-04 17:28:14 +02004183 case KVM_CAP_IRQ_INJECT_STATUS:
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04004184 case KVM_CAP_IOEVENTFD:
Michael S. Tsirkinf848a5a2014-03-31 21:50:38 +03004185 case KVM_CAP_IOEVENTFD_NO_LENGTH:
Jan Kiszkac5ff41c2009-05-14 22:42:53 +02004186 case KVM_CAP_PIT2:
Beth Kone9f42752009-07-07 11:50:38 -04004187 case KVM_CAP_PIT_STATE2:
Sheng Yangb927a3c2009-07-21 10:42:48 +08004188 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004189 case KVM_CAP_VCPU_EVENTS:
Gleb Natapov55cd8e52010-01-17 15:51:22 +02004190 case KVM_CAP_HYPERV:
Gleb Natapov10388a02010-01-17 15:51:23 +02004191 case KVM_CAP_HYPERV_VAPIC:
Gleb Natapovc25bc162010-01-17 15:51:24 +02004192 case KVM_CAP_HYPERV_SPIN:
Andrey Smetanin5c9194122015-11-10 15:36:34 +03004193 case KVM_CAP_HYPERV_SYNIC:
Roman Kaganefc479e2017-06-22 16:51:01 +03004194 case KVM_CAP_HYPERV_SYNIC2:
Roman Kagand3457c82017-07-14 17:13:20 +03004195 case KVM_CAP_HYPERV_VP_INDEX:
Roman Kaganfaeb7832018-02-01 16:48:32 +03004196 case KVM_CAP_HYPERV_EVENTFD:
Vitaly Kuznetsovc1aea912018-05-16 17:21:31 +02004197 case KVM_CAP_HYPERV_TLBFLUSH:
Vitaly Kuznetsov214ff832018-09-26 19:02:59 +02004198 case KVM_CAP_HYPERV_SEND_IPI:
Vitaly Kuznetsov2bc39972018-12-10 18:21:56 +01004199 case KVM_CAP_HYPERV_CPUID:
Vitaly Kuznetsov644f7062021-05-21 11:51:36 +02004200 case KVM_CAP_HYPERV_ENFORCE_CPUID:
Vitaly Kuznetsovc21d54f2020-09-29 17:09:43 +02004201 case KVM_CAP_SYS_HYPERV_CPUID:
Zhai, Edwinab9f4ec2010-01-29 14:38:44 +08004202 case KVM_CAP_PCI_SEGMENT:
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004203 case KVM_CAP_DEBUGREGS:
Jan Kiszkad2be1652010-02-23 17:47:57 +01004204 case KVM_CAP_X86_ROBUST_SINGLESTEP:
Sheng Yang2d5b5a62010-06-13 17:29:39 +08004205 case KVM_CAP_XSAVE:
Gleb Natapov344d9582010-10-14 11:22:50 +02004206 case KVM_CAP_ASYNC_PF:
Vitaly Kuznetsov72de5fa4c2020-05-25 16:41:22 +02004207 case KVM_CAP_ASYNC_PF_INT:
Joerg Roedel92a1f122011-03-25 09:44:51 +01004208 case KVM_CAP_GET_TSC_KHZ:
Eric B Munson1c0b28c2012-03-10 14:37:27 -05004209 case KVM_CAP_KVMCLOCK_CTRL:
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08004210 case KVM_CAP_READONLY_MEM:
Paolo Bonzini5f66b622014-01-29 18:10:45 +01004211 case KVM_CAP_HYPERV_TIME:
Gabriel L. Somlo100943c2014-02-27 23:06:17 -05004212 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
Radim Krčmářdefcf512015-01-08 15:59:30 +01004213 case KVM_CAP_TSC_DEADLINE_TIMER:
Nadav Amit90de4a12015-04-13 01:53:41 +03004214 case KVM_CAP_DISABLE_QUIRKS:
Paolo Bonzinid71ba782015-07-29 11:56:48 +02004215 case KVM_CAP_SET_BOOT_CPU_ID:
Steve Rutherford49df6392015-07-29 23:21:40 -07004216 case KVM_CAP_SPLIT_IRQCHIP:
Paolo Bonzini460df4c2017-02-08 11:50:15 +01004217 case KVM_CAP_IMMEDIATE_EXIT:
Eric Hankland66bb8a02019-07-10 18:25:15 -07004218 case KVM_CAP_PMU_EVENT_FILTER:
Tom Lendacky801e4592018-02-21 13:39:51 -06004219 case KVM_CAP_GET_MSR_FEATURES:
Drew Schmitt6fbbde92018-08-20 10:32:15 -07004220 case KVM_CAP_MSR_PLATFORM_INFO:
Jim Mattsonc4f55192018-10-16 14:29:24 -07004221 case KVM_CAP_EXCEPTION_PAYLOAD:
Peter Xub9b27822020-05-05 11:47:50 -04004222 case KVM_CAP_SET_GUEST_DEBUG:
Jim Mattson1aa561b2020-06-03 16:56:21 -07004223 case KVM_CAP_LAST_CPU:
Alexander Graf1ae09952020-09-25 16:34:16 +02004224 case KVM_CAP_X86_USER_SPACE_MSR:
Alexander Graf1a1552542020-09-25 16:34:21 +02004225 case KVM_CAP_X86_MSR_FILTER:
Oliver Upton66570e92020-08-18 15:24:28 +00004226 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
Sean Christophersonfe7e9482021-04-12 16:21:43 +12004227#ifdef CONFIG_X86_SGX_KVM
4228 case KVM_CAP_SGX_ATTRIBUTE:
4229#endif
Nathan Tempelman54526d12021-04-08 22:32:14 +00004230 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
Paolo Bonzini30d7c5d2021-11-18 04:41:34 -05004231 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
Maxim Levitsky6dba9402021-06-07 12:02:02 +03004232 case KVM_CAP_SREGS2:
Aaron Lewis19238e72021-05-10 07:48:33 -07004233 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
Oliver Upton828ca892021-09-16 18:15:38 +00004234 case KVM_CAP_VCPU_ATTRIBUTES:
Paolo Bonzinidd6e6312022-01-26 07:49:45 -05004235 case KVM_CAP_SYS_ATTRIBUTES:
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004236 r = 1;
4237 break;
Ashish Kalra0dbb1122021-06-08 18:05:43 +00004238 case KVM_CAP_EXIT_HYPERCALL:
4239 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4240 break;
Maxim Levitsky7e582cc2021-04-01 16:54:45 +03004241 case KVM_CAP_SET_GUEST_DEBUG2:
4242 return KVM_GUESTDBG_VALID_MASK;
Paolo Bonzinib59b1532021-02-26 04:54:45 -05004243#ifdef CONFIG_KVM_XEN
Joao Martins23200b72018-06-13 09:55:44 -04004244 case KVM_CAP_XEN_HVM:
4245 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
David Woodhouse8d4e7e82020-12-04 01:02:04 +00004246 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
David Woodhouse14243b32021-12-10 16:36:23 +00004247 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4248 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL;
David Woodhouse30b5c852021-03-01 12:53:09 +00004249 if (sched_info_on())
4250 r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
Joao Martins23200b72018-06-13 09:55:44 -04004251 break;
Paolo Bonzinib59b1532021-02-26 04:54:45 -05004252#endif
Ken Hofsass01643c52018-01-31 16:03:36 -08004253 case KVM_CAP_SYNC_REGS:
4254 r = KVM_SYNC_X86_VALID_FIELDS;
4255 break;
Paolo Bonzinie3fd9a92016-11-09 17:48:15 +01004256 case KVM_CAP_ADJUST_CLOCK:
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00004257 r = KVM_CLOCK_VALID_FLAGS;
Paolo Bonzinie3fd9a92016-11-09 17:48:15 +01004258 break;
Wanpeng Li4d5422c2018-03-12 04:53:02 -07004259 case KVM_CAP_X86_DISABLE_EXITS:
Wanpeng Lib5170062019-05-21 14:06:53 +08004260 r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
4261 KVM_X86_DISABLE_EXITS_CSTATE;
Wanpeng Li4d5422c2018-03-12 04:53:02 -07004262 if(kvm_can_mwait_in_guest())
4263 r |= KVM_X86_DISABLE_EXITS_MWAIT;
Michael S. Tsirkin668fffa2017-04-21 12:27:17 +02004264 break;
Paolo Bonzini6d396b52015-04-01 14:25:33 +02004265 case KVM_CAP_X86_SMM:
4266 /* SMBASE is usually relocated above 1M on modern chipsets,
4267 * and SMM handlers might indeed rely on 4G segment limits,
4268 * so do not report SMM to be available if real mode is
4269 * emulated via vm86 mode. Still, do not go to great lengths
4270 * to avoid userspace's usage of the feature, because it is a
4271 * fringe case that is not enabled except via specific settings
4272 * of the module parameters.
4273 */
Jason Baronb36464772021-01-14 22:27:56 -05004274 r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
Paolo Bonzini6d396b52015-04-01 14:25:33 +02004275 break;
Avi Kivity774ead32007-12-26 13:57:04 +02004276 case KVM_CAP_VAPIC:
Jason Baronb36464772021-01-14 22:27:56 -05004277 r = !static_call(kvm_x86_cpu_has_accelerated_tpr)();
Avi Kivity774ead32007-12-26 13:57:04 +02004278 break;
Avi Kivityf7252302008-02-20 11:53:16 +02004279 case KVM_CAP_NR_VCPUS:
Vitaly Kuznetsov2845e732021-11-16 17:34:43 +01004280 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
Sasha Levin8c3ba332011-07-18 17:17:15 +03004281 break;
4282 case KVM_CAP_MAX_VCPUS:
Avi Kivityf7252302008-02-20 11:53:16 +02004283 r = KVM_MAX_VCPUS;
4284 break;
Thomas Hutha86cb412019-05-23 18:43:08 +02004285 case KVM_CAP_MAX_VCPU_ID:
Juergen Grossa1c42dd2021-09-13 15:57:44 +02004286 r = KVM_MAX_VCPU_IDS;
Thomas Hutha86cb412019-05-23 18:43:08 +02004287 break;
Marcelo Tosattia68a6a72009-10-01 19:28:39 -03004288 case KVM_CAP_PV_MMU: /* obsolete */
4289 r = 0;
Marcelo Tosatti2f333bc2008-02-22 12:21:37 -05004290 break;
Huang Ying890ca9a2009-05-11 16:48:15 +08004291 case KVM_CAP_MCE:
4292 r = KVM_MAX_MCE_BANKS;
4293 break;
Sheng Yang2d5b5a62010-06-13 17:29:39 +08004294 case KVM_CAP_XCRS:
Borislav Petkovd366bf72016-04-04 22:25:02 +02004295 r = boot_cpu_has(X86_FEATURE_XSAVE);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08004296 break;
Joerg Roedel92a1f122011-03-25 09:44:51 +01004297 case KVM_CAP_TSC_CONTROL:
4298 r = kvm_has_tsc_control;
4299 break;
Radim Krčmář371313132016-07-12 22:09:27 +02004300 case KVM_CAP_X2APIC_API:
4301 r = KVM_X2APIC_API_VALID_FLAGS;
4302 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02004303 case KVM_CAP_NESTED_STATE:
Paolo Bonzini33b22172020-04-17 10:24:18 -04004304 r = kvm_x86_ops.nested_ops->get_state ?
4305 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02004306 break;
Tianyu Lan344c6c82019-08-22 22:30:20 +08004307 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
Sean Christophersonafaf0b22020-03-21 13:26:00 -07004308 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
Vitaly Kuznetsov5a0165f2019-08-28 09:59:05 +02004309 break;
4310 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
Paolo Bonzini33b22172020-04-17 10:24:18 -04004311 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
Tianyu Lan344c6c82019-08-22 22:30:20 +08004312 break;
Mohammed Gamal3edd6832020-07-10 17:48:11 +02004313 case KVM_CAP_SMALLER_MAXPHYADDR:
4314 r = (int) allow_smaller_maxphyaddr;
4315 break;
Andrew Jones004a0122020-08-04 19:06:04 +02004316 case KVM_CAP_STEAL_TIME:
4317 r = sched_info_on();
4318 break;
Chenyi Qiangfe6b6bc2020-11-06 17:03:14 +08004319 case KVM_CAP_X86_BUS_LOCK_EXIT:
4320 if (kvm_has_bus_lock_exit)
4321 r = KVM_BUS_LOCK_DETECTION_OFF |
4322 KVM_BUS_LOCK_DETECTION_EXIT;
4323 else
4324 r = 0;
4325 break;
Guang Zengbe50b202022-01-05 04:35:29 -08004326 case KVM_CAP_XSAVE2: {
4327 u64 guest_perm = xstate_get_guest_group_perm();
4328
4329 r = xstate_required_size(supported_xcr0 & guest_perm, false);
4330 if (r < sizeof(struct kvm_xsave))
4331 r = sizeof(struct kvm_xsave);
4332 break;
4333 }
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004334 default:
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004335 break;
4336 }
4337 return r;
Sean Christopherson56f289a2022-01-27 07:31:53 -08004338}
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004339
Sean Christopherson56f289a2022-01-27 07:31:53 -08004340static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
4341{
4342 void __user *uaddr = (void __user*)(unsigned long)attr->addr;
4343
4344 if ((u64)(unsigned long)uaddr != attr->addr)
Sean Christopherson6e37ec882022-02-02 00:51:57 +00004345 return ERR_PTR_USR(-EFAULT);
Sean Christopherson56f289a2022-01-27 07:31:53 -08004346 return uaddr;
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004347}
4348
Paolo Bonzinidd6e6312022-01-26 07:49:45 -05004349static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4350{
4351 u64 __user *uaddr = kvm_get_attr_addr(attr);
4352
4353 if (attr->group)
4354 return -ENXIO;
4355
4356 if (IS_ERR(uaddr))
4357 return PTR_ERR(uaddr);
4358
4359 switch (attr->attr) {
4360 case KVM_X86_XCOMP_GUEST_SUPP:
4361 if (put_user(supported_xcr0, uaddr))
4362 return -EFAULT;
4363 return 0;
4364 default:
4365 return -ENXIO;
4366 break;
4367 }
4368}
4369
4370static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4371{
4372 if (attr->group)
4373 return -ENXIO;
4374
4375 switch (attr->attr) {
4376 case KVM_X86_XCOMP_GUEST_SUPP:
4377 return 0;
4378 default:
4379 return -ENXIO;
4380 }
4381}
4382
Carsten Otte043405e2007-10-10 17:16:19 +02004383long kvm_arch_dev_ioctl(struct file *filp,
4384 unsigned int ioctl, unsigned long arg)
4385{
4386 void __user *argp = (void __user *)arg;
4387 long r;
4388
4389 switch (ioctl) {
4390 case KVM_GET_MSR_INDEX_LIST: {
4391 struct kvm_msr_list __user *user_msr_list = argp;
4392 struct kvm_msr_list msr_list;
4393 unsigned n;
4394
4395 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00004396 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
Carsten Otte043405e2007-10-10 17:16:19 +02004397 goto out;
4398 n = msr_list.nmsrs;
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02004399 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
Jordan Borgner0e96f312018-10-28 12:58:28 +00004400 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
Carsten Otte043405e2007-10-10 17:16:19 +02004401 goto out;
4402 r = -E2BIG;
Jan Kiszkae125e7b2009-07-02 21:45:47 +02004403 if (n < msr_list.nmsrs)
Carsten Otte043405e2007-10-10 17:16:19 +02004404 goto out;
4405 r = -EFAULT;
4406 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4407 num_msrs_to_save * sizeof(u32)))
4408 goto out;
Jan Kiszkae125e7b2009-07-02 21:45:47 +02004409 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
Carsten Otte043405e2007-10-10 17:16:19 +02004410 &emulated_msrs,
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02004411 num_emulated_msrs * sizeof(u32)))
Carsten Otte043405e2007-10-10 17:16:19 +02004412 goto out;
4413 r = 0;
4414 break;
4415 }
Borislav Petkov9c15bb12013-09-22 16:44:50 +02004416 case KVM_GET_SUPPORTED_CPUID:
4417 case KVM_GET_EMULATED_CPUID: {
Avi Kivity674eea02008-02-11 18:37:23 +02004418 struct kvm_cpuid2 __user *cpuid_arg = argp;
4419 struct kvm_cpuid2 cpuid;
4420
4421 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00004422 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Avi Kivity674eea02008-02-11 18:37:23 +02004423 goto out;
Borislav Petkov9c15bb12013-09-22 16:44:50 +02004424
4425 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4426 ioctl);
Avi Kivity674eea02008-02-11 18:37:23 +02004427 if (r)
4428 goto out;
4429
4430 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00004431 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
Avi Kivity674eea02008-02-11 18:37:23 +02004432 goto out;
4433 r = 0;
4434 break;
4435 }
Xiaoyao Licf6c26e2020-02-29 10:52:12 +08004436 case KVM_X86_GET_MCE_CAP_SUPPORTED:
Huang Ying890ca9a2009-05-11 16:48:15 +08004437 r = -EFAULT;
Ashok Rajc45dcc72016-06-22 14:59:56 +08004438 if (copy_to_user(argp, &kvm_mce_cap_supported,
4439 sizeof(kvm_mce_cap_supported)))
Huang Ying890ca9a2009-05-11 16:48:15 +08004440 goto out;
4441 r = 0;
4442 break;
Tom Lendacky801e4592018-02-21 13:39:51 -06004443 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4444 struct kvm_msr_list __user *user_msr_list = argp;
4445 struct kvm_msr_list msr_list;
4446 unsigned int n;
4447
4448 r = -EFAULT;
4449 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4450 goto out;
4451 n = msr_list.nmsrs;
4452 msr_list.nmsrs = num_msr_based_features;
4453 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4454 goto out;
4455 r = -E2BIG;
4456 if (n < msr_list.nmsrs)
4457 goto out;
4458 r = -EFAULT;
4459 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4460 num_msr_based_features * sizeof(u32)))
4461 goto out;
4462 r = 0;
4463 break;
4464 }
4465 case KVM_GET_MSRS:
4466 r = msr_io(NULL, argp, do_get_msr_feature, 1);
4467 break;
Vitaly Kuznetsovc21d54f2020-09-29 17:09:43 +02004468 case KVM_GET_SUPPORTED_HV_CPUID:
4469 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4470 break;
Paolo Bonzinidd6e6312022-01-26 07:49:45 -05004471 case KVM_GET_DEVICE_ATTR: {
4472 struct kvm_device_attr attr;
4473 r = -EFAULT;
4474 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4475 break;
4476 r = kvm_x86_dev_get_attr(&attr);
4477 break;
4478 }
4479 case KVM_HAS_DEVICE_ATTR: {
4480 struct kvm_device_attr attr;
4481 r = -EFAULT;
4482 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4483 break;
4484 r = kvm_x86_dev_has_attr(&attr);
4485 break;
4486 }
Carsten Otte043405e2007-10-10 17:16:19 +02004487 default:
4488 r = -EINVAL;
Xiaoyao Licf6c26e2020-02-29 10:52:12 +08004489 break;
Carsten Otte043405e2007-10-10 17:16:19 +02004490 }
4491out:
4492 return r;
4493}
4494
Sheng Yangf5f48ee2010-06-30 12:25:15 +08004495static void wbinvd_ipi(void *garbage)
4496{
4497 wbinvd();
4498}
4499
4500static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4501{
Alex Williamsone0f0bbc2013-10-30 11:02:30 -06004502 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
Sheng Yangf5f48ee2010-06-30 12:25:15 +08004503}
4504
Carsten Otte313a3dc2007-10-11 19:16:52 +02004505void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4506{
Sheng Yangf5f48ee2010-06-30 12:25:15 +08004507 /* Address WBINVD may be executed by guest */
4508 if (need_emulate_wbinvd(vcpu)) {
Jason Baronb36464772021-01-14 22:27:56 -05004509 if (static_call(kvm_x86_has_wbinvd_exit)())
Sheng Yangf5f48ee2010-06-30 12:25:15 +08004510 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4511 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
4512 smp_call_function_single(vcpu->cpu,
4513 wbinvd_ipi, NULL, 1);
4514 }
4515
Jason Baronb36464772021-01-14 22:27:56 -05004516 static_call(kvm_x86_vcpu_load)(vcpu, cpu);
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -02004517
Babu Moger37486132020-05-12 18:59:06 -05004518 /* Save host pkru register if supported */
4519 vcpu->arch.host_pkru = read_pkru();
4520
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -02004521 /* Apply any externally detected TSC adjustments (due to suspend) */
4522 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
4523 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
4524 vcpu->arch.tsc_offset_adjustment = 0;
Guo Hui Liu105b21b2014-09-12 13:43:19 +08004525 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -02004526 }
4527
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01004528 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
Zachary Amsden6f526ec2012-02-03 15:43:54 -02004529 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
Andy Lutomirski4ea16362015-06-25 18:44:07 +02004530 rdtsc() - vcpu->arch.last_host_tsc;
Zachary Amsdene48672f2010-08-19 22:07:23 -10004531 if (tsc_delta < 0)
4532 mark_tsc_unstable("KVM discovered backwards TSC");
Yunhong Jiangce7a0582016-06-13 14:20:01 -07004533
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01004534 if (kvm_check_tsc_unstable()) {
Ilias Stamatis9b399df2021-05-26 19:44:10 +01004535 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
Zachary Amsdenb183aa52012-02-03 15:43:53 -02004536 vcpu->arch.last_guest_tsc);
Luiz Capitulinoa545ab62016-09-07 14:47:19 -04004537 kvm_vcpu_write_tsc_offset(vcpu, offset);
Zachary Amsdenc2855452010-09-18 14:38:15 -10004538 vcpu->arch.tsc_catchup = 1;
Zachary Amsdenc2855452010-09-18 14:38:15 -10004539 }
Paolo Bonzinia749e242017-06-29 17:14:50 +02004540
4541 if (kvm_lapic_hv_timer_in_use(vcpu))
4542 kvm_lapic_restart_hv_timer(vcpu);
4543
Marcelo Tosattid98d07c2012-11-27 23:29:04 -02004544 /*
4545 * On a host with synchronized TSC, there is no need to update
4546 * kvmclock on vcpu->cpu migration
4547 */
4548 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03004549 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
Zachary Amsdenc2855452010-09-18 14:38:15 -10004550 if (vcpu->cpu != cpu)
Radim Krčmář1bd20092017-04-26 22:32:20 +02004551 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
Zachary Amsdene48672f2010-08-19 22:07:23 -10004552 vcpu->cpu = cpu;
Zachary Amsden6b7d7e72009-10-09 16:26:08 -10004553 }
Glauber Costac9aaa892011-07-11 15:28:14 -04004554
Glauber Costac9aaa892011-07-11 15:28:14 -04004555 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
Carsten Otte313a3dc2007-10-11 19:16:52 +02004556}
4557
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04004558static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
4559{
David Woodhouse7e2175e2021-11-02 17:36:39 +00004560 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
4561 struct kvm_steal_time __user *st;
4562 struct kvm_memslots *slots;
4563 static const u8 preempted = KVM_VCPU_PREEMPTED;
Boris Ostrovskyb0431382019-12-05 03:45:32 +00004564
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04004565 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
4566 return;
4567
Boris Ostrovskya6bd8112019-12-06 15:36:12 +00004568 if (vcpu->arch.st.preempted)
Boris Ostrovsky8c6de562019-10-30 19:01:31 +00004569 return;
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04004570
David Woodhouse7e2175e2021-11-02 17:36:39 +00004571 /* This happens on process exit */
4572 if (unlikely(current->mm != vcpu->kvm->mm))
Wanpeng Li9c1a0742021-04-23 16:23:20 +08004573 return;
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04004574
David Woodhouse7e2175e2021-11-02 17:36:39 +00004575 slots = kvm_memslots(vcpu->kvm);
Boris Ostrovskyb0431382019-12-05 03:45:32 +00004576
David Woodhouse7e2175e2021-11-02 17:36:39 +00004577 if (unlikely(slots->generation != ghc->generation ||
4578 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
4579 return;
Boris Ostrovskyb0431382019-12-05 03:45:32 +00004580
David Woodhouse7e2175e2021-11-02 17:36:39 +00004581 st = (struct kvm_steal_time __user *)ghc->hva;
4582 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
4583
4584 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
4585 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
4586
4587 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
Pan Xinhui0b9f6c42016-11-02 05:08:35 -04004588}
4589
Carsten Otte313a3dc2007-10-11 19:16:52 +02004590void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
4591{
Wanpeng Li9c1a0742021-04-23 16:23:20 +08004592 int idx;
4593
Tom Lendackyf1c63662020-12-14 10:29:50 -05004594 if (vcpu->preempted && !vcpu->arch.guest_state_protected)
Jason Baronb36464772021-01-14 22:27:56 -05004595 vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
Longpeng(Mike)de63ad42017-08-08 12:05:33 +08004596
Wanpeng Li9c1a0742021-04-23 16:23:20 +08004597 /*
4598 * Take the srcu lock as memslots will be accessed to check the gfn
4599 * cache generation against the memslots generation.
4600 */
4601 idx = srcu_read_lock(&vcpu->kvm->srcu);
David Woodhouse30b5c852021-03-01 12:53:09 +00004602 if (kvm_xen_msr_enabled(vcpu->kvm))
4603 kvm_xen_runstate_set_preempted(vcpu);
4604 else
4605 kvm_steal_time_set_preempted(vcpu);
Wanpeng Li9c1a0742021-04-23 16:23:20 +08004606 srcu_read_unlock(&vcpu->kvm->srcu, idx);
David Woodhouse30b5c852021-03-01 12:53:09 +00004607
Jason Baronb36464772021-01-14 22:27:56 -05004608 static_call(kvm_x86_vcpu_put)(vcpu);
Andy Lutomirski4ea16362015-06-25 18:44:07 +02004609 vcpu->arch.last_host_tsc = rdtsc();
Carsten Otte313a3dc2007-10-11 19:16:52 +02004610}
4611
Carsten Otte313a3dc2007-10-11 19:16:52 +02004612static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
4613 struct kvm_lapic_state *s)
4614{
Paolo Bonzini37c4dbf2021-11-22 19:43:10 -05004615 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
Andrey Smetanind62caab2015-11-10 15:36:33 +03004616
Radim Krčmářa92e2542016-07-12 22:09:22 +02004617 return kvm_apic_get_state(vcpu, s);
Carsten Otte313a3dc2007-10-11 19:16:52 +02004618}
4619
4620static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
4621 struct kvm_lapic_state *s)
4622{
Radim Krčmářa92e2542016-07-12 22:09:22 +02004623 int r;
4624
4625 r = kvm_apic_set_state(vcpu, s);
4626 if (r)
4627 return r;
Gleb Natapovcb142eb2009-08-09 15:17:40 +03004628 update_cr8_intercept(vcpu);
Carsten Otte313a3dc2007-10-11 19:16:52 +02004629
4630 return 0;
4631}
4632
Matt Gingell127a4572015-11-17 17:32:05 +01004633static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
4634{
Paolo Bonzini71cc8492020-11-27 09:18:20 +01004635 /*
4636 * We can accept userspace's request for interrupt injection
4637 * as long as we have a place to store the interrupt number.
4638 * The actual injection will happen when the CPU is able to
4639 * deliver the interrupt.
4640 */
4641 if (kvm_cpu_has_extint(vcpu))
4642 return false;
4643
4644 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
Matt Gingell127a4572015-11-17 17:32:05 +01004645 return (!lapic_in_kernel(vcpu) ||
4646 kvm_apic_accept_pic_intr(vcpu));
4647}
4648
Matt Gingell782d4222015-11-16 15:26:00 -08004649static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
4650{
Paolo Bonzinifa7a5492021-07-14 17:37:49 -04004651 /*
4652 * Do not cause an interrupt window exit if an exception
4653 * is pending or an event needs reinjection; userspace
4654 * might want to inject the interrupt manually using KVM_SET_REGS
4655 * or KVM_SET_SREGS. For that to work, we must be at an
4656 * instruction boundary and with no events half-injected.
4657 */
4658 return (kvm_arch_interrupt_allowed(vcpu) &&
4659 kvm_cpu_accept_dm_intr(vcpu) &&
4660 !kvm_event_needs_reinjection(vcpu) &&
4661 !vcpu->arch.exception.pending);
Matt Gingell782d4222015-11-16 15:26:00 -08004662}
4663
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004664static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
4665 struct kvm_interrupt *irq)
4666{
Chen Gang02cdb502013-02-27 11:33:25 +08004667 if (irq->irq >= KVM_NR_INTERRUPTS)
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004668 return -EINVAL;
Steve Rutherford1c1a9ce2015-07-30 11:27:16 +02004669
4670 if (!irqchip_in_kernel(vcpu->kvm)) {
4671 kvm_queue_interrupt(vcpu, irq->irq, false);
4672 kvm_make_request(KVM_REQ_EVENT, vcpu);
4673 return 0;
4674 }
4675
4676 /*
4677 * With in-kernel LAPIC, we only use this to inject EXTINT, so
4678 * fail for in-kernel 8259.
4679 */
4680 if (pic_in_kernel(vcpu->kvm))
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004681 return -ENXIO;
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004682
Steve Rutherford1c1a9ce2015-07-30 11:27:16 +02004683 if (vcpu->arch.pending_external_vector != -1)
4684 return -EEXIST;
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004685
Steve Rutherford1c1a9ce2015-07-30 11:27:16 +02004686 vcpu->arch.pending_external_vector = irq->irq;
Matt Gingell934bf652015-11-16 15:26:05 -08004687 kvm_make_request(KVM_REQ_EVENT, vcpu);
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08004688 return 0;
4689}
4690
Jan Kiszkac4abb7c2008-09-26 09:30:55 +02004691static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
4692{
Jan Kiszkac4abb7c2008-09-26 09:30:55 +02004693 kvm_inject_nmi(vcpu);
Jan Kiszkac4abb7c2008-09-26 09:30:55 +02004694
4695 return 0;
4696}
4697
Paolo Bonzinif0778252015-04-01 15:06:40 +02004698static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
4699{
Paolo Bonzini64d60672015-05-07 11:36:11 +02004700 kvm_make_request(KVM_REQ_SMI, vcpu);
4701
Paolo Bonzinif0778252015-04-01 15:06:40 +02004702 return 0;
4703}
4704
Avi Kivityb209749f2007-10-22 16:50:39 +02004705static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
4706 struct kvm_tpr_access_ctl *tac)
4707{
4708 if (tac->flags)
4709 return -EINVAL;
4710 vcpu->arch.tpr_access_reporting = !!tac->enabled;
4711 return 0;
4712}
4713
Huang Ying890ca9a2009-05-11 16:48:15 +08004714static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
4715 u64 mcg_cap)
4716{
4717 int r;
4718 unsigned bank_num = mcg_cap & 0xff, bank;
4719
4720 r = -EINVAL;
Jim Mattsonc4e0e4ab2020-05-11 15:56:16 -07004721 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
Huang Ying890ca9a2009-05-11 16:48:15 +08004722 goto out;
Ashok Rajc45dcc72016-06-22 14:59:56 +08004723 if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
Huang Ying890ca9a2009-05-11 16:48:15 +08004724 goto out;
4725 r = 0;
4726 vcpu->arch.mcg_cap = mcg_cap;
4727 /* Init IA32_MCG_CTL to all 1s */
4728 if (mcg_cap & MCG_CTL_P)
4729 vcpu->arch.mcg_ctl = ~(u64)0;
4730 /* Init IA32_MCi_CTL to all 1s */
4731 for (bank = 0; bank < bank_num; bank++)
4732 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
Ashok Rajc45dcc72016-06-22 14:59:56 +08004733
Jason Baronb36464772021-01-14 22:27:56 -05004734 static_call(kvm_x86_setup_mce)(vcpu);
Huang Ying890ca9a2009-05-11 16:48:15 +08004735out:
4736 return r;
4737}
4738
4739static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
4740 struct kvm_x86_mce *mce)
4741{
4742 u64 mcg_cap = vcpu->arch.mcg_cap;
4743 unsigned bank_num = mcg_cap & 0xff;
4744 u64 *banks = vcpu->arch.mce_banks;
4745
4746 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
4747 return -EINVAL;
4748 /*
4749 * if IA32_MCG_CTL is not all 1s, the uncorrected error
4750 * reporting is disabled
4751 */
4752 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
4753 vcpu->arch.mcg_ctl != ~(u64)0)
4754 return 0;
4755 banks += 4 * mce->bank;
4756 /*
4757 * if IA32_MCi_CTL is not all 1s, the uncorrected error
4758 * reporting is disabled for the bank
4759 */
4760 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
4761 return 0;
4762 if (mce->status & MCI_STATUS_UC) {
4763 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
Avi Kivityfc78f512009-12-07 12:16:48 +02004764 !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
Avi Kivitya8eeb042010-05-10 12:34:53 +03004765 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
Huang Ying890ca9a2009-05-11 16:48:15 +08004766 return 0;
4767 }
4768 if (banks[1] & MCI_STATUS_VAL)
4769 mce->status |= MCI_STATUS_OVER;
4770 banks[2] = mce->addr;
4771 banks[3] = mce->misc;
4772 vcpu->arch.mcg_status = mce->mcg_status;
4773 banks[1] = mce->status;
4774 kvm_queue_exception(vcpu, MC_VECTOR);
4775 } else if (!(banks[1] & MCI_STATUS_VAL)
4776 || !(banks[1] & MCI_STATUS_UC)) {
4777 if (banks[1] & MCI_STATUS_VAL)
4778 mce->status |= MCI_STATUS_OVER;
4779 banks[2] = mce->addr;
4780 banks[3] = mce->misc;
4781 banks[1] = mce->status;
4782 } else
4783 banks[1] |= MCI_STATUS_OVER;
4784 return 0;
4785}
4786
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004787static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
4788 struct kvm_vcpu_events *events)
4789{
Avi Kivity7460fb4a2011-09-20 13:43:14 +03004790 process_nmi(vcpu);
Jim Mattson59073aa2018-10-16 14:29:20 -07004791
Jay Zhou1f7becf2021-01-18 16:47:20 +08004792 if (kvm_check_request(KVM_REQ_SMI, vcpu))
4793 process_smi(vcpu);
4794
Wanpeng Li664f8e22017-08-24 03:35:09 -07004795 /*
Oliver Uptona06230b2020-02-07 02:36:06 -08004796 * In guest mode, payload delivery should be deferred,
4797 * so that the L1 hypervisor can intercept #PF before
4798 * CR2 is modified (or intercept #DB before DR6 is
4799 * modified under nVMX). Unless the per-VM capability,
4800 * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
4801 * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
4802 * opportunistically defer the exception payload, deliver it if the
4803 * capability hasn't been requested before processing a
4804 * KVM_GET_VCPU_EVENTS.
4805 */
4806 if (!vcpu->kvm->arch.exception_payload_enabled &&
4807 vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
4808 kvm_deliver_exception_payload(vcpu);
4809
4810 /*
Jim Mattson59073aa2018-10-16 14:29:20 -07004811 * The API doesn't provide the instruction length for software
4812 * exceptions, so don't report them. As long as the guest RIP
4813 * isn't advanced, we should expect to encounter the exception
4814 * again.
Wanpeng Li664f8e22017-08-24 03:35:09 -07004815 */
Jim Mattson59073aa2018-10-16 14:29:20 -07004816 if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
4817 events->exception.injected = 0;
4818 events->exception.pending = 0;
4819 } else {
4820 events->exception.injected = vcpu->arch.exception.injected;
4821 events->exception.pending = vcpu->arch.exception.pending;
4822 /*
4823 * For ABI compatibility, deliberately conflate
4824 * pending and injected exceptions when
4825 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4826 */
4827 if (!vcpu->kvm->arch.exception_payload_enabled)
4828 events->exception.injected |=
4829 vcpu->arch.exception.pending;
4830 }
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004831 events->exception.nr = vcpu->arch.exception.nr;
4832 events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4833 events->exception.error_code = vcpu->arch.exception.error_code;
Jim Mattson59073aa2018-10-16 14:29:20 -07004834 events->exception_has_payload = vcpu->arch.exception.has_payload;
4835 events->exception_payload = vcpu->arch.exception.payload;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004836
Jan Kiszka03b82a32010-02-15 10:45:41 +01004837 events->interrupt.injected =
Liran Alon04140b42018-03-23 03:01:31 +03004838 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004839 events->interrupt.nr = vcpu->arch.interrupt.nr;
Jan Kiszka03b82a32010-02-15 10:45:41 +01004840 events->interrupt.soft = 0;
Jason Baronb36464772021-01-14 22:27:56 -05004841 events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004842
4843 events->nmi.injected = vcpu->arch.nmi_injected;
Avi Kivity7460fb4a2011-09-20 13:43:14 +03004844 events->nmi.pending = vcpu->arch.nmi_pending != 0;
Jason Baronb36464772021-01-14 22:27:56 -05004845 events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
Vasiliy Kulikov97e69aa2010-10-30 22:54:47 +04004846 events->nmi.pad = 0;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004847
Jan Kiszka66450a22013-03-13 12:42:34 +01004848 events->sipi_vector = 0; /* never valid when reporting to user space */
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004849
Paolo Bonzinif0778252015-04-01 15:06:40 +02004850 events->smi.smm = is_smm(vcpu);
4851 events->smi.pending = vcpu->arch.smi_pending;
4852 events->smi.smm_inside_nmi =
4853 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4854 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4855
Jan Kiszkadab4b912009-12-06 18:24:15 +01004856 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
Paolo Bonzinif0778252015-04-01 15:06:40 +02004857 | KVM_VCPUEVENT_VALID_SHADOW
4858 | KVM_VCPUEVENT_VALID_SMM);
Jim Mattson59073aa2018-10-16 14:29:20 -07004859 if (vcpu->kvm->arch.exception_payload_enabled)
4860 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4861
Vasiliy Kulikov97e69aa2010-10-30 22:54:47 +04004862 memset(&events->reserved, 0, sizeof(events->reserved));
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004863}
4864
Sean Christophersondc872752021-06-09 11:56:15 -07004865static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm);
Xiao Guangrong6ef4e072016-12-24 10:00:42 +01004866
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004867static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4868 struct kvm_vcpu_events *events)
4869{
Jan Kiszkadab4b912009-12-06 18:24:15 +01004870 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
Jan Kiszka48005f62010-02-19 19:38:07 +01004871 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
Paolo Bonzinif0778252015-04-01 15:06:40 +02004872 | KVM_VCPUEVENT_VALID_SHADOW
Jim Mattson59073aa2018-10-16 14:29:20 -07004873 | KVM_VCPUEVENT_VALID_SMM
4874 | KVM_VCPUEVENT_VALID_PAYLOAD))
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004875 return -EINVAL;
4876
Jim Mattson59073aa2018-10-16 14:29:20 -07004877 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4878 if (!vcpu->kvm->arch.exception_payload_enabled)
4879 return -EINVAL;
4880 if (events->exception.pending)
4881 events->exception.injected = 0;
4882 else
4883 events->exception_has_payload = 0;
4884 } else {
4885 events->exception.pending = 0;
4886 events->exception_has_payload = 0;
4887 }
4888
4889 if ((events->exception.injected || events->exception.pending) &&
4890 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
Paolo Bonzini78e546c2016-06-01 14:09:20 +02004891 return -EINVAL;
4892
David Hildenbrand28bf2882017-03-23 11:46:03 +01004893 /* INITs are latched while in SMM */
4894 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4895 (events->smi.smm || events->smi.pending) &&
4896 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4897 return -EINVAL;
4898
Avi Kivity7460fb4a2011-09-20 13:43:14 +03004899 process_nmi(vcpu);
Jim Mattson59073aa2018-10-16 14:29:20 -07004900 vcpu->arch.exception.injected = events->exception.injected;
4901 vcpu->arch.exception.pending = events->exception.pending;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004902 vcpu->arch.exception.nr = events->exception.nr;
4903 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4904 vcpu->arch.exception.error_code = events->exception.error_code;
Jim Mattson59073aa2018-10-16 14:29:20 -07004905 vcpu->arch.exception.has_payload = events->exception_has_payload;
4906 vcpu->arch.exception.payload = events->exception_payload;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004907
Liran Alon04140b42018-03-23 03:01:31 +03004908 vcpu->arch.interrupt.injected = events->interrupt.injected;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004909 vcpu->arch.interrupt.nr = events->interrupt.nr;
4910 vcpu->arch.interrupt.soft = events->interrupt.soft;
Jan Kiszka48005f62010-02-19 19:38:07 +01004911 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
Jason Baronb36464772021-01-14 22:27:56 -05004912 static_call(kvm_x86_set_interrupt_shadow)(vcpu,
4913 events->interrupt.shadow);
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004914
4915 vcpu->arch.nmi_injected = events->nmi.injected;
Jan Kiszkadab4b912009-12-06 18:24:15 +01004916 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4917 vcpu->arch.nmi_pending = events->nmi.pending;
Jason Baronb36464772021-01-14 22:27:56 -05004918 static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004919
Jan Kiszka66450a22013-03-13 12:42:34 +01004920 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01004921 lapic_in_kernel(vcpu))
Jan Kiszka66450a22013-03-13 12:42:34 +01004922 vcpu->arch.apic->sipi_vector = events->sipi_vector;
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004923
Paolo Bonzinif0778252015-04-01 15:06:40 +02004924 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
Sean Christophersonf7e57072022-01-25 22:03:58 +00004925 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4926 kvm_x86_ops.nested_ops->leave_nested(vcpu);
Sean Christophersondc872752021-06-09 11:56:15 -07004927 kvm_smm_changed(vcpu, events->smi.smm);
Sean Christophersonf7e57072022-01-25 22:03:58 +00004928 }
Xiao Guangrong6ef4e072016-12-24 10:00:42 +01004929
Paolo Bonzinif0778252015-04-01 15:06:40 +02004930 vcpu->arch.smi_pending = events->smi.pending;
Wanpeng Lif4ef1912017-08-01 16:05:25 -07004931
4932 if (events->smi.smm) {
4933 if (events->smi.smm_inside_nmi)
4934 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
Paolo Bonzinif0778252015-04-01 15:06:40 +02004935 else
Wanpeng Lif4ef1912017-08-01 16:05:25 -07004936 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
Liran Alonff90afa2019-11-11 11:16:39 +02004937 }
4938
4939 if (lapic_in_kernel(vcpu)) {
4940 if (events->smi.latched_init)
4941 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4942 else
4943 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
Paolo Bonzinif0778252015-04-01 15:06:40 +02004944 }
4945 }
4946
Avi Kivity3842d132010-07-27 12:30:24 +03004947 kvm_make_request(KVM_REQ_EVENT, vcpu);
4948
Jan Kiszka3cfc3092009-11-12 01:04:25 +01004949 return 0;
4950}
4951
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004952static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4953 struct kvm_debugregs *dbgregs)
4954{
Jan Kiszka73aaf249e2014-01-04 18:47:16 +01004955 unsigned long val;
4956
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004957 memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
Nadav Amit16f8a6f2014-10-03 01:10:05 +03004958 kvm_get_dr(vcpu, 6, &val);
Jan Kiszka73aaf249e2014-01-04 18:47:16 +01004959 dbgregs->dr6 = val;
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004960 dbgregs->dr7 = vcpu->arch.dr7;
4961 dbgregs->flags = 0;
Vasiliy Kulikov97e69aa2010-10-30 22:54:47 +04004962 memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004963}
4964
4965static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4966 struct kvm_debugregs *dbgregs)
4967{
4968 if (dbgregs->flags)
4969 return -EINVAL;
4970
Paolo Bonzinifd238002020-11-13 08:31:09 -05004971 if (!kvm_dr6_valid(dbgregs->dr6))
Paolo Bonzinid14bdb52016-06-01 14:09:23 +02004972 return -EINVAL;
Paolo Bonzinifd238002020-11-13 08:31:09 -05004973 if (!kvm_dr7_valid(dbgregs->dr7))
Paolo Bonzinid14bdb52016-06-01 14:09:23 +02004974 return -EINVAL;
4975
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004976 memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
Nadav Amitae561ed2015-04-02 03:10:37 +03004977 kvm_update_dr0123(vcpu);
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004978 vcpu->arch.dr6 = dbgregs->dr6;
4979 vcpu->arch.dr7 = dbgregs->dr7;
Jan Kiszka9926c9f2014-01-04 18:47:15 +01004980 kvm_update_dr7(vcpu);
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004981
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01004982 return 0;
4983}
4984
Sheng Yang2d5b5a62010-06-13 17:29:39 +08004985static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4986 struct kvm_xsave *guest_xsave)
4987{
Thomas Gleixnerd69c1382021-10-22 20:55:53 +02004988 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
Tom Lendackyed02b212020-12-10 11:10:01 -06004989 return;
4990
Thomas Gleixnerd69c1382021-10-22 20:55:53 +02004991 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
4992 guest_xsave->region,
4993 sizeof(guest_xsave->region),
4994 vcpu->arch.pkru);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08004995}
4996
Guang Zengbe50b202022-01-05 04:35:29 -08004997static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
4998 u8 *state, unsigned int size)
4999{
5000 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5001 return;
5002
5003 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu,
5004 state, size, vcpu->arch.pkru);
5005}
5006
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005007static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5008 struct kvm_xsave *guest_xsave)
5009{
Thomas Gleixnerd69c1382021-10-22 20:55:53 +02005010 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
Tom Lendackyed02b212020-12-10 11:10:01 -06005011 return 0;
5012
Thomas Gleixnerd69c1382021-10-22 20:55:53 +02005013 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5014 guest_xsave->region,
5015 supported_xcr0, &vcpu->arch.pkru);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005016}
5017
5018static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5019 struct kvm_xcrs *guest_xcrs)
5020{
Borislav Petkovd366bf72016-04-04 22:25:02 +02005021 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005022 guest_xcrs->nr_xcrs = 0;
5023 return;
5024 }
5025
5026 guest_xcrs->nr_xcrs = 1;
5027 guest_xcrs->flags = 0;
5028 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5029 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5030}
5031
5032static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5033 struct kvm_xcrs *guest_xcrs)
5034{
5035 int i, r = 0;
5036
Borislav Petkovd366bf72016-04-04 22:25:02 +02005037 if (!boot_cpu_has(X86_FEATURE_XSAVE))
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005038 return -EINVAL;
5039
5040 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5041 return -EINVAL;
5042
5043 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5044 /* Only support XCR0 currently */
Paolo Bonzinic67a04c2013-10-17 16:50:47 +02005045 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005046 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
Paolo Bonzinic67a04c2013-10-17 16:50:47 +02005047 guest_xcrs->xcrs[i].value);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005048 break;
5049 }
5050 if (r)
5051 r = -EINVAL;
5052 return r;
5053}
5054
Eric B Munson1c0b28c2012-03-10 14:37:27 -05005055/*
5056 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5057 * stopped by the hypervisor. This function will be called from the host only.
5058 * EINVAL is returned when the host attempts to set the flag for a guest that
5059 * does not support pv clocks.
5060 */
5061static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5062{
Andy Honig0b794592013-02-20 14:48:10 -08005063 if (!vcpu->arch.pv_time_enabled)
Eric B Munson1c0b28c2012-03-10 14:37:27 -05005064 return -EINVAL;
Marcelo Tosatti51d59c62012-08-03 15:57:49 -03005065 vcpu->arch.pvclock_set_guest_stopped_request = true;
Eric B Munson1c0b28c2012-03-10 14:37:27 -05005066 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5067 return 0;
5068}
5069
Oliver Upton828ca892021-09-16 18:15:38 +00005070static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5071 struct kvm_device_attr *attr)
5072{
5073 int r;
5074
5075 switch (attr->attr) {
5076 case KVM_VCPU_TSC_OFFSET:
5077 r = 0;
5078 break;
5079 default:
5080 r = -ENXIO;
5081 }
5082
5083 return r;
5084}
5085
5086static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5087 struct kvm_device_attr *attr)
5088{
Sean Christopherson56f289a2022-01-27 07:31:53 -08005089 u64 __user *uaddr = kvm_get_attr_addr(attr);
Oliver Upton828ca892021-09-16 18:15:38 +00005090 int r;
5091
Sean Christopherson56f289a2022-01-27 07:31:53 -08005092 if (IS_ERR(uaddr))
5093 return PTR_ERR(uaddr);
Oliver Upton828ca892021-09-16 18:15:38 +00005094
5095 switch (attr->attr) {
5096 case KVM_VCPU_TSC_OFFSET:
5097 r = -EFAULT;
5098 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5099 break;
5100 r = 0;
5101 break;
5102 default:
5103 r = -ENXIO;
5104 }
5105
5106 return r;
5107}
5108
5109static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5110 struct kvm_device_attr *attr)
5111{
Sean Christopherson56f289a2022-01-27 07:31:53 -08005112 u64 __user *uaddr = kvm_get_attr_addr(attr);
Oliver Upton828ca892021-09-16 18:15:38 +00005113 struct kvm *kvm = vcpu->kvm;
5114 int r;
5115
Sean Christopherson56f289a2022-01-27 07:31:53 -08005116 if (IS_ERR(uaddr))
5117 return PTR_ERR(uaddr);
Oliver Upton828ca892021-09-16 18:15:38 +00005118
5119 switch (attr->attr) {
5120 case KVM_VCPU_TSC_OFFSET: {
5121 u64 offset, tsc, ns;
5122 unsigned long flags;
5123 bool matched;
5124
5125 r = -EFAULT;
5126 if (get_user(offset, uaddr))
5127 break;
5128
5129 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5130
5131 matched = (vcpu->arch.virtual_tsc_khz &&
5132 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5133 kvm->arch.last_tsc_offset == offset);
5134
5135 tsc = kvm_scale_tsc(vcpu, rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5136 ns = get_kvmclock_base_ns();
5137
5138 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
5139 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5140
5141 r = 0;
5142 break;
5143 }
5144 default:
5145 r = -ENXIO;
5146 }
5147
5148 return r;
5149}
5150
5151static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5152 unsigned int ioctl,
5153 void __user *argp)
5154{
5155 struct kvm_device_attr attr;
5156 int r;
5157
5158 if (copy_from_user(&attr, argp, sizeof(attr)))
5159 return -EFAULT;
5160
5161 if (attr.group != KVM_VCPU_TSC_CTRL)
5162 return -ENXIO;
5163
5164 switch (ioctl) {
5165 case KVM_HAS_DEVICE_ATTR:
5166 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5167 break;
5168 case KVM_GET_DEVICE_ATTR:
5169 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5170 break;
5171 case KVM_SET_DEVICE_ATTR:
5172 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5173 break;
5174 }
5175
5176 return r;
5177}
5178
Andrey Smetanin5c9194122015-11-10 15:36:34 +03005179static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5180 struct kvm_enable_cap *cap)
5181{
Vitaly Kuznetsov57b119d2018-10-16 18:50:01 +02005182 int r;
5183 uint16_t vmcs_version;
5184 void __user *user_ptr;
5185
Andrey Smetanin5c9194122015-11-10 15:36:34 +03005186 if (cap->flags)
5187 return -EINVAL;
5188
5189 switch (cap->cap) {
Roman Kaganefc479e2017-06-22 16:51:01 +03005190 case KVM_CAP_HYPERV_SYNIC2:
5191 if (cap->args[0])
5192 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05005193 fallthrough;
Gustavo A. R. Silvab2869f22019-01-25 12:23:17 -06005194
Andrey Smetanin5c9194122015-11-10 15:36:34 +03005195 case KVM_CAP_HYPERV_SYNIC:
Wanpeng Li546d87e2017-01-03 18:56:19 -08005196 if (!irqchip_in_kernel(vcpu->kvm))
5197 return -EINVAL;
Roman Kaganefc479e2017-06-22 16:51:01 +03005198 return kvm_hv_activate_synic(vcpu, cap->cap ==
5199 KVM_CAP_HYPERV_SYNIC2);
Vitaly Kuznetsov57b119d2018-10-16 18:50:01 +02005200 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
Paolo Bonzini33b22172020-04-17 10:24:18 -04005201 if (!kvm_x86_ops.nested_ops->enable_evmcs)
Sean Christopherson51589172018-12-03 13:53:10 -08005202 return -ENOTTY;
Paolo Bonzini33b22172020-04-17 10:24:18 -04005203 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
Vitaly Kuznetsov57b119d2018-10-16 18:50:01 +02005204 if (!r) {
5205 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5206 if (copy_to_user(user_ptr, &vmcs_version,
5207 sizeof(vmcs_version)))
5208 r = -EFAULT;
5209 }
5210 return r;
Tianyu Lan344c6c82019-08-22 22:30:20 +08005211 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
Sean Christophersonafaf0b22020-03-21 13:26:00 -07005212 if (!kvm_x86_ops.enable_direct_tlbflush)
Tianyu Lan344c6c82019-08-22 22:30:20 +08005213 return -ENOTTY;
5214
Jason Baronb36464772021-01-14 22:27:56 -05005215 return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
Vitaly Kuznetsov57b119d2018-10-16 18:50:01 +02005216
Vitaly Kuznetsov644f7062021-05-21 11:51:36 +02005217 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5218 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5219
Oliver Upton66570e92020-08-18 15:24:28 +00005220 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5221 vcpu->arch.pv_cpuid.enforce = cap->args[0];
Oliver Upton01b4f512020-10-27 16:10:42 -07005222 if (vcpu->arch.pv_cpuid.enforce)
5223 kvm_update_pv_runtime(vcpu);
Oliver Upton66570e92020-08-18 15:24:28 +00005224
5225 return 0;
Andrey Smetanin5c9194122015-11-10 15:36:34 +03005226 default:
5227 return -EINVAL;
5228 }
5229}
5230
Carsten Otte313a3dc2007-10-11 19:16:52 +02005231long kvm_arch_vcpu_ioctl(struct file *filp,
5232 unsigned int ioctl, unsigned long arg)
5233{
5234 struct kvm_vcpu *vcpu = filp->private_data;
5235 void __user *argp = (void __user *)arg;
5236 int r;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005237 union {
Maxim Levitsky6dba9402021-06-07 12:02:02 +03005238 struct kvm_sregs2 *sregs2;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005239 struct kvm_lapic_state *lapic;
5240 struct kvm_xsave *xsave;
5241 struct kvm_xcrs *xcrs;
5242 void *buffer;
5243 } u;
Carsten Otte313a3dc2007-10-11 19:16:52 +02005244
Christoffer Dall9b0624712017-12-04 21:35:36 +01005245 vcpu_load(vcpu);
5246
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005247 u.buffer = NULL;
Carsten Otte313a3dc2007-10-11 19:16:52 +02005248 switch (ioctl) {
5249 case KVM_GET_LAPIC: {
Marcelo Tosatti2204ae32009-10-29 13:44:16 -02005250 r = -EINVAL;
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01005251 if (!lapic_in_kernel(vcpu))
Marcelo Tosatti2204ae32009-10-29 13:44:16 -02005252 goto out;
Ben Gardon254272c2019-02-11 11:02:50 -08005253 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
5254 GFP_KERNEL_ACCOUNT);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005255
Dave Hansenb772ff32008-08-11 10:01:47 -07005256 r = -ENOMEM;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005257 if (!u.lapic)
Dave Hansenb772ff32008-08-11 10:01:47 -07005258 goto out;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005259 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005260 if (r)
5261 goto out;
5262 r = -EFAULT;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005263 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
Carsten Otte313a3dc2007-10-11 19:16:52 +02005264 goto out;
5265 r = 0;
5266 break;
5267 }
5268 case KVM_SET_LAPIC: {
Marcelo Tosatti2204ae32009-10-29 13:44:16 -02005269 r = -EINVAL;
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01005270 if (!lapic_in_kernel(vcpu))
Marcelo Tosatti2204ae32009-10-29 13:44:16 -02005271 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02005272 u.lapic = memdup_user(argp, sizeof(*u.lapic));
Christoffer Dall9b0624712017-12-04 21:35:36 +01005273 if (IS_ERR(u.lapic)) {
5274 r = PTR_ERR(u.lapic);
5275 goto out_nofree;
5276 }
Sasha Levinff5c2c02011-12-04 19:36:29 +02005277
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005278 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005279 break;
5280 }
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08005281 case KVM_INTERRUPT: {
5282 struct kvm_interrupt irq;
5283
5284 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005285 if (copy_from_user(&irq, argp, sizeof(irq)))
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08005286 goto out;
5287 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
Zhang Xiantaof77bc6a2007-11-21 04:36:41 +08005288 break;
5289 }
Jan Kiszkac4abb7c2008-09-26 09:30:55 +02005290 case KVM_NMI: {
5291 r = kvm_vcpu_ioctl_nmi(vcpu);
Jan Kiszkac4abb7c2008-09-26 09:30:55 +02005292 break;
5293 }
Paolo Bonzinif0778252015-04-01 15:06:40 +02005294 case KVM_SMI: {
5295 r = kvm_vcpu_ioctl_smi(vcpu);
5296 break;
5297 }
Carsten Otte313a3dc2007-10-11 19:16:52 +02005298 case KVM_SET_CPUID: {
5299 struct kvm_cpuid __user *cpuid_arg = argp;
5300 struct kvm_cpuid cpuid;
5301
5302 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005303 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Carsten Otte313a3dc2007-10-11 19:16:52 +02005304 goto out;
5305 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005306 break;
5307 }
Dan Kenigsberg07716712007-11-21 17:10:04 +02005308 case KVM_SET_CPUID2: {
5309 struct kvm_cpuid2 __user *cpuid_arg = argp;
5310 struct kvm_cpuid2 cpuid;
5311
5312 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005313 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Dan Kenigsberg07716712007-11-21 17:10:04 +02005314 goto out;
5315 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
Amit Shah19355472009-01-14 16:56:00 +00005316 cpuid_arg->entries);
Dan Kenigsberg07716712007-11-21 17:10:04 +02005317 break;
5318 }
5319 case KVM_GET_CPUID2: {
5320 struct kvm_cpuid2 __user *cpuid_arg = argp;
5321 struct kvm_cpuid2 cpuid;
5322
5323 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005324 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
Dan Kenigsberg07716712007-11-21 17:10:04 +02005325 goto out;
5326 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
Amit Shah19355472009-01-14 16:56:00 +00005327 cpuid_arg->entries);
Dan Kenigsberg07716712007-11-21 17:10:04 +02005328 if (r)
5329 goto out;
5330 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005331 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
Dan Kenigsberg07716712007-11-21 17:10:04 +02005332 goto out;
5333 r = 0;
5334 break;
5335 }
Tom Lendacky801e4592018-02-21 13:39:51 -06005336 case KVM_GET_MSRS: {
5337 int idx = srcu_read_lock(&vcpu->kvm->srcu);
Paolo Bonzini609e36d2015-04-08 15:30:38 +02005338 r = msr_io(vcpu, argp, do_get_msr, 1);
Tom Lendacky801e4592018-02-21 13:39:51 -06005339 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005340 break;
Tom Lendacky801e4592018-02-21 13:39:51 -06005341 }
5342 case KVM_SET_MSRS: {
5343 int idx = srcu_read_lock(&vcpu->kvm->srcu);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005344 r = msr_io(vcpu, argp, do_set_msr, 0);
Tom Lendacky801e4592018-02-21 13:39:51 -06005345 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005346 break;
Tom Lendacky801e4592018-02-21 13:39:51 -06005347 }
Avi Kivityb209749f2007-10-22 16:50:39 +02005348 case KVM_TPR_ACCESS_REPORTING: {
5349 struct kvm_tpr_access_ctl tac;
5350
5351 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005352 if (copy_from_user(&tac, argp, sizeof(tac)))
Avi Kivityb209749f2007-10-22 16:50:39 +02005353 goto out;
5354 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
5355 if (r)
5356 goto out;
5357 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005358 if (copy_to_user(argp, &tac, sizeof(tac)))
Avi Kivityb209749f2007-10-22 16:50:39 +02005359 goto out;
5360 r = 0;
5361 break;
5362 };
Avi Kivityb93463a2007-10-25 16:52:32 +02005363 case KVM_SET_VAPIC_ADDR: {
5364 struct kvm_vapic_addr va;
Paolo Bonzini7301d6a2016-11-17 15:55:46 +01005365 int idx;
Avi Kivityb93463a2007-10-25 16:52:32 +02005366
5367 r = -EINVAL;
Paolo Bonzini35754c92015-07-29 12:05:37 +02005368 if (!lapic_in_kernel(vcpu))
Avi Kivityb93463a2007-10-25 16:52:32 +02005369 goto out;
5370 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005371 if (copy_from_user(&va, argp, sizeof(va)))
Avi Kivityb93463a2007-10-25 16:52:32 +02005372 goto out;
Paolo Bonzini7301d6a2016-11-17 15:55:46 +01005373 idx = srcu_read_lock(&vcpu->kvm->srcu);
Andy Honigfda4e2e2013-11-20 10:23:22 -08005374 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
Paolo Bonzini7301d6a2016-11-17 15:55:46 +01005375 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Avi Kivityb93463a2007-10-25 16:52:32 +02005376 break;
5377 }
Huang Ying890ca9a2009-05-11 16:48:15 +08005378 case KVM_X86_SETUP_MCE: {
5379 u64 mcg_cap;
5380
5381 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005382 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
Huang Ying890ca9a2009-05-11 16:48:15 +08005383 goto out;
5384 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
5385 break;
5386 }
5387 case KVM_X86_SET_MCE: {
5388 struct kvm_x86_mce mce;
5389
5390 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00005391 if (copy_from_user(&mce, argp, sizeof(mce)))
Huang Ying890ca9a2009-05-11 16:48:15 +08005392 goto out;
5393 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
5394 break;
5395 }
Jan Kiszka3cfc3092009-11-12 01:04:25 +01005396 case KVM_GET_VCPU_EVENTS: {
5397 struct kvm_vcpu_events events;
5398
5399 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
5400
5401 r = -EFAULT;
5402 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
5403 break;
5404 r = 0;
5405 break;
5406 }
5407 case KVM_SET_VCPU_EVENTS: {
5408 struct kvm_vcpu_events events;
5409
5410 r = -EFAULT;
5411 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
5412 break;
5413
5414 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
5415 break;
5416 }
Jan Kiszkaa1efbe72010-02-15 10:45:43 +01005417 case KVM_GET_DEBUGREGS: {
5418 struct kvm_debugregs dbgregs;
5419
5420 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
5421
5422 r = -EFAULT;
5423 if (copy_to_user(argp, &dbgregs,
5424 sizeof(struct kvm_debugregs)))
5425 break;
5426 r = 0;
5427 break;
5428 }
5429 case KVM_SET_DEBUGREGS: {
5430 struct kvm_debugregs dbgregs;
5431
5432 r = -EFAULT;
5433 if (copy_from_user(&dbgregs, argp,
5434 sizeof(struct kvm_debugregs)))
5435 break;
5436
5437 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
5438 break;
5439 }
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005440 case KVM_GET_XSAVE: {
Guang Zengbe50b202022-01-05 04:35:29 -08005441 r = -EINVAL;
5442 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
5443 break;
5444
Ben Gardon254272c2019-02-11 11:02:50 -08005445 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005446 r = -ENOMEM;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005447 if (!u.xsave)
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005448 break;
5449
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005450 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005451
5452 r = -EFAULT;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005453 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005454 break;
5455 r = 0;
5456 break;
5457 }
5458 case KVM_SET_XSAVE: {
Guang Zengbe50b202022-01-05 04:35:29 -08005459 int size = vcpu->arch.guest_fpu.uabi_size;
5460
5461 u.xsave = memdup_user(argp, size);
Christoffer Dall9b0624712017-12-04 21:35:36 +01005462 if (IS_ERR(u.xsave)) {
5463 r = PTR_ERR(u.xsave);
5464 goto out_nofree;
5465 }
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005466
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005467 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005468 break;
5469 }
Guang Zengbe50b202022-01-05 04:35:29 -08005470
5471 case KVM_GET_XSAVE2: {
5472 int size = vcpu->arch.guest_fpu.uabi_size;
5473
5474 u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
5475 r = -ENOMEM;
5476 if (!u.xsave)
5477 break;
5478
5479 kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
5480
5481 r = -EFAULT;
5482 if (copy_to_user(argp, u.xsave, size))
5483 break;
5484
5485 r = 0;
5486 break;
5487 }
5488
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005489 case KVM_GET_XCRS: {
Ben Gardon254272c2019-02-11 11:02:50 -08005490 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005491 r = -ENOMEM;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005492 if (!u.xcrs)
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005493 break;
5494
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005495 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005496
5497 r = -EFAULT;
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005498 if (copy_to_user(argp, u.xcrs,
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005499 sizeof(struct kvm_xcrs)))
5500 break;
5501 r = 0;
5502 break;
5503 }
5504 case KVM_SET_XCRS: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02005505 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
Christoffer Dall9b0624712017-12-04 21:35:36 +01005506 if (IS_ERR(u.xcrs)) {
5507 r = PTR_ERR(u.xcrs);
5508 goto out_nofree;
5509 }
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005510
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005511 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
Sheng Yang2d5b5a62010-06-13 17:29:39 +08005512 break;
5513 }
Joerg Roedel92a1f122011-03-25 09:44:51 +01005514 case KVM_SET_TSC_KHZ: {
5515 u32 user_tsc_khz;
5516
5517 r = -EINVAL;
Joerg Roedel92a1f122011-03-25 09:44:51 +01005518 user_tsc_khz = (u32)arg;
5519
Marcelo Tosatti26769f92020-06-16 08:47:41 -03005520 if (kvm_has_tsc_control &&
5521 user_tsc_khz >= kvm_max_guest_tsc_khz)
Joerg Roedel92a1f122011-03-25 09:44:51 +01005522 goto out;
5523
Zachary Amsdencc578282012-02-03 15:43:50 -02005524 if (user_tsc_khz == 0)
5525 user_tsc_khz = tsc_khz;
5526
Haozhong Zhang381d5852015-10-20 15:39:04 +08005527 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
5528 r = 0;
Joerg Roedel92a1f122011-03-25 09:44:51 +01005529
Joerg Roedel92a1f122011-03-25 09:44:51 +01005530 goto out;
5531 }
5532 case KVM_GET_TSC_KHZ: {
Zachary Amsdencc578282012-02-03 15:43:50 -02005533 r = vcpu->arch.virtual_tsc_khz;
Joerg Roedel92a1f122011-03-25 09:44:51 +01005534 goto out;
5535 }
Eric B Munson1c0b28c2012-03-10 14:37:27 -05005536 case KVM_KVMCLOCK_CTRL: {
5537 r = kvm_set_guest_paused(vcpu);
5538 goto out;
5539 }
Andrey Smetanin5c9194122015-11-10 15:36:34 +03005540 case KVM_ENABLE_CAP: {
5541 struct kvm_enable_cap cap;
5542
5543 r = -EFAULT;
5544 if (copy_from_user(&cap, argp, sizeof(cap)))
5545 goto out;
5546 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
5547 break;
5548 }
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005549 case KVM_GET_NESTED_STATE: {
5550 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5551 u32 user_data_size;
5552
5553 r = -EINVAL;
Paolo Bonzini33b22172020-04-17 10:24:18 -04005554 if (!kvm_x86_ops.nested_ops->get_state)
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005555 break;
5556
5557 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
Liran Alon26b471c2018-09-16 14:28:20 +03005558 r = -EFAULT;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005559 if (get_user(user_data_size, &user_kvm_nested_state->size))
Liran Alon26b471c2018-09-16 14:28:20 +03005560 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005561
Paolo Bonzini33b22172020-04-17 10:24:18 -04005562 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
5563 user_data_size);
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005564 if (r < 0)
Liran Alon26b471c2018-09-16 14:28:20 +03005565 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005566
5567 if (r > user_data_size) {
5568 if (put_user(r, &user_kvm_nested_state->size))
Liran Alon26b471c2018-09-16 14:28:20 +03005569 r = -EFAULT;
5570 else
5571 r = -E2BIG;
5572 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005573 }
Liran Alon26b471c2018-09-16 14:28:20 +03005574
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005575 r = 0;
5576 break;
5577 }
5578 case KVM_SET_NESTED_STATE: {
5579 struct kvm_nested_state __user *user_kvm_nested_state = argp;
5580 struct kvm_nested_state kvm_state;
Sean Christophersonad5996d2019-11-22 08:58:18 -08005581 int idx;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005582
5583 r = -EINVAL;
Paolo Bonzini33b22172020-04-17 10:24:18 -04005584 if (!kvm_x86_ops.nested_ops->set_state)
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005585 break;
5586
Liran Alon26b471c2018-09-16 14:28:20 +03005587 r = -EFAULT;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005588 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
Liran Alon26b471c2018-09-16 14:28:20 +03005589 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005590
Liran Alon26b471c2018-09-16 14:28:20 +03005591 r = -EINVAL;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005592 if (kvm_state.size < sizeof(kvm_state))
Liran Alon26b471c2018-09-16 14:28:20 +03005593 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005594
5595 if (kvm_state.flags &
Vitaly Kuznetsov8cab6502018-10-16 18:50:09 +02005596 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
Paolo Bonzinicc440cd2020-05-13 13:36:32 -04005597 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
5598 | KVM_STATE_NESTED_GIF_SET))
Liran Alon26b471c2018-09-16 14:28:20 +03005599 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005600
5601 /* nested_run_pending implies guest_mode. */
Vitaly Kuznetsov8cab6502018-10-16 18:50:09 +02005602 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
5603 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
Liran Alon26b471c2018-09-16 14:28:20 +03005604 break;
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005605
Sean Christophersonad5996d2019-11-22 08:58:18 -08005606 idx = srcu_read_lock(&vcpu->kvm->srcu);
Paolo Bonzini33b22172020-04-17 10:24:18 -04005607 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
Sean Christophersonad5996d2019-11-22 08:58:18 -08005608 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Jim Mattson8fcc4b52018-07-10 11:27:20 +02005609 break;
5610 }
Vitaly Kuznetsovc21d54f2020-09-29 17:09:43 +02005611 case KVM_GET_SUPPORTED_HV_CPUID:
5612 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
Vitaly Kuznetsov2bc39972018-12-10 18:21:56 +01005613 break;
Paolo Bonzinib59b1532021-02-26 04:54:45 -05005614#ifdef CONFIG_KVM_XEN
David Woodhouse3e324612021-02-02 16:53:25 +00005615 case KVM_XEN_VCPU_GET_ATTR: {
5616 struct kvm_xen_vcpu_attr xva;
5617
5618 r = -EFAULT;
5619 if (copy_from_user(&xva, argp, sizeof(xva)))
5620 goto out;
5621 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
5622 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
5623 r = -EFAULT;
5624 break;
5625 }
5626 case KVM_XEN_VCPU_SET_ATTR: {
5627 struct kvm_xen_vcpu_attr xva;
5628
5629 r = -EFAULT;
5630 if (copy_from_user(&xva, argp, sizeof(xva)))
5631 goto out;
5632 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
5633 break;
5634 }
Paolo Bonzinib59b1532021-02-26 04:54:45 -05005635#endif
Maxim Levitsky6dba9402021-06-07 12:02:02 +03005636 case KVM_GET_SREGS2: {
5637 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
5638 r = -ENOMEM;
5639 if (!u.sregs2)
5640 goto out;
5641 __get_sregs2(vcpu, u.sregs2);
5642 r = -EFAULT;
5643 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
5644 goto out;
5645 r = 0;
5646 break;
5647 }
5648 case KVM_SET_SREGS2: {
5649 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
5650 if (IS_ERR(u.sregs2)) {
5651 r = PTR_ERR(u.sregs2);
5652 u.sregs2 = NULL;
5653 goto out;
5654 }
5655 r = __set_sregs2(vcpu, u.sregs2);
5656 break;
5657 }
Oliver Upton828ca892021-09-16 18:15:38 +00005658 case KVM_HAS_DEVICE_ATTR:
5659 case KVM_GET_DEVICE_ATTR:
5660 case KVM_SET_DEVICE_ATTR:
5661 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
5662 break;
Carsten Otte313a3dc2007-10-11 19:16:52 +02005663 default:
5664 r = -EINVAL;
5665 }
5666out:
Avi Kivityd1ac91d2010-06-20 15:54:43 +03005667 kfree(u.buffer);
Christoffer Dall9b0624712017-12-04 21:35:36 +01005668out_nofree:
5669 vcpu_put(vcpu);
Carsten Otte313a3dc2007-10-11 19:16:52 +02005670 return r;
5671}
5672
Souptick Joarder1499fa82018-04-19 00:49:58 +05305673vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
Carsten Otte5b1c1492012-01-04 10:25:23 +01005674{
5675 return VM_FAULT_SIGBUS;
5676}
5677
Carsten Otte1fe779f2007-10-29 16:08:35 +01005678static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
5679{
5680 int ret;
5681
5682 if (addr > (unsigned int)(-3 * PAGE_SIZE))
Guo Chao951179c2012-11-02 18:33:22 +08005683 return -EINVAL;
Jason Baronb36464772021-01-14 22:27:56 -05005684 ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005685 return ret;
5686}
5687
Sheng Yangb927a3c2009-07-21 10:42:48 +08005688static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
5689 u64 ident_addr)
5690{
Jason Baronb36464772021-01-14 22:27:56 -05005691 return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
Sheng Yangb927a3c2009-07-21 10:42:48 +08005692}
5693
Carsten Otte1fe779f2007-10-29 16:08:35 +01005694static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
Ben Gardonbc8a3d82019-04-08 11:07:30 -07005695 unsigned long kvm_nr_mmu_pages)
Carsten Otte1fe779f2007-10-29 16:08:35 +01005696{
5697 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
5698 return -EINVAL;
5699
Marcelo Tosatti79fac952009-12-23 14:35:26 -02005700 mutex_lock(&kvm->slots_lock);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005701
5702 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
Zhang Xiantaof05e70a2007-12-14 10:01:48 +08005703 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
Carsten Otte1fe779f2007-10-29 16:08:35 +01005704
Marcelo Tosatti79fac952009-12-23 14:35:26 -02005705 mutex_unlock(&kvm->slots_lock);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005706 return 0;
5707}
5708
Ben Gardonbc8a3d82019-04-08 11:07:30 -07005709static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
Carsten Otte1fe779f2007-10-29 16:08:35 +01005710{
Dave Hansen39de71e2010-08-19 18:11:14 -07005711 return kvm->arch.n_max_mmu_pages;
Carsten Otte1fe779f2007-10-29 16:08:35 +01005712}
5713
Carsten Otte1fe779f2007-10-29 16:08:35 +01005714static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5715{
David Hildenbrand90bca052017-04-07 10:50:23 +02005716 struct kvm_pic *pic = kvm->arch.vpic;
Carsten Otte1fe779f2007-10-29 16:08:35 +01005717 int r;
5718
5719 r = 0;
5720 switch (chip->chip_id) {
5721 case KVM_IRQCHIP_PIC_MASTER:
David Hildenbrand90bca052017-04-07 10:50:23 +02005722 memcpy(&chip->chip.pic, &pic->pics[0],
Carsten Otte1fe779f2007-10-29 16:08:35 +01005723 sizeof(struct kvm_pic_state));
5724 break;
5725 case KVM_IRQCHIP_PIC_SLAVE:
David Hildenbrand90bca052017-04-07 10:50:23 +02005726 memcpy(&chip->chip.pic, &pic->pics[1],
Carsten Otte1fe779f2007-10-29 16:08:35 +01005727 sizeof(struct kvm_pic_state));
5728 break;
5729 case KVM_IRQCHIP_IOAPIC:
David Hildenbrand33392b42017-04-07 10:50:27 +02005730 kvm_get_ioapic(kvm, &chip->chip.ioapic);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005731 break;
5732 default:
5733 r = -EINVAL;
5734 break;
5735 }
5736 return r;
5737}
5738
5739static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
5740{
David Hildenbrand90bca052017-04-07 10:50:23 +02005741 struct kvm_pic *pic = kvm->arch.vpic;
Carsten Otte1fe779f2007-10-29 16:08:35 +01005742 int r;
5743
5744 r = 0;
5745 switch (chip->chip_id) {
5746 case KVM_IRQCHIP_PIC_MASTER:
David Hildenbrand90bca052017-04-07 10:50:23 +02005747 spin_lock(&pic->lock);
5748 memcpy(&pic->pics[0], &chip->chip.pic,
Carsten Otte1fe779f2007-10-29 16:08:35 +01005749 sizeof(struct kvm_pic_state));
David Hildenbrand90bca052017-04-07 10:50:23 +02005750 spin_unlock(&pic->lock);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005751 break;
5752 case KVM_IRQCHIP_PIC_SLAVE:
David Hildenbrand90bca052017-04-07 10:50:23 +02005753 spin_lock(&pic->lock);
5754 memcpy(&pic->pics[1], &chip->chip.pic,
Carsten Otte1fe779f2007-10-29 16:08:35 +01005755 sizeof(struct kvm_pic_state));
David Hildenbrand90bca052017-04-07 10:50:23 +02005756 spin_unlock(&pic->lock);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005757 break;
5758 case KVM_IRQCHIP_IOAPIC:
David Hildenbrand33392b42017-04-07 10:50:27 +02005759 kvm_set_ioapic(kvm, &chip->chip.ioapic);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005760 break;
5761 default:
5762 r = -EINVAL;
5763 break;
5764 }
David Hildenbrand90bca052017-04-07 10:50:23 +02005765 kvm_pic_update_irq(pic);
Carsten Otte1fe779f2007-10-29 16:08:35 +01005766 return r;
5767}
5768
Sheng Yange0f63cb2008-03-04 00:50:59 +08005769static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5770{
Radim Krčmář34f39412016-03-02 22:56:50 +01005771 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
5772
5773 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
5774
5775 mutex_lock(&kps->lock);
5776 memcpy(ps, &kps->channels, sizeof(*ps));
5777 mutex_unlock(&kps->lock);
Saurabh Sengar2da29bc2015-10-30 12:56:11 +05305778 return 0;
Sheng Yange0f63cb2008-03-04 00:50:59 +08005779}
5780
5781static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
5782{
Andrew Honig01856042015-11-18 14:50:23 -08005783 int i;
Radim Krčmář09edea72016-03-02 22:56:43 +01005784 struct kvm_pit *pit = kvm->arch.vpit;
5785
5786 mutex_lock(&pit->pit_state.lock);
Radim Krčmář34f39412016-03-02 22:56:50 +01005787 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
Andrew Honig01856042015-11-18 14:50:23 -08005788 for (i = 0; i < 3; i++)
Radim Krčmář09edea72016-03-02 22:56:43 +01005789 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
5790 mutex_unlock(&pit->pit_state.lock);
Saurabh Sengar2da29bc2015-10-30 12:56:11 +05305791 return 0;
Beth Kone9f42752009-07-07 11:50:38 -04005792}
5793
5794static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5795{
Beth Kone9f42752009-07-07 11:50:38 -04005796 mutex_lock(&kvm->arch.vpit->pit_state.lock);
5797 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
5798 sizeof(ps->channels));
5799 ps->flags = kvm->arch.vpit->pit_state.flags;
5800 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
Vasiliy Kulikov97e69aa2010-10-30 22:54:47 +04005801 memset(&ps->reserved, 0, sizeof(ps->reserved));
Saurabh Sengar2da29bc2015-10-30 12:56:11 +05305802 return 0;
Beth Kone9f42752009-07-07 11:50:38 -04005803}
5804
5805static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
5806{
Saurabh Sengar2da29bc2015-10-30 12:56:11 +05305807 int start = 0;
Andrew Honig01856042015-11-18 14:50:23 -08005808 int i;
Beth Kone9f42752009-07-07 11:50:38 -04005809 u32 prev_legacy, cur_legacy;
Radim Krčmář09edea72016-03-02 22:56:43 +01005810 struct kvm_pit *pit = kvm->arch.vpit;
5811
5812 mutex_lock(&pit->pit_state.lock);
5813 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
Beth Kone9f42752009-07-07 11:50:38 -04005814 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
5815 if (!prev_legacy && cur_legacy)
5816 start = 1;
Radim Krčmář09edea72016-03-02 22:56:43 +01005817 memcpy(&pit->pit_state.channels, &ps->channels,
5818 sizeof(pit->pit_state.channels));
5819 pit->pit_state.flags = ps->flags;
Andrew Honig01856042015-11-18 14:50:23 -08005820 for (i = 0; i < 3; i++)
Radim Krčmář09edea72016-03-02 22:56:43 +01005821 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
Paolo Bonzinie5e57e72016-01-07 13:50:38 +01005822 start && i == 0);
Radim Krčmář09edea72016-03-02 22:56:43 +01005823 mutex_unlock(&pit->pit_state.lock);
Saurabh Sengar2da29bc2015-10-30 12:56:11 +05305824 return 0;
Sheng Yange0f63cb2008-03-04 00:50:59 +08005825}
5826
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02005827static int kvm_vm_ioctl_reinject(struct kvm *kvm,
5828 struct kvm_reinject_control *control)
5829{
Radim Krčmář71474e22016-03-02 22:56:45 +01005830 struct kvm_pit *pit = kvm->arch.vpit;
5831
Radim Krčmář71474e22016-03-02 22:56:45 +01005832 /* pit->pit_state.lock was overloaded to prevent userspace from getting
5833 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
5834 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
5835 */
5836 mutex_lock(&pit->pit_state.lock);
5837 kvm_pit_set_reinject(pit, control->pit_reinject);
5838 mutex_unlock(&pit->pit_state.lock);
Radim Krčmářb39c90b2016-03-02 22:56:44 +01005839
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02005840 return 0;
5841}
5842
Sean Christopherson0dff0842020-02-18 13:07:29 -08005843void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
Zhang Xiantao5bb064d2007-11-18 20:29:43 +08005844{
Sean Christophersona018eba2021-02-12 16:50:10 -08005845
Kai Huang88178fd2015-01-28 10:54:27 +08005846 /*
Sean Christophersona018eba2021-02-12 16:50:10 -08005847 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
5848 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
5849 * on all VM-Exits, thus we only need to kick running vCPUs to force a
5850 * VM-Exit.
Kai Huang88178fd2015-01-28 10:54:27 +08005851 */
Sean Christophersona018eba2021-02-12 16:50:10 -08005852 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +00005853 unsigned long i;
Sean Christophersona018eba2021-02-12 16:50:10 -08005854
5855 kvm_for_each_vcpu(i, vcpu, kvm)
5856 kvm_vcpu_kick(vcpu);
Zhang Xiantao5bb064d2007-11-18 20:29:43 +08005857}
5858
Yang Zhangaa2fbe62013-04-11 19:21:40 +08005859int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
5860 bool line_status)
Christoffer Dall23d43cf2012-07-24 08:51:20 -04005861{
5862 if (!irqchip_in_kernel(kvm))
5863 return -ENXIO;
5864
5865 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
Yang Zhangaa2fbe62013-04-11 19:21:40 +08005866 irq_event->irq, irq_event->level,
5867 line_status);
Christoffer Dall23d43cf2012-07-24 08:51:20 -04005868 return 0;
5869}
5870
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01005871int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
5872 struct kvm_enable_cap *cap)
Nadav Amit90de4a12015-04-13 01:53:41 +03005873{
5874 int r;
5875
5876 if (cap->flags)
5877 return -EINVAL;
5878
5879 switch (cap->cap) {
5880 case KVM_CAP_DISABLE_QUIRKS:
5881 kvm->arch.disabled_quirks = cap->args[0];
5882 r = 0;
5883 break;
Steve Rutherford49df6392015-07-29 23:21:40 -07005884 case KVM_CAP_SPLIT_IRQCHIP: {
5885 mutex_lock(&kvm->lock);
Steve Rutherfordb053b2a2015-07-29 23:32:35 -07005886 r = -EINVAL;
5887 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
5888 goto split_irqchip_unlock;
Steve Rutherford49df6392015-07-29 23:21:40 -07005889 r = -EEXIST;
5890 if (irqchip_in_kernel(kvm))
5891 goto split_irqchip_unlock;
Paolo Bonzini557abc42016-06-13 14:50:04 +02005892 if (kvm->created_vcpus)
Steve Rutherford49df6392015-07-29 23:21:40 -07005893 goto split_irqchip_unlock;
5894 r = kvm_setup_empty_irq_routing(kvm);
David Hildenbrand5c0aea02017-04-28 17:06:20 +02005895 if (r)
Steve Rutherford49df6392015-07-29 23:21:40 -07005896 goto split_irqchip_unlock;
5897 /* Pairs with irqchip_in_kernel. */
5898 smp_wmb();
Radim Krčmář49776fa2016-12-16 16:10:02 +01005899 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
Steve Rutherfordb053b2a2015-07-29 23:32:35 -07005900 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
Paolo Bonzinief8b4b72021-11-30 07:37:45 -05005901 kvm_request_apicv_update(kvm, true, APICV_INHIBIT_REASON_ABSENT);
Steve Rutherford49df6392015-07-29 23:21:40 -07005902 r = 0;
5903split_irqchip_unlock:
5904 mutex_unlock(&kvm->lock);
5905 break;
5906 }
Radim Krčmář371313132016-07-12 22:09:27 +02005907 case KVM_CAP_X2APIC_API:
5908 r = -EINVAL;
5909 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
5910 break;
5911
5912 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5913 kvm->arch.x2apic_format = true;
Radim Krčmářc5192652016-07-12 22:09:28 +02005914 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5915 kvm->arch.x2apic_broadcast_quirk_disabled = true;
Radim Krčmář371313132016-07-12 22:09:27 +02005916
5917 r = 0;
5918 break;
Wanpeng Li4d5422c2018-03-12 04:53:02 -07005919 case KVM_CAP_X86_DISABLE_EXITS:
5920 r = -EINVAL;
5921 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5922 break;
5923
5924 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5925 kvm_can_mwait_in_guest())
5926 kvm->arch.mwait_in_guest = true;
Michael S. Tsirkin766d3572018-06-08 02:19:53 +03005927 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
Wanpeng Licaa057a2018-03-12 04:53:03 -07005928 kvm->arch.hlt_in_guest = true;
Wanpeng Lib31c1142018-03-12 04:53:04 -07005929 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5930 kvm->arch.pause_in_guest = true;
Wanpeng Lib5170062019-05-21 14:06:53 +08005931 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5932 kvm->arch.cstate_in_guest = true;
Wanpeng Li4d5422c2018-03-12 04:53:02 -07005933 r = 0;
5934 break;
Drew Schmitt6fbbde92018-08-20 10:32:15 -07005935 case KVM_CAP_MSR_PLATFORM_INFO:
5936 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5937 r = 0;
5938 break;
Jim Mattsonc4f55192018-10-16 14:29:24 -07005939 case KVM_CAP_EXCEPTION_PAYLOAD:
5940 kvm->arch.exception_payload_enabled = cap->args[0];
5941 r = 0;
5942 break;
Alexander Graf1ae09952020-09-25 16:34:16 +02005943 case KVM_CAP_X86_USER_SPACE_MSR:
5944 kvm->arch.user_space_msr_mask = cap->args[0];
5945 r = 0;
5946 break;
Chenyi Qiangfe6b6bc2020-11-06 17:03:14 +08005947 case KVM_CAP_X86_BUS_LOCK_EXIT:
5948 r = -EINVAL;
5949 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
5950 break;
5951
5952 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
5953 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
5954 break;
5955
5956 if (kvm_has_bus_lock_exit &&
5957 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
5958 kvm->arch.bus_lock_detection_enabled = true;
5959 r = 0;
5960 break;
Sean Christophersonfe7e9482021-04-12 16:21:43 +12005961#ifdef CONFIG_X86_SGX_KVM
5962 case KVM_CAP_SGX_ATTRIBUTE: {
5963 unsigned long allowed_attributes = 0;
5964
5965 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
5966 if (r)
5967 break;
5968
5969 /* KVM only supports the PROVISIONKEY privileged attribute. */
5970 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
5971 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
5972 kvm->arch.sgx_provisioning_allowed = true;
5973 else
5974 r = -EINVAL;
5975 break;
5976 }
5977#endif
Nathan Tempelman54526d12021-04-08 22:32:14 +00005978 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
5979 r = -EINVAL;
5980 if (kvm_x86_ops.vm_copy_enc_context_from)
5981 r = kvm_x86_ops.vm_copy_enc_context_from(kvm, cap->args[0]);
5982 return r;
Peter Gondab5663932021-10-21 10:43:00 -07005983 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
5984 r = -EINVAL;
5985 if (kvm_x86_ops.vm_move_enc_context_from)
5986 r = kvm_x86_ops.vm_move_enc_context_from(
5987 kvm, cap->args[0]);
5988 return r;
Ashish Kalra0dbb1122021-06-08 18:05:43 +00005989 case KVM_CAP_EXIT_HYPERCALL:
5990 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
5991 r = -EINVAL;
5992 break;
5993 }
5994 kvm->arch.hypercall_exit_enabled = cap->args[0];
5995 r = 0;
5996 break;
Aaron Lewis19238e72021-05-10 07:48:33 -07005997 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
5998 r = -EINVAL;
5999 if (cap->args[0] & ~1)
6000 break;
6001 kvm->arch.exit_on_emulation_error = cap->args[0];
6002 r = 0;
6003 break;
Nadav Amit90de4a12015-04-13 01:53:41 +03006004 default:
6005 r = -EINVAL;
6006 break;
6007 }
6008 return r;
6009}
6010
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006011static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
Alexander Graf1a1552542020-09-25 16:34:21 +02006012{
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006013 struct kvm_x86_msr_filter *msr_filter;
Alexander Graf1a1552542020-09-25 16:34:21 +02006014
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006015 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6016 if (!msr_filter)
6017 return NULL;
Alexander Graf1a1552542020-09-25 16:34:21 +02006018
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006019 msr_filter->default_allow = default_allow;
6020 return msr_filter;
Alexander Graf1a1552542020-09-25 16:34:21 +02006021}
6022
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006023static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
Alexander Graf1a1552542020-09-25 16:34:21 +02006024{
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006025 u32 i;
6026
6027 if (!msr_filter)
6028 return;
6029
6030 for (i = 0; i < msr_filter->count; i++)
6031 kfree(msr_filter->ranges[i].bitmap);
6032
6033 kfree(msr_filter);
6034}
6035
6036static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6037 struct kvm_msr_filter_range *user_range)
6038{
Alexander Graf1a1552542020-09-25 16:34:21 +02006039 unsigned long *bitmap = NULL;
6040 size_t bitmap_size;
Alexander Graf1a1552542020-09-25 16:34:21 +02006041
6042 if (!user_range->nmsrs)
6043 return 0;
6044
Siddharth Chandrasekaranaca35282021-05-03 14:21:11 +02006045 if (user_range->flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE))
6046 return -EINVAL;
6047
6048 if (!user_range->flags)
6049 return -EINVAL;
6050
Alexander Graf1a1552542020-09-25 16:34:21 +02006051 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6052 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6053 return -EINVAL;
6054
6055 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6056 if (IS_ERR(bitmap))
6057 return PTR_ERR(bitmap);
6058
Siddharth Chandrasekaranaca35282021-05-03 14:21:11 +02006059 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
Alexander Graf1a1552542020-09-25 16:34:21 +02006060 .flags = user_range->flags,
6061 .base = user_range->base,
6062 .nmsrs = user_range->nmsrs,
6063 .bitmap = bitmap,
6064 };
6065
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006066 msr_filter->count++;
Alexander Graf1a1552542020-09-25 16:34:21 +02006067 return 0;
Alexander Graf1a1552542020-09-25 16:34:21 +02006068}
6069
6070static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm, void __user *argp)
6071{
6072 struct kvm_msr_filter __user *user_msr_filter = argp;
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006073 struct kvm_x86_msr_filter *new_filter, *old_filter;
Alexander Graf1a1552542020-09-25 16:34:21 +02006074 struct kvm_msr_filter filter;
6075 bool default_allow;
Paolo Bonzini043248b2020-10-20 10:57:01 -04006076 bool empty = true;
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006077 int r = 0;
Alexander Graf1a1552542020-09-25 16:34:21 +02006078 u32 i;
6079
6080 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
6081 return -EFAULT;
6082
Paolo Bonzini043248b2020-10-20 10:57:01 -04006083 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++)
6084 empty &= !filter.ranges[i].nmsrs;
Alexander Graf1a1552542020-09-25 16:34:21 +02006085
6086 default_allow = !(filter.flags & KVM_MSR_FILTER_DEFAULT_DENY);
Paolo Bonzini043248b2020-10-20 10:57:01 -04006087 if (empty && !default_allow)
6088 return -EINVAL;
6089
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006090 new_filter = kvm_alloc_msr_filter(default_allow);
6091 if (!new_filter)
6092 return -ENOMEM;
Paolo Bonzini043248b2020-10-20 10:57:01 -04006093
Alexander Graf1a1552542020-09-25 16:34:21 +02006094 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006095 r = kvm_add_msr_filter(new_filter, &filter.ranges[i]);
6096 if (r) {
6097 kvm_free_msr_filter(new_filter);
6098 return r;
6099 }
Alexander Graf1a1552542020-09-25 16:34:21 +02006100 }
6101
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006102 mutex_lock(&kvm->lock);
6103
6104 /* The per-VM filter is protected by kvm->lock... */
6105 old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
6106
6107 rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
6108 synchronize_srcu(&kvm->srcu);
6109
6110 kvm_free_msr_filter(old_filter);
6111
Alexander Graf1a1552542020-09-25 16:34:21 +02006112 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6113 mutex_unlock(&kvm->lock);
6114
Sean Christophersonb318e8d2021-03-16 11:44:33 -07006115 return 0;
Alexander Graf1a1552542020-09-25 16:34:21 +02006116}
6117
Sergey Senozhatsky7d628742021-06-06 11:10:45 +09006118#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
6119static int kvm_arch_suspend_notifier(struct kvm *kvm)
6120{
6121 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +00006122 unsigned long i;
6123 int ret = 0;
Sergey Senozhatsky7d628742021-06-06 11:10:45 +09006124
6125 mutex_lock(&kvm->lock);
6126 kvm_for_each_vcpu(i, vcpu, kvm) {
6127 if (!vcpu->arch.pv_time_enabled)
6128 continue;
6129
6130 ret = kvm_set_guest_paused(vcpu);
6131 if (ret) {
6132 kvm_err("Failed to pause guest VCPU%d: %d\n",
6133 vcpu->vcpu_id, ret);
6134 break;
6135 }
6136 }
6137 mutex_unlock(&kvm->lock);
6138
6139 return ret ? NOTIFY_BAD : NOTIFY_DONE;
6140}
6141
6142int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6143{
6144 switch (state) {
6145 case PM_HIBERNATION_PREPARE:
6146 case PM_SUSPEND_PREPARE:
6147 return kvm_arch_suspend_notifier(kvm);
6148 }
6149
6150 return NOTIFY_DONE;
6151}
6152#endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
6153
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006154static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
6155{
Paolo Bonzini869b4422021-09-16 18:15:36 +00006156 struct kvm_clock_data data = { 0 };
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006157
Oliver Upton55c0cef2021-09-16 18:15:34 +00006158 get_kvmclock(kvm, &data);
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006159 if (copy_to_user(argp, &data, sizeof(data)))
6160 return -EFAULT;
6161
6162 return 0;
6163}
6164
6165static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
6166{
6167 struct kvm_arch *ka = &kvm->arch;
6168 struct kvm_clock_data data;
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00006169 u64 now_raw_ns;
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006170
6171 if (copy_from_user(&data, argp, sizeof(data)))
6172 return -EFAULT;
6173
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00006174 /*
6175 * Only KVM_CLOCK_REALTIME is used, but allow passing the
6176 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
6177 */
6178 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006179 return -EINVAL;
6180
6181 kvm_hv_invalidate_tsc_page(kvm);
6182 kvm_start_pvclock_update(kvm);
6183 pvclock_update_vm_gtod_copy(kvm);
6184
6185 /*
6186 * This pairs with kvm_guest_time_update(): when masterclock is
6187 * in use, we use master_kernel_ns + kvmclock_offset to set
6188 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
6189 * is slightly ahead) here we risk going negative on unsigned
6190 * 'system_time' when 'data.clock' is very small.
6191 */
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00006192 if (data.flags & KVM_CLOCK_REALTIME) {
6193 u64 now_real_ns = ktime_get_real_ns();
6194
6195 /*
6196 * Avoid stepping the kvmclock backwards.
6197 */
6198 if (now_real_ns > data.realtime)
6199 data.clock += now_real_ns - data.realtime;
6200 }
6201
6202 if (ka->use_master_clock)
6203 now_raw_ns = ka->master_kernel_ns;
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006204 else
Oliver Uptonc68dc1b2021-09-16 18:15:35 +00006205 now_raw_ns = get_kvmclock_base_ns();
6206 ka->kvmclock_offset = data.clock - now_raw_ns;
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006207 kvm_end_pvclock_update(kvm);
6208 return 0;
6209}
6210
Carsten Otte1fe779f2007-10-29 16:08:35 +01006211long kvm_arch_vm_ioctl(struct file *filp,
6212 unsigned int ioctl, unsigned long arg)
6213{
6214 struct kvm *kvm = filp->private_data;
6215 void __user *argp = (void __user *)arg;
Avi Kivity367e1312009-08-26 14:57:07 +03006216 int r = -ENOTTY;
Dave Hansenf0d66272008-08-11 10:01:45 -07006217 /*
6218 * This union makes it completely explicit to gcc-3.x
6219 * that these two variables' stack usage should be
6220 * combined, not added together.
6221 */
6222 union {
6223 struct kvm_pit_state ps;
Beth Kone9f42752009-07-07 11:50:38 -04006224 struct kvm_pit_state2 ps2;
Jan Kiszkac5ff41c2009-05-14 22:42:53 +02006225 struct kvm_pit_config pit_config;
Dave Hansenf0d66272008-08-11 10:01:45 -07006226 } u;
Carsten Otte1fe779f2007-10-29 16:08:35 +01006227
6228 switch (ioctl) {
6229 case KVM_SET_TSS_ADDR:
6230 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006231 break;
Sheng Yangb927a3c2009-07-21 10:42:48 +08006232 case KVM_SET_IDENTITY_MAP_ADDR: {
6233 u64 ident_addr;
6234
David Hildenbrand1af1ac92017-08-24 20:51:36 +02006235 mutex_lock(&kvm->lock);
6236 r = -EINVAL;
6237 if (kvm->created_vcpus)
6238 goto set_identity_unlock;
Sheng Yangb927a3c2009-07-21 10:42:48 +08006239 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00006240 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
David Hildenbrand1af1ac92017-08-24 20:51:36 +02006241 goto set_identity_unlock;
Sheng Yangb927a3c2009-07-21 10:42:48 +08006242 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
David Hildenbrand1af1ac92017-08-24 20:51:36 +02006243set_identity_unlock:
6244 mutex_unlock(&kvm->lock);
Sheng Yangb927a3c2009-07-21 10:42:48 +08006245 break;
6246 }
Carsten Otte1fe779f2007-10-29 16:08:35 +01006247 case KVM_SET_NR_MMU_PAGES:
6248 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006249 break;
6250 case KVM_GET_NR_MMU_PAGES:
6251 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
6252 break;
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006253 case KVM_CREATE_IRQCHIP: {
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006254 mutex_lock(&kvm->lock);
Radim Krčmář09941362016-12-16 16:10:03 +01006255
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006256 r = -EEXIST;
Radim Krčmář35e6eaa2016-12-16 16:10:01 +01006257 if (irqchip_in_kernel(kvm))
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006258 goto create_irqchip_unlock;
Radim Krčmář09941362016-12-16 16:10:03 +01006259
Avi Kivity3e515702012-03-05 14:23:29 +02006260 r = -EINVAL;
Paolo Bonzini557abc42016-06-13 14:50:04 +02006261 if (kvm->created_vcpus)
Avi Kivity3e515702012-03-05 14:23:29 +02006262 goto create_irqchip_unlock;
Radim Krčmář09941362016-12-16 16:10:03 +01006263
6264 r = kvm_pic_init(kvm);
6265 if (r)
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006266 goto create_irqchip_unlock;
Radim Krčmář09941362016-12-16 16:10:03 +01006267
6268 r = kvm_ioapic_init(kvm);
6269 if (r) {
Radim Krčmář09941362016-12-16 16:10:03 +01006270 kvm_pic_destroy(kvm);
Radim Krčmář09941362016-12-16 16:10:03 +01006271 goto create_irqchip_unlock;
6272 }
6273
Avi Kivity399ec802008-11-19 13:58:46 +02006274 r = kvm_setup_default_irq_routing(kvm);
6275 if (r) {
Wei Yongjun72bb2fc2010-02-09 10:33:03 +08006276 kvm_ioapic_destroy(kvm);
Radim Krčmář09941362016-12-16 16:10:03 +01006277 kvm_pic_destroy(kvm);
Paolo Bonzini71ba9942015-07-29 12:31:15 +02006278 goto create_irqchip_unlock;
Avi Kivity399ec802008-11-19 13:58:46 +02006279 }
Radim Krčmář49776fa2016-12-16 16:10:02 +01006280 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
Paolo Bonzini71ba9942015-07-29 12:31:15 +02006281 smp_wmb();
Radim Krčmář49776fa2016-12-16 16:10:02 +01006282 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
Paolo Bonzinief8b4b72021-11-30 07:37:45 -05006283 kvm_request_apicv_update(kvm, true, APICV_INHIBIT_REASON_ABSENT);
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006284 create_irqchip_unlock:
6285 mutex_unlock(&kvm->lock);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006286 break;
Marcelo Tosatti3ddea122009-10-29 13:44:15 -02006287 }
Sheng Yang78376992008-01-28 05:10:22 +08006288 case KVM_CREATE_PIT:
Jan Kiszkac5ff41c2009-05-14 22:42:53 +02006289 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
6290 goto create_pit;
6291 case KVM_CREATE_PIT2:
6292 r = -EFAULT;
6293 if (copy_from_user(&u.pit_config, argp,
6294 sizeof(struct kvm_pit_config)))
6295 goto out;
6296 create_pit:
Paolo Bonzini250715a2016-06-01 14:09:24 +02006297 mutex_lock(&kvm->lock);
Avi Kivity269e05e2009-01-05 15:21:42 +02006298 r = -EEXIST;
6299 if (kvm->arch.vpit)
6300 goto create_pit_unlock;
Sheng Yang78376992008-01-28 05:10:22 +08006301 r = -ENOMEM;
Jan Kiszkac5ff41c2009-05-14 22:42:53 +02006302 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
Sheng Yang78376992008-01-28 05:10:22 +08006303 if (kvm->arch.vpit)
6304 r = 0;
Avi Kivity269e05e2009-01-05 15:21:42 +02006305 create_pit_unlock:
Paolo Bonzini250715a2016-06-01 14:09:24 +02006306 mutex_unlock(&kvm->lock);
Sheng Yang78376992008-01-28 05:10:22 +08006307 break;
Carsten Otte1fe779f2007-10-29 16:08:35 +01006308 case KVM_GET_IRQCHIP: {
6309 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
Sasha Levinff5c2c02011-12-04 19:36:29 +02006310 struct kvm_irqchip *chip;
Carsten Otte1fe779f2007-10-29 16:08:35 +01006311
Sasha Levinff5c2c02011-12-04 19:36:29 +02006312 chip = memdup_user(argp, sizeof(*chip));
6313 if (IS_ERR(chip)) {
6314 r = PTR_ERR(chip);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006315 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02006316 }
6317
Carsten Otte1fe779f2007-10-29 16:08:35 +01006318 r = -ENXIO;
Radim Krčmář826da322016-12-16 16:10:06 +01006319 if (!irqchip_kernel(kvm))
Dave Hansenf0d66272008-08-11 10:01:45 -07006320 goto get_irqchip_out;
6321 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
6322 if (r)
6323 goto get_irqchip_out;
6324 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00006325 if (copy_to_user(argp, chip, sizeof(*chip)))
Dave Hansenf0d66272008-08-11 10:01:45 -07006326 goto get_irqchip_out;
6327 r = 0;
6328 get_irqchip_out:
6329 kfree(chip);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006330 break;
6331 }
6332 case KVM_SET_IRQCHIP: {
6333 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
Sasha Levinff5c2c02011-12-04 19:36:29 +02006334 struct kvm_irqchip *chip;
Carsten Otte1fe779f2007-10-29 16:08:35 +01006335
Sasha Levinff5c2c02011-12-04 19:36:29 +02006336 chip = memdup_user(argp, sizeof(*chip));
6337 if (IS_ERR(chip)) {
6338 r = PTR_ERR(chip);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006339 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02006340 }
6341
Carsten Otte1fe779f2007-10-29 16:08:35 +01006342 r = -ENXIO;
Radim Krčmář826da322016-12-16 16:10:06 +01006343 if (!irqchip_kernel(kvm))
Dave Hansenf0d66272008-08-11 10:01:45 -07006344 goto set_irqchip_out;
6345 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
Dave Hansenf0d66272008-08-11 10:01:45 -07006346 set_irqchip_out:
6347 kfree(chip);
Carsten Otte1fe779f2007-10-29 16:08:35 +01006348 break;
6349 }
Sheng Yange0f63cb2008-03-04 00:50:59 +08006350 case KVM_GET_PIT: {
Sheng Yange0f63cb2008-03-04 00:50:59 +08006351 r = -EFAULT;
Dave Hansenf0d66272008-08-11 10:01:45 -07006352 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
Sheng Yange0f63cb2008-03-04 00:50:59 +08006353 goto out;
6354 r = -ENXIO;
6355 if (!kvm->arch.vpit)
6356 goto out;
Dave Hansenf0d66272008-08-11 10:01:45 -07006357 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
Sheng Yange0f63cb2008-03-04 00:50:59 +08006358 if (r)
6359 goto out;
6360 r = -EFAULT;
Dave Hansenf0d66272008-08-11 10:01:45 -07006361 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
Sheng Yange0f63cb2008-03-04 00:50:59 +08006362 goto out;
6363 r = 0;
6364 break;
6365 }
6366 case KVM_SET_PIT: {
Sheng Yange0f63cb2008-03-04 00:50:59 +08006367 r = -EFAULT;
Jordan Borgner0e96f312018-10-28 12:58:28 +00006368 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
Sheng Yange0f63cb2008-03-04 00:50:59 +08006369 goto out;
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006370 mutex_lock(&kvm->lock);
Sheng Yange0f63cb2008-03-04 00:50:59 +08006371 r = -ENXIO;
6372 if (!kvm->arch.vpit)
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006373 goto set_pit_out;
Dave Hansenf0d66272008-08-11 10:01:45 -07006374 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006375set_pit_out:
6376 mutex_unlock(&kvm->lock);
Sheng Yange0f63cb2008-03-04 00:50:59 +08006377 break;
6378 }
Beth Kone9f42752009-07-07 11:50:38 -04006379 case KVM_GET_PIT2: {
6380 r = -ENXIO;
6381 if (!kvm->arch.vpit)
6382 goto out;
6383 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
6384 if (r)
6385 goto out;
6386 r = -EFAULT;
6387 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
6388 goto out;
6389 r = 0;
6390 break;
6391 }
6392 case KVM_SET_PIT2: {
6393 r = -EFAULT;
6394 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
6395 goto out;
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006396 mutex_lock(&kvm->lock);
Beth Kone9f42752009-07-07 11:50:38 -04006397 r = -ENXIO;
6398 if (!kvm->arch.vpit)
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006399 goto set_pit2_out;
Beth Kone9f42752009-07-07 11:50:38 -04006400 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
Steve Rutherford7289fdb2020-04-16 12:11:52 -07006401set_pit2_out:
6402 mutex_unlock(&kvm->lock);
Beth Kone9f42752009-07-07 11:50:38 -04006403 break;
6404 }
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02006405 case KVM_REINJECT_CONTROL: {
6406 struct kvm_reinject_control control;
6407 r = -EFAULT;
6408 if (copy_from_user(&control, argp, sizeof(control)))
6409 goto out;
Miaohe Lincad23e72019-12-07 17:25:22 +08006410 r = -ENXIO;
6411 if (!kvm->arch.vpit)
6412 goto out;
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02006413 r = kvm_vm_ioctl_reinject(kvm, &control);
Marcelo Tosatti52d939a2008-12-30 15:55:06 -02006414 break;
6415 }
Paolo Bonzinid71ba782015-07-29 11:56:48 +02006416 case KVM_SET_BOOT_CPU_ID:
6417 r = 0;
6418 mutex_lock(&kvm->lock);
Paolo Bonzini557abc42016-06-13 14:50:04 +02006419 if (kvm->created_vcpus)
Paolo Bonzinid71ba782015-07-29 11:56:48 +02006420 r = -EBUSY;
6421 else
6422 kvm->arch.bsp_vcpu_id = arg;
6423 mutex_unlock(&kvm->lock);
6424 break;
Paolo Bonzinib59b1532021-02-26 04:54:45 -05006425#ifdef CONFIG_KVM_XEN
Ed Swierkffde22a2009-10-15 15:21:43 -07006426 case KVM_XEN_HVM_CONFIG: {
Paolo Bonzini51776042017-10-26 15:45:47 +02006427 struct kvm_xen_hvm_config xhc;
Ed Swierkffde22a2009-10-15 15:21:43 -07006428 r = -EFAULT;
Paolo Bonzini51776042017-10-26 15:45:47 +02006429 if (copy_from_user(&xhc, argp, sizeof(xhc)))
Ed Swierkffde22a2009-10-15 15:21:43 -07006430 goto out;
David Woodhouse78e98782021-02-02 13:19:35 +00006431 r = kvm_xen_hvm_config(kvm, &xhc);
Ed Swierkffde22a2009-10-15 15:21:43 -07006432 break;
6433 }
Joao Martinsa76b9642020-12-03 15:52:25 +00006434 case KVM_XEN_HVM_GET_ATTR: {
6435 struct kvm_xen_hvm_attr xha;
6436
6437 r = -EFAULT;
6438 if (copy_from_user(&xha, argp, sizeof(xha)))
Hannes Edercded19f2009-02-21 02:19:13 +01006439 goto out;
Joao Martinsa76b9642020-12-03 15:52:25 +00006440 r = kvm_xen_hvm_get_attr(kvm, &xha);
6441 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
6442 r = -EFAULT;
6443 break;
6444 }
6445 case KVM_XEN_HVM_SET_ATTR: {
6446 struct kvm_xen_hvm_attr xha;
6447
6448 r = -EFAULT;
6449 if (copy_from_user(&xha, argp, sizeof(xha)))
6450 goto out;
6451 r = kvm_xen_hvm_set_attr(kvm, &xha);
Carsten Ottebbd9b642007-10-30 18:44:21 +01006452 break;
6453 }
Paolo Bonzinib59b1532021-02-26 04:54:45 -05006454#endif
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006455 case KVM_SET_CLOCK:
6456 r = kvm_vm_ioctl_set_clock(kvm, argp);
Glauber Costaafbcf7a2009-10-16 15:28:36 -04006457 break;
Paolo Bonzini45e6c2f2021-09-16 18:15:33 +00006458 case KVM_GET_CLOCK:
6459 r = kvm_vm_ioctl_get_clock(kvm, argp);
Glauber Costaafbcf7a2009-10-16 15:28:36 -04006460 break;
Brijesh Singh5acc5c02017-12-04 10:57:26 -06006461 case KVM_MEMORY_ENCRYPT_OP: {
6462 r = -ENOTTY;
Sean Christophersonafaf0b22020-03-21 13:26:00 -07006463 if (kvm_x86_ops.mem_enc_op)
Jason Baronb36464772021-01-14 22:27:56 -05006464 r = static_call(kvm_x86_mem_enc_op)(kvm, argp);
Brijesh Singh5acc5c02017-12-04 10:57:26 -06006465 break;
6466 }
Brijesh Singh69eaede2017-12-04 10:57:26 -06006467 case KVM_MEMORY_ENCRYPT_REG_REGION: {
6468 struct kvm_enc_region region;
6469
6470 r = -EFAULT;
6471 if (copy_from_user(&region, argp, sizeof(region)))
6472 goto out;
6473
6474 r = -ENOTTY;
Sean Christophersonafaf0b22020-03-21 13:26:00 -07006475 if (kvm_x86_ops.mem_enc_reg_region)
Jason Baronb36464772021-01-14 22:27:56 -05006476 r = static_call(kvm_x86_mem_enc_reg_region)(kvm, &region);
Brijesh Singh69eaede2017-12-04 10:57:26 -06006477 break;
6478 }
6479 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
6480 struct kvm_enc_region region;
6481
6482 r = -EFAULT;
6483 if (copy_from_user(&region, argp, sizeof(region)))
6484 goto out;
6485
6486 r = -ENOTTY;
Sean Christophersonafaf0b22020-03-21 13:26:00 -07006487 if (kvm_x86_ops.mem_enc_unreg_region)
Jason Baronb36464772021-01-14 22:27:56 -05006488 r = static_call(kvm_x86_mem_enc_unreg_region)(kvm, &region);
Brijesh Singh69eaede2017-12-04 10:57:26 -06006489 break;
6490 }
Roman Kaganfaeb7832018-02-01 16:48:32 +03006491 case KVM_HYPERV_EVENTFD: {
6492 struct kvm_hyperv_eventfd hvevfd;
6493
6494 r = -EFAULT;
6495 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
6496 goto out;
6497 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
6498 break;
6499 }
Eric Hankland66bb8a02019-07-10 18:25:15 -07006500 case KVM_SET_PMU_EVENT_FILTER:
6501 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
6502 break;
Alexander Graf1a1552542020-09-25 16:34:21 +02006503 case KVM_X86_SET_MSR_FILTER:
6504 r = kvm_vm_ioctl_set_msr_filter(kvm, argp);
6505 break;
Carsten Otte043405e2007-10-10 17:16:19 +02006506 default:
Paolo Bonziniad6260d2017-03-27 14:30:40 +02006507 r = -ENOTTY;
Carsten Otte043405e2007-10-10 17:16:19 +02006508 }
6509out:
6510 return r;
6511}
6512
6513static void kvm_init_msr_list(void)
6514{
Paolo Bonzini24c29b72019-10-01 15:18:26 +02006515 struct x86_pmu_capability x86_pmu;
Carsten Otte043405e2007-10-10 17:16:19 +02006516 u32 dummy[2];
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006517 unsigned i;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006518
Jim Mattsone2ada662019-08-21 11:20:04 -07006519 BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006520 "Please update the fixed PMCs in msrs_to_saved_all[]");
Paolo Bonzini24c29b72019-10-01 15:18:26 +02006521
6522 perf_get_x86_pmu_capability(&x86_pmu);
Jim Mattsone2ada662019-08-21 11:20:04 -07006523
Xiaoyao Li6cbee2b2019-11-13 09:15:21 +08006524 num_msrs_to_save = 0;
6525 num_emulated_msrs = 0;
6526 num_msr_based_features = 0;
6527
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006528 for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
6529 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
Carsten Ottebbd9b642007-10-30 18:44:21 +01006530 continue;
Paolo Bonzini93c4adc2014-03-05 23:19:52 +01006531
6532 /*
6533 * Even MSRs that are valid in the host may not be exposed
Paolo Bonzini9dbe6cf2015-11-12 14:49:17 +01006534 * to the guests in some cases.
Paolo Bonzini93c4adc2014-03-05 23:19:52 +01006535 */
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006536 switch (msrs_to_save_all[i]) {
Paolo Bonzini93c4adc2014-03-05 23:19:52 +01006537 case MSR_IA32_BNDCFGS:
Liran Alon503234b2018-09-14 03:25:53 +03006538 if (!kvm_mpx_supported())
Paolo Bonzini93c4adc2014-03-05 23:19:52 +01006539 continue;
6540 break;
Paolo Bonzini9dbe6cf2015-11-12 14:49:17 +01006541 case MSR_TSC_AUX:
Sean Christopherson36fa06f2021-05-04 10:17:26 -07006542 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
6543 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
Paolo Bonzini9dbe6cf2015-11-12 14:49:17 +01006544 continue;
6545 break;
Maxim Levitskyf4cfcd22020-05-23 19:14:55 +03006546 case MSR_IA32_UMWAIT_CONTROL:
6547 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
6548 continue;
6549 break;
Chao Pengbf8c55d2018-10-24 16:05:14 +08006550 case MSR_IA32_RTIT_CTL:
6551 case MSR_IA32_RTIT_STATUS:
Sean Christopherson7b874c22020-03-02 15:56:59 -08006552 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
Chao Pengbf8c55d2018-10-24 16:05:14 +08006553 continue;
6554 break;
6555 case MSR_IA32_RTIT_CR3_MATCH:
Sean Christopherson7b874c22020-03-02 15:56:59 -08006556 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
Chao Pengbf8c55d2018-10-24 16:05:14 +08006557 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
6558 continue;
6559 break;
6560 case MSR_IA32_RTIT_OUTPUT_BASE:
6561 case MSR_IA32_RTIT_OUTPUT_MASK:
Sean Christopherson7b874c22020-03-02 15:56:59 -08006562 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
Chao Pengbf8c55d2018-10-24 16:05:14 +08006563 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
6564 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
6565 continue;
6566 break;
Sean Christopherson7cb85fc2020-02-18 15:40:10 -08006567 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
Sean Christopherson7b874c22020-03-02 15:56:59 -08006568 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006569 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
Chao Pengbf8c55d2018-10-24 16:05:14 +08006570 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
6571 continue;
6572 break;
Paolo Bonzinicf05a672019-10-01 15:33:07 +02006573 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006574 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
Paolo Bonzini24c29b72019-10-01 15:18:26 +02006575 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
6576 continue;
6577 break;
Paolo Bonzinicf05a672019-10-01 15:33:07 +02006578 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006579 if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
Paolo Bonzini24c29b72019-10-01 15:18:26 +02006580 min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
6581 continue;
Sean Christopherson7cb85fc2020-02-18 15:40:10 -08006582 break;
Jing Liu820a6ee2022-01-05 04:35:21 -08006583 case MSR_IA32_XFD:
Jing Liu548e8362022-01-05 04:35:24 -08006584 case MSR_IA32_XFD_ERR:
Jing Liu820a6ee2022-01-05 04:35:21 -08006585 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
6586 continue;
6587 break;
Paolo Bonzini93c4adc2014-03-05 23:19:52 +01006588 default:
6589 break;
6590 }
6591
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006592 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
Carsten Ottebbd9b642007-10-30 18:44:21 +01006593 }
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02006594
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006595 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
Jason Baronb36464772021-01-14 22:27:56 -05006596 if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
Tom Lendackybc226f02018-05-10 22:06:39 +02006597 continue;
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02006598
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006599 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
Paolo Bonzini62ef68b2015-05-05 12:08:55 +02006600 }
Tom Lendacky801e4592018-02-21 13:39:51 -06006601
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006602 for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
Tom Lendacky801e4592018-02-21 13:39:51 -06006603 struct kvm_msr_entry msr;
6604
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006605 msr.index = msr_based_features_all[i];
Wanpeng Li66421c12018-02-28 14:03:30 +08006606 if (kvm_get_msr_feature(&msr))
Tom Lendacky801e4592018-02-21 13:39:51 -06006607 continue;
6608
Chenyi Qiang7a5ee6e2019-11-06 14:35:20 +08006609 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
Tom Lendacky801e4592018-02-21 13:39:51 -06006610 }
Carsten Ottebbd9b642007-10-30 18:44:21 +01006611}
6612
6613static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
6614 const void *v)
6615{
Avi Kivity70252a12010-01-19 12:51:22 +02006616 int handled = 0;
6617 int n;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006618
Avi Kivity70252a12010-01-19 12:51:22 +02006619 do {
6620 n = min(len, 8);
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01006621 if (!(lapic_in_kernel(vcpu) &&
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00006622 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
6623 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
Avi Kivity70252a12010-01-19 12:51:22 +02006624 break;
6625 handled += n;
6626 addr += n;
6627 len -= n;
6628 v += n;
6629 } while (len);
6630
6631 return handled;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006632}
6633
6634static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
6635{
Avi Kivity70252a12010-01-19 12:51:22 +02006636 int handled = 0;
6637 int n;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006638
Avi Kivity70252a12010-01-19 12:51:22 +02006639 do {
6640 n = min(len, 8);
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01006641 if (!(lapic_in_kernel(vcpu) &&
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00006642 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
6643 addr, n, v))
6644 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
Avi Kivity70252a12010-01-19 12:51:22 +02006645 break;
Wanpeng Lie39d200f2017-12-14 17:40:50 -08006646 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
Avi Kivity70252a12010-01-19 12:51:22 +02006647 handled += n;
6648 addr += n;
6649 len -= n;
6650 v += n;
6651 } while (len);
6652
6653 return handled;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006654}
6655
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02006656static void kvm_set_segment(struct kvm_vcpu *vcpu,
6657 struct kvm_segment *var, int seg)
6658{
Jason Baronb36464772021-01-14 22:27:56 -05006659 static_call(kvm_x86_set_segment)(vcpu, var, seg);
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02006660}
6661
6662void kvm_get_segment(struct kvm_vcpu *vcpu,
6663 struct kvm_segment *var, int seg)
6664{
Jason Baronb36464772021-01-14 22:27:56 -05006665 static_call(kvm_x86_get_segment)(vcpu, var, seg);
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02006666}
6667
Paolo Bonzini54987b72014-09-02 13:23:06 +02006668gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
6669 struct x86_exception *exception)
Joerg Roedel02f59dc2010-09-10 17:30:54 +02006670{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006671 struct kvm_mmu *mmu = vcpu->arch.mmu;
Joerg Roedel02f59dc2010-09-10 17:30:54 +02006672 gpa_t t_gpa;
Joerg Roedel02f59dc2010-09-10 17:30:54 +02006673
6674 BUG_ON(!mmu_is_nested(vcpu));
6675
6676 /* NPT walks are always user-walks */
6677 access |= PFERR_USER_MASK;
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006678 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
Joerg Roedel02f59dc2010-09-10 17:30:54 +02006679
6680 return t_gpa;
6681}
6682
Avi Kivityab9ae312010-11-22 17:53:26 +02006683gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
6684 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006685{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006686 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6687
Jason Baronb36464772021-01-14 22:27:56 -05006688 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006689 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006690}
Sean Christopherson54f958c2021-04-12 16:21:33 +12006691EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
Gleb Natapov1871c602010-02-10 14:21:32 +02006692
Avi Kivityab9ae312010-11-22 17:53:26 +02006693 gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
6694 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006695{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006696 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6697
Jason Baronb36464772021-01-14 22:27:56 -05006698 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
Gleb Natapov1871c602010-02-10 14:21:32 +02006699 access |= PFERR_FETCH_MASK;
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006700 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006701}
6702
Avi Kivityab9ae312010-11-22 17:53:26 +02006703gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
6704 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006705{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006706 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6707
Jason Baronb36464772021-01-14 22:27:56 -05006708 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
Gleb Natapov1871c602010-02-10 14:21:32 +02006709 access |= PFERR_WRITE_MASK;
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006710 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006711}
Sean Christopherson54f958c2021-04-12 16:21:33 +12006712EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
Gleb Natapov1871c602010-02-10 14:21:32 +02006713
6714/* uses this to access any guest's mapped memory without checking CPL */
Avi Kivityab9ae312010-11-22 17:53:26 +02006715gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
6716 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006717{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006718 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
6719
6720 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006721}
6722
6723static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6724 struct kvm_vcpu *vcpu, u32 access,
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006725 struct x86_exception *exception)
Carsten Ottebbd9b642007-10-30 18:44:21 +01006726{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006727 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006728 void *data = val;
Marcelo Tosatti10589a42007-12-20 19:18:22 -05006729 int r = X86EMUL_CONTINUE;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006730
6731 while (bytes) {
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006732 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
Carsten Ottebbd9b642007-10-30 18:44:21 +01006733 unsigned offset = addr & (PAGE_SIZE-1);
Izik Eidus77c20022008-12-29 01:42:19 +02006734 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
Carsten Ottebbd9b642007-10-30 18:44:21 +01006735 int ret;
6736
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006737 if (gpa == UNMAPPED_GVA)
Avi Kivityab9ae312010-11-22 17:53:26 +02006738 return X86EMUL_PROPAGATE_FAULT;
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02006739 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
6740 offset, toread);
Marcelo Tosatti10589a42007-12-20 19:18:22 -05006741 if (ret < 0) {
Gleb Natapovc3cd7ff2010-04-28 19:15:35 +03006742 r = X86EMUL_IO_NEEDED;
Marcelo Tosatti10589a42007-12-20 19:18:22 -05006743 goto out;
6744 }
Carsten Ottebbd9b642007-10-30 18:44:21 +01006745
Izik Eidus77c20022008-12-29 01:42:19 +02006746 bytes -= toread;
6747 data += toread;
6748 addr += toread;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006749 }
Marcelo Tosatti10589a42007-12-20 19:18:22 -05006750out:
Marcelo Tosatti10589a42007-12-20 19:18:22 -05006751 return r;
Carsten Ottebbd9b642007-10-30 18:44:21 +01006752}
Izik Eidus77c20022008-12-29 01:42:19 +02006753
Gleb Natapov1871c602010-02-10 14:21:32 +02006754/* used for instruction fetching */
Avi Kivity0f65dd72011-04-20 13:37:53 +03006755static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
6756 gva_t addr, void *val, unsigned int bytes,
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006757 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006758{
Avi Kivity0f65dd72011-04-20 13:37:53 +03006759 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006760 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Jason Baronb36464772021-01-14 22:27:56 -05006761 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
Paolo Bonzini44583cb2014-05-13 14:02:13 +02006762 unsigned offset;
6763 int ret;
Avi Kivity0f65dd72011-04-20 13:37:53 +03006764
Paolo Bonzini44583cb2014-05-13 14:02:13 +02006765 /* Inline kvm_read_guest_virt_helper for speed. */
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006766 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
6767 exception);
Paolo Bonzini44583cb2014-05-13 14:02:13 +02006768 if (unlikely(gpa == UNMAPPED_GVA))
6769 return X86EMUL_PROPAGATE_FAULT;
6770
6771 offset = addr & (PAGE_SIZE-1);
6772 if (WARN_ON(offset + bytes > PAGE_SIZE))
6773 bytes = (unsigned)PAGE_SIZE - offset;
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02006774 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
6775 offset, bytes);
Paolo Bonzini44583cb2014-05-13 14:02:13 +02006776 if (unlikely(ret < 0))
6777 return X86EMUL_IO_NEEDED;
6778
6779 return X86EMUL_CONTINUE;
Gleb Natapov1871c602010-02-10 14:21:32 +02006780}
6781
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006782int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
Avi Kivity0f65dd72011-04-20 13:37:53 +03006783 gva_t addr, void *val, unsigned int bytes,
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006784 struct x86_exception *exception)
Gleb Natapov1871c602010-02-10 14:21:32 +02006785{
Jason Baronb36464772021-01-14 22:27:56 -05006786 u32 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
Avi Kivity0f65dd72011-04-20 13:37:53 +03006787
Paolo Bonzini353c0952019-01-29 18:41:16 +01006788 /*
6789 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
6790 * is returned, but our callers are not ready for that and they blindly
6791 * call kvm_inject_page_fault. Ensure that they at least do not leak
6792 * uninitialized kernel stack memory into cr2 and error code.
6793 */
6794 memset(exception, 0, sizeof(*exception));
Gleb Natapov1871c602010-02-10 14:21:32 +02006795 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006796 exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006797}
Nadav Har'El064aea72011-05-25 23:04:56 +03006798EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
Gleb Natapov1871c602010-02-10 14:21:32 +02006799
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006800static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
6801 gva_t addr, void *val, unsigned int bytes,
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006802 struct x86_exception *exception, bool system)
Gleb Natapov1871c602010-02-10 14:21:32 +02006803{
Avi Kivity0f65dd72011-04-20 13:37:53 +03006804 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006805 u32 access = 0;
6806
Jason Baronb36464772021-01-14 22:27:56 -05006807 if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006808 access |= PFERR_USER_MASK;
6809
6810 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
Gleb Natapov1871c602010-02-10 14:21:32 +02006811}
6812
Radim Krčmář7a036a62015-10-30 16:36:24 +01006813static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
6814 unsigned long addr, void *val, unsigned int bytes)
6815{
6816 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6817 int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
6818
6819 return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
6820}
6821
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006822static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
6823 struct kvm_vcpu *vcpu, u32 access,
6824 struct x86_exception *exception)
Izik Eidus77c20022008-12-29 01:42:19 +02006825{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006826 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Izik Eidus77c20022008-12-29 01:42:19 +02006827 void *data = val;
6828 int r = X86EMUL_CONTINUE;
6829
6830 while (bytes) {
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006831 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
Izik Eidus77c20022008-12-29 01:42:19 +02006832 unsigned offset = addr & (PAGE_SIZE-1);
6833 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
6834 int ret;
6835
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006836 if (gpa == UNMAPPED_GVA)
Avi Kivityab9ae312010-11-22 17:53:26 +02006837 return X86EMUL_PROPAGATE_FAULT;
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02006838 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
Izik Eidus77c20022008-12-29 01:42:19 +02006839 if (ret < 0) {
Gleb Natapovc3cd7ff2010-04-28 19:15:35 +03006840 r = X86EMUL_IO_NEEDED;
Izik Eidus77c20022008-12-29 01:42:19 +02006841 goto out;
6842 }
6843
6844 bytes -= towrite;
6845 data += towrite;
6846 addr += towrite;
6847 }
6848out:
6849 return r;
6850}
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006851
6852static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006853 unsigned int bytes, struct x86_exception *exception,
6854 bool system)
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006855{
6856 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006857 u32 access = PFERR_WRITE_MASK;
6858
Jason Baronb36464772021-01-14 22:27:56 -05006859 if (!system && static_call(kvm_x86_get_cpl)(vcpu) == 3)
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006860 access |= PFERR_USER_MASK;
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006861
6862 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006863 access, exception);
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006864}
6865
6866int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
6867 unsigned int bytes, struct x86_exception *exception)
6868{
Paolo Bonzinic595cee2018-07-02 13:07:14 +02006869 /* kvm_write_guest_virt_system can pull in tons of pages. */
6870 vcpu->arch.l1tf_flush_l1d = true;
6871
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02006872 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
6873 PFERR_WRITE_MASK, exception);
6874}
Nadav Har'El6a4d7552011-05-25 23:08:00 +03006875EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
Izik Eidus77c20022008-12-29 01:42:19 +02006876
Sean Christopherson4d31d9e2022-01-20 01:07:15 +00006877static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
6878 void *insn, int insn_len)
6879{
6880 return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
6881 insn, insn_len);
6882}
6883
Wanpeng Li082d06e2018-04-03 16:28:48 -07006884int handle_ud(struct kvm_vcpu *vcpu)
6885{
Masami Hiramatsub3dc0692019-09-06 22:13:59 +09006886 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
Wanpeng Li6c86eed2018-04-03 16:28:49 -07006887 int emul_type = EMULTYPE_TRAP_UD;
Wanpeng Li6c86eed2018-04-03 16:28:49 -07006888 char sig[5]; /* ud2; .ascii "kvm" */
6889 struct x86_exception e;
Wanpeng Li082d06e2018-04-03 16:28:48 -07006890
Sean Christopherson4d31d9e2022-01-20 01:07:15 +00006891 if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
Sean Christopherson09e3e2a2020-09-15 16:27:02 -07006892 return 1;
6893
Wanpeng Li6c86eed2018-04-03 16:28:49 -07006894 if (force_emulation_prefix &&
Paolo Bonzini3c9fa242018-06-06 17:38:09 +02006895 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
6896 sig, sizeof(sig), &e) == 0 &&
Masami Hiramatsub3dc0692019-09-06 22:13:59 +09006897 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
Wanpeng Li6c86eed2018-04-03 16:28:49 -07006898 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
Sean Christophersonb4000602019-08-27 14:40:32 -07006899 emul_type = EMULTYPE_TRAP_UD_FORCED;
Wanpeng Li6c86eed2018-04-03 16:28:49 -07006900 }
6901
Sean Christopherson60fc3d02019-08-27 14:40:38 -07006902 return kvm_emulate_instruction(vcpu, emul_type);
Wanpeng Li082d06e2018-04-03 16:28:48 -07006903}
6904EXPORT_SYMBOL_GPL(handle_ud);
6905
Tom Lendacky0f89b202016-12-14 14:59:23 -05006906static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6907 gpa_t gpa, bool write)
6908{
6909 /* For APIC access vmexit */
6910 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6911 return 1;
6912
6913 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
6914 trace_vcpu_match_mmio(gva, gpa, write, true);
6915 return 1;
6916 }
6917
6918 return 0;
6919}
6920
Xiao Guangrongaf7cc7d2011-07-12 03:22:46 +08006921static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
6922 gpa_t *gpa, struct x86_exception *exception,
6923 bool write)
6924{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006925 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Jason Baronb36464772021-01-14 22:27:56 -05006926 u32 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
Avi Kivity97d64b72012-09-12 14:52:00 +03006927 | (write ? PFERR_WRITE_MASK : 0);
Xiao Guangrongaf7cc7d2011-07-12 03:22:46 +08006928
Huaitong Hanbe94f6b2016-03-22 16:51:20 +08006929 /*
6930 * currently PKRU is only applied to ept enabled guest so
6931 * there is no pkey in EPT page table for L1 guest or EPT
6932 * shadow page table for L2 guest.
6933 */
Sean Christopherson908b7d42021-07-13 09:33:04 -07006934 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
6935 !permission_fault(vcpu, vcpu->arch.walk_mmu,
6936 vcpu->arch.mmio_access, 0, access))) {
Xiao Guangrongbebb1062011-07-12 03:23:20 +08006937 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
6938 (gva & (PAGE_SIZE - 1));
Xiao Guangrong4f022642011-07-12 03:34:24 +08006939 trace_vcpu_match_mmio(gva, *gpa, write, false);
Xiao Guangrongbebb1062011-07-12 03:23:20 +08006940 return 1;
6941 }
6942
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +08006943 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
Xiao Guangrongaf7cc7d2011-07-12 03:22:46 +08006944
6945 if (*gpa == UNMAPPED_GVA)
6946 return -1;
6947
Tom Lendacky0f89b202016-12-14 14:59:23 -05006948 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
Xiao Guangrongaf7cc7d2011-07-12 03:22:46 +08006949}
6950
Marcelo Tosatti3200f402008-03-29 20:17:59 -03006951int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
Avi Kivitybcc55cb2010-11-22 17:53:22 +02006952 const void *val, int bytes)
Avi Kivity9f811282008-03-02 14:06:05 +02006953{
6954 int ret;
6955
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02006956 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
Avi Kivity9f811282008-03-02 14:06:05 +02006957 if (ret < 0)
6958 return 0;
Xiao Guangrong0eb05bf2016-02-24 17:51:13 +08006959 kvm_page_track_write(vcpu, gpa, val, bytes);
Avi Kivity9f811282008-03-02 14:06:05 +02006960 return 1;
6961}
6962
Xiao Guangrong77d197b2011-07-13 14:31:50 +08006963struct read_write_emulator_ops {
6964 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
6965 int bytes);
6966 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
6967 void *val, int bytes);
6968 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6969 int bytes, void *val);
6970 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
6971 void *val, int bytes);
6972 bool write;
6973};
6974
6975static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
6976{
6977 if (vcpu->mmio_read_completed) {
Xiao Guangrong77d197b2011-07-13 14:31:50 +08006978 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
Wanpeng Lie39d200f2017-12-14 17:40:50 -08006979 vcpu->mmio_fragments[0].gpa, val);
Xiao Guangrong77d197b2011-07-13 14:31:50 +08006980 vcpu->mmio_read_completed = 0;
6981 return 1;
6982 }
6983
6984 return 0;
6985}
6986
6987static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6988 void *val, int bytes)
6989{
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02006990 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
Xiao Guangrong77d197b2011-07-13 14:31:50 +08006991}
6992
6993static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
6994 void *val, int bytes)
6995{
6996 return emulator_write_phys(vcpu, gpa, val, bytes);
6997}
6998
6999static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7000{
Wanpeng Lie39d200f2017-12-14 17:40:50 -08007001 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
Xiao Guangrong77d197b2011-07-13 14:31:50 +08007002 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7003}
7004
7005static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7006 void *val, int bytes)
7007{
Wanpeng Lie39d200f2017-12-14 17:40:50 -08007008 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
Xiao Guangrong77d197b2011-07-13 14:31:50 +08007009 return X86EMUL_IO_NEEDED;
7010}
7011
7012static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7013 void *val, int bytes)
7014{
Avi Kivityf78146b2012-04-18 19:22:47 +03007015 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7016
Xiao Guangrong87da7e62012-10-24 14:07:59 +08007017 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
Xiao Guangrong77d197b2011-07-13 14:31:50 +08007018 return X86EMUL_CONTINUE;
7019}
7020
Mathias Krause0fbe9b02012-08-30 01:30:17 +02007021static const struct read_write_emulator_ops read_emultor = {
Xiao Guangrong77d197b2011-07-13 14:31:50 +08007022 .read_write_prepare = read_prepare,
7023 .read_write_emulate = read_emulate,
7024 .read_write_mmio = vcpu_mmio_read,
7025 .read_write_exit_mmio = read_exit_mmio,
7026};
7027
Mathias Krause0fbe9b02012-08-30 01:30:17 +02007028static const struct read_write_emulator_ops write_emultor = {
Xiao Guangrong77d197b2011-07-13 14:31:50 +08007029 .read_write_emulate = write_emulate,
7030 .read_write_mmio = write_mmio,
7031 .read_write_exit_mmio = write_exit_mmio,
7032 .write = true,
7033};
7034
Xiao Guangrong22388a32011-07-13 14:32:31 +08007035static int emulator_read_write_onepage(unsigned long addr, void *val,
7036 unsigned int bytes,
7037 struct x86_exception *exception,
7038 struct kvm_vcpu *vcpu,
Mathias Krause0fbe9b02012-08-30 01:30:17 +02007039 const struct read_write_emulator_ops *ops)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007040{
Xiao Guangrongaf7cc7d2011-07-12 03:22:46 +08007041 gpa_t gpa;
7042 int handled, ret;
Xiao Guangrong22388a32011-07-13 14:32:31 +08007043 bool write = ops->write;
Avi Kivityf78146b2012-04-18 19:22:47 +03007044 struct kvm_mmio_fragment *frag;
Sean Christophersonc9b8b072020-02-18 15:29:48 -08007045 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Tom Lendacky0f89b202016-12-14 14:59:23 -05007046
7047 /*
7048 * If the exit was due to a NPF we may already have a GPA.
7049 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7050 * Note, this cannot be used on string operations since string
7051 * operation using rep will only have the initial GPA from the NPF
7052 * occurred.
7053 */
Sean Christopherson744e6992020-02-18 15:03:09 -08007054 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7055 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7056 gpa = ctxt->gpa_val;
Brijesh Singh618232e2017-08-17 18:36:57 +02007057 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7058 } else {
7059 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7060 if (ret < 0)
7061 return X86EMUL_PROPAGATE_FAULT;
Tom Lendacky0f89b202016-12-14 14:59:23 -05007062 }
Xiao Guangrong22388a32011-07-13 14:32:31 +08007063
Brijesh Singh618232e2017-08-17 18:36:57 +02007064 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
Carsten Ottebbd9b642007-10-30 18:44:21 +01007065 return X86EMUL_CONTINUE;
7066
Carsten Ottebbd9b642007-10-30 18:44:21 +01007067 /*
7068 * Is this MMIO handled locally?
7069 */
Xiao Guangrong22388a32011-07-13 14:32:31 +08007070 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
Avi Kivity70252a12010-01-19 12:51:22 +02007071 if (handled == bytes)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007072 return X86EMUL_CONTINUE;
Carsten Ottebbd9b642007-10-30 18:44:21 +01007073
Avi Kivity70252a12010-01-19 12:51:22 +02007074 gpa += handled;
7075 bytes -= handled;
7076 val += handled;
7077
Xiao Guangrong87da7e62012-10-24 14:07:59 +08007078 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
7079 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
7080 frag->gpa = gpa;
7081 frag->data = val;
7082 frag->len = bytes;
Avi Kivityf78146b2012-04-18 19:22:47 +03007083 return X86EMUL_CONTINUE;
Carsten Ottebbd9b642007-10-30 18:44:21 +01007084}
7085
Xiubo Li52eb5a62015-03-13 17:39:45 +08007086static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
7087 unsigned long addr,
Xiao Guangrong22388a32011-07-13 14:32:31 +08007088 void *val, unsigned int bytes,
7089 struct x86_exception *exception,
Mathias Krause0fbe9b02012-08-30 01:30:17 +02007090 const struct read_write_emulator_ops *ops)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007091{
Avi Kivity0f65dd72011-04-20 13:37:53 +03007092 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Avi Kivityf78146b2012-04-18 19:22:47 +03007093 gpa_t gpa;
7094 int rc;
7095
7096 if (ops->read_write_prepare &&
7097 ops->read_write_prepare(vcpu, val, bytes))
7098 return X86EMUL_CONTINUE;
7099
7100 vcpu->mmio_nr_fragments = 0;
Avi Kivity0f65dd72011-04-20 13:37:53 +03007101
Carsten Ottebbd9b642007-10-30 18:44:21 +01007102 /* Crossing a page boundary? */
7103 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
Avi Kivityf78146b2012-04-18 19:22:47 +03007104 int now;
Carsten Ottebbd9b642007-10-30 18:44:21 +01007105
7106 now = -addr & ~PAGE_MASK;
Xiao Guangrong22388a32011-07-13 14:32:31 +08007107 rc = emulator_read_write_onepage(addr, val, now, exception,
7108 vcpu, ops);
7109
Carsten Ottebbd9b642007-10-30 18:44:21 +01007110 if (rc != X86EMUL_CONTINUE)
7111 return rc;
7112 addr += now;
Nadav Amitbac155312015-01-26 09:32:26 +02007113 if (ctxt->mode != X86EMUL_MODE_PROT64)
7114 addr = (u32)addr;
Carsten Ottebbd9b642007-10-30 18:44:21 +01007115 val += now;
7116 bytes -= now;
7117 }
Xiao Guangrong22388a32011-07-13 14:32:31 +08007118
Avi Kivityf78146b2012-04-18 19:22:47 +03007119 rc = emulator_read_write_onepage(addr, val, bytes, exception,
7120 vcpu, ops);
7121 if (rc != X86EMUL_CONTINUE)
7122 return rc;
7123
7124 if (!vcpu->mmio_nr_fragments)
7125 return rc;
7126
7127 gpa = vcpu->mmio_fragments[0].gpa;
7128
7129 vcpu->mmio_needed = 1;
7130 vcpu->mmio_cur_fragment = 0;
7131
Xiao Guangrong87da7e62012-10-24 14:07:59 +08007132 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
Avi Kivityf78146b2012-04-18 19:22:47 +03007133 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
7134 vcpu->run->exit_reason = KVM_EXIT_MMIO;
7135 vcpu->run->mmio.phys_addr = gpa;
7136
7137 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
Xiao Guangrong22388a32011-07-13 14:32:31 +08007138}
7139
7140static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
7141 unsigned long addr,
7142 void *val,
7143 unsigned int bytes,
7144 struct x86_exception *exception)
7145{
7146 return emulator_read_write(ctxt, addr, val, bytes,
7147 exception, &read_emultor);
7148}
7149
Xiubo Li52eb5a62015-03-13 17:39:45 +08007150static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
Xiao Guangrong22388a32011-07-13 14:32:31 +08007151 unsigned long addr,
7152 const void *val,
7153 unsigned int bytes,
7154 struct x86_exception *exception)
7155{
7156 return emulator_read_write(ctxt, addr, (void *)val, bytes,
7157 exception, &write_emultor);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007158}
Carsten Ottebbd9b642007-10-30 18:44:21 +01007159
Avi Kivitydaea3e72010-03-15 13:59:54 +02007160#define CMPXCHG_TYPE(t, ptr, old, new) \
7161 (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
7162
7163#ifdef CONFIG_X86_64
7164# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
7165#else
7166# define CMPXCHG64(ptr, old, new) \
Jan Kiszka9749a6c2010-03-20 10:14:13 +01007167 (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
Avi Kivitydaea3e72010-03-15 13:59:54 +02007168#endif
7169
Avi Kivity0f65dd72011-04-20 13:37:53 +03007170static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
7171 unsigned long addr,
Carsten Ottebbd9b642007-10-30 18:44:21 +01007172 const void *old,
7173 const void *new,
7174 unsigned int bytes,
Avi Kivity0f65dd72011-04-20 13:37:53 +03007175 struct x86_exception *exception)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007176{
KarimAllah Ahmed42e35f82019-01-31 21:24:39 +01007177 struct kvm_host_map map;
Avi Kivity0f65dd72011-04-20 13:37:53 +03007178 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Xiaoyao Li9de6fe32020-04-10 13:54:01 +02007179 u64 page_line_mask;
Avi Kivitydaea3e72010-03-15 13:59:54 +02007180 gpa_t gpa;
Avi Kivitydaea3e72010-03-15 13:59:54 +02007181 char *kaddr;
7182 bool exchanged;
7183
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007184 /* guests cmpxchg8b have to be emulated atomically */
Avi Kivitydaea3e72010-03-15 13:59:54 +02007185 if (bytes > 8 || (bytes & (bytes - 1)))
7186 goto emul_write;
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007187
Avi Kivitydaea3e72010-03-15 13:59:54 +02007188 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
Marcelo Tosatti10589a42007-12-20 19:18:22 -05007189
Avi Kivitydaea3e72010-03-15 13:59:54 +02007190 if (gpa == UNMAPPED_GVA ||
7191 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7192 goto emul_write;
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007193
Xiaoyao Li9de6fe32020-04-10 13:54:01 +02007194 /*
7195 * Emulate the atomic as a straight write to avoid #AC if SLD is
7196 * enabled in the host and the access splits a cache line.
7197 */
7198 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
7199 page_line_mask = ~(cache_line_size() - 1);
7200 else
7201 page_line_mask = PAGE_MASK;
7202
7203 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
Avi Kivitydaea3e72010-03-15 13:59:54 +02007204 goto emul_write;
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007205
KarimAllah Ahmed42e35f82019-01-31 21:24:39 +01007206 if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
Wei Yongjunc19b8bd2010-07-15 08:51:58 +08007207 goto emul_write;
Izik Eidus72dc67a2008-02-10 18:04:15 +02007208
KarimAllah Ahmed42e35f82019-01-31 21:24:39 +01007209 kaddr = map.hva + offset_in_page(gpa);
7210
Avi Kivitydaea3e72010-03-15 13:59:54 +02007211 switch (bytes) {
7212 case 1:
7213 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
7214 break;
7215 case 2:
7216 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
7217 break;
7218 case 4:
7219 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
7220 break;
7221 case 8:
7222 exchanged = CMPXCHG64(kaddr, old, new);
7223 break;
7224 default:
7225 BUG();
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007226 }
KarimAllah Ahmed42e35f82019-01-31 21:24:39 +01007227
7228 kvm_vcpu_unmap(vcpu, &map, true);
Avi Kivitydaea3e72010-03-15 13:59:54 +02007229
7230 if (!exchanged)
7231 return X86EMUL_CMPXCHG_FAILED;
7232
Xiao Guangrong0eb05bf2016-02-24 17:51:13 +08007233 kvm_page_track_write(vcpu, gpa, new, bytes);
Gleb Natapov8f6abd02010-04-13 10:21:56 +03007234
7235 return X86EMUL_CONTINUE;
Avi Kivity4a5f48f2010-03-15 13:59:55 +02007236
Marcelo Tosatti3200f402008-03-29 20:17:59 -03007237emul_write:
Avi Kivitydaea3e72010-03-15 13:59:54 +02007238 printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
Marcelo Tosatti2bacc552007-12-12 10:46:12 -05007239
Avi Kivity0f65dd72011-04-20 13:37:53 +03007240 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007241}
7242
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007243static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
7244{
Wanpeng Licbfc6c92017-05-19 02:46:56 -07007245 int r = 0, i;
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007246
Wanpeng Licbfc6c92017-05-19 02:46:56 -07007247 for (i = 0; i < vcpu->arch.pio.count; i++) {
7248 if (vcpu->arch.pio.in)
7249 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
7250 vcpu->arch.pio.size, pd);
7251 else
7252 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
7253 vcpu->arch.pio.port, vcpu->arch.pio.size,
7254 pd);
7255 if (r)
7256 break;
7257 pd += vcpu->arch.pio.size;
7258 }
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007259 return r;
7260}
7261
Xiao Guangrong6f6fbe92011-09-22 16:55:10 +08007262static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007263 unsigned short port,
Xiao Guangrong6f6fbe92011-09-22 16:55:10 +08007264 unsigned int count, bool in)
7265{
Xiao Guangrong6f6fbe92011-09-22 16:55:10 +08007266 vcpu->arch.pio.port = port;
7267 vcpu->arch.pio.in = in;
7268 vcpu->arch.pio.count = count;
7269 vcpu->arch.pio.size = size;
7270
Paolo Bonzini0d33b1b2021-10-13 12:29:42 -04007271 if (!kernel_pio(vcpu, vcpu->arch.pio_data))
Xiao Guangrong6f6fbe92011-09-22 16:55:10 +08007272 return 1;
Xiao Guangrong6f6fbe92011-09-22 16:55:10 +08007273
7274 vcpu->run->exit_reason = KVM_EXIT_IO;
7275 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
7276 vcpu->run->io.size = size;
7277 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
7278 vcpu->run->io.count = count;
7279 vcpu->run->io.port = port;
7280
7281 return 0;
7282}
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007283
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007284static int __emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7285 unsigned short port, unsigned int count)
7286{
7287 WARN_ON(vcpu->arch.pio.count);
7288 memset(vcpu->arch.pio_data, 0, size * count);
7289 return emulator_pio_in_out(vcpu, size, port, count, true);
7290}
7291
Paolo Bonzini6b5efc92021-10-12 12:35:20 -04007292static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007293{
Paolo Bonzini6b5efc92021-10-12 12:35:20 -04007294 int size = vcpu->arch.pio.size;
7295 unsigned count = vcpu->arch.pio.count;
7296 memcpy(val, vcpu->arch.pio_data, size * count);
7297 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007298 vcpu->arch.pio.count = 0;
7299}
7300
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08007301static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
7302 unsigned short port, void *val, unsigned int count)
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007303{
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007304 if (vcpu->arch.pio.count) {
Sean Christophersond07898e2021-10-25 13:13:10 -07007305 /*
7306 * Complete a previous iteration that required userspace I/O.
7307 * Note, @count isn't guaranteed to match pio.count as userspace
7308 * can modify ECX before rerunning the vCPU. Ignore any such
7309 * shenanigans as KVM doesn't support modifying the rep count,
7310 * and the emulator ensures @count doesn't overflow the buffer.
7311 */
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007312 } else {
7313 int r = __emulator_pio_in(vcpu, size, port, count);
7314 if (!r)
7315 return r;
Avi Kivityca1d4a92011-04-20 13:37:53 +03007316
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007317 /* Results already available, fall through. */
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007318 }
7319
Paolo Bonzini6b5efc92021-10-12 12:35:20 -04007320 complete_emulator_pio_in(vcpu, val);
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007321 return 1;
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007322}
7323
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08007324static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
7325 int size, unsigned short port, void *val,
7326 unsigned int count)
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007327{
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08007328 return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
Avi Kivityca1d4a92011-04-20 13:37:53 +03007329
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08007330}
7331
7332static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
7333 unsigned short port, const void *val,
7334 unsigned int count)
7335{
Paolo Bonzini0d33b1b2021-10-13 12:29:42 -04007336 int ret;
7337
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007338 memcpy(vcpu->arch.pio_data, val, size * count);
Ulrich Obergfell11719032014-05-02 17:57:47 +02007339 trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
Paolo Bonzini3b27de22021-10-13 12:32:02 -04007340 ret = emulator_pio_in_out(vcpu, size, port, count, false);
Paolo Bonzini0d33b1b2021-10-13 12:29:42 -04007341 if (ret)
7342 vcpu->arch.pio.count = 0;
7343
7344 return ret;
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007345}
7346
Carsten Ottebbd9b642007-10-30 18:44:21 +01007347static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
7348 int size, unsigned short port,
7349 const void *val, unsigned int count)
7350{
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08007351 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007352}
7353
7354static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
7355{
Jason Baronb36464772021-01-14 22:27:56 -05007356 return static_call(kvm_x86_get_segment_base)(vcpu, seg);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007357}
7358
Avi Kivity3cb16fe2011-04-20 15:38:44 +03007359static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007360{
Avi Kivity3cb16fe2011-04-20 15:38:44 +03007361 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007362}
7363
Jiang Biaoae6a2372016-11-07 08:54:51 +08007364static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
Sheng Yangf5f48ee2010-06-30 12:25:15 +08007365{
7366 if (!need_emulate_wbinvd(vcpu))
7367 return X86EMUL_CONTINUE;
7368
Jason Baronb36464772021-01-14 22:27:56 -05007369 if (static_call(kvm_x86_has_wbinvd_exit)()) {
Jan Kiszka2eec7342010-11-01 14:01:29 +01007370 int cpu = get_cpu();
7371
7372 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
Wanpeng Lic2162e12021-03-12 10:45:51 +08007373 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
Sheng Yangf5f48ee2010-06-30 12:25:15 +08007374 wbinvd_ipi, NULL, 1);
Jan Kiszka2eec7342010-11-01 14:01:29 +01007375 put_cpu();
Sheng Yangf5f48ee2010-06-30 12:25:15 +08007376 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
Jan Kiszka2eec7342010-11-01 14:01:29 +01007377 } else
7378 wbinvd();
Sheng Yangf5f48ee2010-06-30 12:25:15 +08007379 return X86EMUL_CONTINUE;
7380}
Joel Schopp5cb56052015-03-02 13:43:31 -06007381
7382int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
7383{
Kyle Huey6affcbe2016-11-29 12:40:40 -08007384 kvm_emulate_wbinvd_noskip(vcpu);
7385 return kvm_skip_emulated_instruction(vcpu);
Joel Schopp5cb56052015-03-02 13:43:31 -06007386}
Sheng Yangf5f48ee2010-06-30 12:25:15 +08007387EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
7388
Joel Schopp5cb56052015-03-02 13:43:31 -06007389
7390
Avi Kivitybcaf5cc2011-04-20 15:53:23 +03007391static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
7392{
Joel Schopp5cb56052015-03-02 13:43:31 -06007393 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
Avi Kivitybcaf5cc2011-04-20 15:53:23 +03007394}
7395
Paolo Bonzini29d6ca42021-02-03 03:42:41 -05007396static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
7397 unsigned long *dest)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007398{
Paolo Bonzini29d6ca42021-02-03 03:42:41 -05007399 kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007400}
7401
Xiubo Li52eb5a62015-03-13 17:39:45 +08007402static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
7403 unsigned long value)
Carsten Ottebbd9b642007-10-30 18:44:21 +01007404{
Gleb Natapov338dbc92010-04-28 19:15:32 +03007405
Paolo Bonzini996ff542020-12-14 07:49:54 -05007406 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
Carsten Ottebbd9b642007-10-30 18:44:21 +01007407}
7408
Gleb Natapov52a46612010-03-18 15:20:03 +02007409static u64 mk_cr_64(u64 curr_cr, u32 new_val)
7410{
7411 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
7412}
7413
Avi Kivity717746e2011-04-20 13:37:53 +03007414static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
Gleb Natapov52a46612010-03-18 15:20:03 +02007415{
Avi Kivity717746e2011-04-20 13:37:53 +03007416 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Gleb Natapov52a46612010-03-18 15:20:03 +02007417 unsigned long value;
7418
7419 switch (cr) {
7420 case 0:
7421 value = kvm_read_cr0(vcpu);
7422 break;
7423 case 2:
7424 value = vcpu->arch.cr2;
7425 break;
7426 case 3:
Avi Kivity9f8fe502010-12-05 17:30:00 +02007427 value = kvm_read_cr3(vcpu);
Gleb Natapov52a46612010-03-18 15:20:03 +02007428 break;
7429 case 4:
7430 value = kvm_read_cr4(vcpu);
7431 break;
7432 case 8:
7433 value = kvm_get_cr8(vcpu);
7434 break;
7435 default:
Christoffer Dalla737f252012-06-03 21:17:48 +03007436 kvm_err("%s: unexpected cr %u\n", __func__, cr);
Gleb Natapov52a46612010-03-18 15:20:03 +02007437 return 0;
7438 }
7439
7440 return value;
7441}
7442
Avi Kivity717746e2011-04-20 13:37:53 +03007443static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
Gleb Natapov52a46612010-03-18 15:20:03 +02007444{
Avi Kivity717746e2011-04-20 13:37:53 +03007445 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Gleb Natapov0f122442010-04-28 19:15:31 +03007446 int res = 0;
7447
Gleb Natapov52a46612010-03-18 15:20:03 +02007448 switch (cr) {
7449 case 0:
Avi Kivity49a9b072010-06-10 17:02:14 +03007450 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
Gleb Natapov52a46612010-03-18 15:20:03 +02007451 break;
7452 case 2:
7453 vcpu->arch.cr2 = val;
7454 break;
7455 case 3:
Avi Kivity23902182010-06-10 17:02:16 +03007456 res = kvm_set_cr3(vcpu, val);
Gleb Natapov52a46612010-03-18 15:20:03 +02007457 break;
7458 case 4:
Avi Kivitya83b29c2010-06-10 17:02:15 +03007459 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
Gleb Natapov52a46612010-03-18 15:20:03 +02007460 break;
7461 case 8:
Andre Przywaraeea1cff2010-12-21 11:12:00 +01007462 res = kvm_set_cr8(vcpu, val);
Gleb Natapov52a46612010-03-18 15:20:03 +02007463 break;
7464 default:
Christoffer Dalla737f252012-06-03 21:17:48 +03007465 kvm_err("%s: unexpected cr %u\n", __func__, cr);
Gleb Natapov0f122442010-04-28 19:15:31 +03007466 res = -1;
Gleb Natapov52a46612010-03-18 15:20:03 +02007467 }
Gleb Natapov0f122442010-04-28 19:15:31 +03007468
7469 return res;
Gleb Natapov52a46612010-03-18 15:20:03 +02007470}
7471
Avi Kivity717746e2011-04-20 13:37:53 +03007472static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
Gleb Natapov9c537242010-03-18 15:20:05 +02007473{
Jason Baronb36464772021-01-14 22:27:56 -05007474 return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
Gleb Natapov9c537242010-03-18 15:20:05 +02007475}
7476
Avi Kivity4bff1e862011-04-20 13:37:53 +03007477static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007478{
Jason Baronb36464772021-01-14 22:27:56 -05007479 static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007480}
7481
Avi Kivity4bff1e862011-04-20 13:37:53 +03007482static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
Mohammed Gamal160ce1f2010-08-04 05:44:24 +03007483{
Jason Baronb36464772021-01-14 22:27:56 -05007484 static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
Mohammed Gamal160ce1f2010-08-04 05:44:24 +03007485}
7486
Avi Kivity1ac9d0c2011-04-20 15:12:00 +03007487static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7488{
Jason Baronb36464772021-01-14 22:27:56 -05007489 static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
Avi Kivity1ac9d0c2011-04-20 15:12:00 +03007490}
7491
7492static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
7493{
Jason Baronb36464772021-01-14 22:27:56 -05007494 static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
Avi Kivity1ac9d0c2011-04-20 15:12:00 +03007495}
7496
Avi Kivity4bff1e862011-04-20 13:37:53 +03007497static unsigned long emulator_get_cached_segment_base(
7498 struct x86_emulate_ctxt *ctxt, int seg)
Gleb Natapov5951c442010-04-28 19:15:29 +03007499{
Avi Kivity4bff1e862011-04-20 13:37:53 +03007500 return get_segment_base(emul_to_vcpu(ctxt), seg);
Gleb Natapov5951c442010-04-28 19:15:29 +03007501}
7502
Avi Kivity1aa36612011-04-27 13:20:30 +03007503static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
7504 struct desc_struct *desc, u32 *base3,
7505 int seg)
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007506{
7507 struct kvm_segment var;
7508
Avi Kivity4bff1e862011-04-20 13:37:53 +03007509 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
Avi Kivity1aa36612011-04-27 13:20:30 +03007510 *selector = var.selector;
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007511
Gleb Natapov378a8b02013-01-21 15:36:48 +02007512 if (var.unusable) {
7513 memset(desc, 0, sizeof(*desc));
Radim Krčmářf0367ee2017-05-18 19:37:30 +02007514 if (base3)
7515 *base3 = 0;
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007516 return false;
Gleb Natapov378a8b02013-01-21 15:36:48 +02007517 }
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007518
7519 if (var.g)
7520 var.limit >>= 12;
7521 set_desc_limit(desc, var.limit);
7522 set_desc_base(desc, (unsigned long)var.base);
Gleb Natapov5601d052011-03-07 14:55:06 +02007523#ifdef CONFIG_X86_64
7524 if (base3)
7525 *base3 = var.base >> 32;
7526#endif
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007527 desc->type = var.type;
7528 desc->s = var.s;
7529 desc->dpl = var.dpl;
7530 desc->p = var.present;
7531 desc->avl = var.avl;
7532 desc->l = var.l;
7533 desc->d = var.db;
7534 desc->g = var.g;
7535
7536 return true;
7537}
7538
Avi Kivity1aa36612011-04-27 13:20:30 +03007539static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
7540 struct desc_struct *desc, u32 base3,
7541 int seg)
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007542{
Avi Kivity4bff1e862011-04-20 13:37:53 +03007543 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007544 struct kvm_segment var;
7545
Avi Kivity1aa36612011-04-27 13:20:30 +03007546 var.selector = selector;
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007547 var.base = get_desc_base(desc);
Gleb Natapov5601d052011-03-07 14:55:06 +02007548#ifdef CONFIG_X86_64
7549 var.base |= ((u64)base3) << 32;
7550#endif
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007551 var.limit = get_desc_limit(desc);
7552 if (desc->g)
7553 var.limit = (var.limit << 12) | 0xfff;
7554 var.type = desc->type;
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007555 var.dpl = desc->dpl;
7556 var.db = desc->d;
7557 var.s = desc->s;
7558 var.l = desc->l;
7559 var.g = desc->g;
7560 var.avl = desc->avl;
7561 var.present = desc->p;
7562 var.unusable = !var.present;
7563 var.padding = 0;
7564
7565 kvm_set_segment(vcpu, &var, seg);
7566 return;
7567}
7568
Avi Kivity717746e2011-04-20 13:37:53 +03007569static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
7570 u32 msr_index, u64 *pdata)
7571{
Alexander Graf1ae09952020-09-25 16:34:16 +02007572 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7573 int r;
7574
7575 r = kvm_get_msr(vcpu, msr_index, pdata);
7576
Hou Wenlongd2f7d492021-11-02 17:15:31 +08007577 if (r && kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
7578 complete_emulated_rdmsr, r)) {
Alexander Graf1ae09952020-09-25 16:34:16 +02007579 /* Bounce to user space */
7580 return X86EMUL_IO_NEEDED;
7581 }
7582
7583 return r;
Avi Kivity717746e2011-04-20 13:37:53 +03007584}
7585
7586static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
7587 u32 msr_index, u64 data)
7588{
Alexander Graf1ae09952020-09-25 16:34:16 +02007589 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7590 int r;
7591
7592 r = kvm_set_msr(vcpu, msr_index, data);
7593
Hou Wenlongd2f7d492021-11-02 17:15:31 +08007594 if (r && kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
7595 complete_emulated_msr_access, r)) {
Alexander Graf1ae09952020-09-25 16:34:16 +02007596 /* Bounce to user space */
7597 return X86EMUL_IO_NEEDED;
7598 }
7599
7600 return r;
Avi Kivity717746e2011-04-20 13:37:53 +03007601}
7602
Paolo Bonzini64d60672015-05-07 11:36:11 +02007603static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
7604{
7605 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7606
7607 return vcpu->arch.smbase;
7608}
7609
7610static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
7611{
7612 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7613
7614 vcpu->arch.smbase = smbase;
7615}
7616
Nadav Amit67f4d422014-06-02 18:34:09 +03007617static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
7618 u32 pmc)
7619{
Jim Mattsone6cd31f2021-11-05 13:20:58 -07007620 if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
7621 return 0;
7622 return -EINVAL;
Nadav Amit67f4d422014-06-02 18:34:09 +03007623}
7624
Avi Kivity222d21a2011-11-10 14:57:30 +02007625static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
7626 u32 pmc, u64 *pdata)
7627{
Wei Huangc6702c92015-06-19 13:44:45 +02007628 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
Avi Kivity222d21a2011-11-10 14:57:30 +02007629}
7630
Avi Kivity6c3287f2011-04-20 15:43:05 +03007631static void emulator_halt(struct x86_emulate_ctxt *ctxt)
7632{
7633 emul_to_vcpu(ctxt)->arch.halt_request = 1;
7634}
7635
Avi Kivity29535382011-04-20 13:37:53 +03007636static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
Joerg Roedel8a76d7f2011-04-04 12:39:27 +02007637 struct x86_instruction_info *info,
Avi Kivityc4f035c2011-04-04 12:39:22 +02007638 enum x86_intercept_stage stage)
7639{
Jason Baronb36464772021-01-14 22:27:56 -05007640 return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
Sean Christopherson21f1b8f2020-02-18 15:29:42 -08007641 &ctxt->exception);
Avi Kivityc4f035c2011-04-04 12:39:22 +02007642}
7643
Yu Zhange911eb32017-08-24 20:27:52 +08007644static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
Sean Christophersonf91af512020-03-04 17:34:37 -08007645 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
7646 bool exact_only)
Stephan Bärwolfbdb42f52012-01-12 16:43:03 +01007647{
Sean Christophersonf91af512020-03-04 17:34:37 -08007648 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
Stephan Bärwolfbdb42f52012-01-12 16:43:03 +01007649}
7650
Sean Christopherson5ae78e92019-12-17 13:32:38 -08007651static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
7652{
7653 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
7654}
7655
7656static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
7657{
7658 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
7659}
7660
7661static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
7662{
7663 return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
7664}
7665
Avi Kivitydd856ef2012-08-27 23:46:17 +03007666static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
7667{
Sean Christopherson27b4a9c42021-04-21 19:21:28 -07007668 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
Avi Kivitydd856ef2012-08-27 23:46:17 +03007669}
7670
7671static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
7672{
Sean Christopherson27b4a9c42021-04-21 19:21:28 -07007673 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
Avi Kivitydd856ef2012-08-27 23:46:17 +03007674}
7675
Nadav Amit801806d2015-01-26 09:32:23 +02007676static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
7677{
Jason Baronb36464772021-01-14 22:27:56 -05007678 static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
Nadav Amit801806d2015-01-26 09:32:23 +02007679}
7680
Ladi Prosek6ed071f2017-04-25 16:42:44 +02007681static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
7682{
7683 return emul_to_vcpu(ctxt)->arch.hflags;
7684}
7685
Sean Christophersonedce4652021-06-09 11:56:13 -07007686static void emulator_exiting_smm(struct x86_emulate_ctxt *ctxt)
Ladi Prosek6ed071f2017-04-25 16:42:44 +02007687{
Sean Christopherson78fcb2c2021-06-09 11:56:11 -07007688 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7689
Sean Christophersondc872752021-06-09 11:56:15 -07007690 kvm_smm_changed(vcpu, false);
Ladi Prosek6ed071f2017-04-25 16:42:44 +02007691}
7692
Sean Christophersonecc513e2021-06-09 11:56:19 -07007693static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt,
Sean Christophersoned193212019-04-02 08:03:09 -07007694 const char *smstate)
Ladi Prosek0234bf82017-10-11 16:54:40 +02007695{
Sean Christophersonecc513e2021-06-09 11:56:19 -07007696 return static_call(kvm_x86_leave_smm)(emul_to_vcpu(ctxt), smstate);
Ladi Prosek0234bf82017-10-11 16:54:40 +02007697}
7698
Sean Christopherson25b17222021-06-09 11:56:12 -07007699static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
7700{
7701 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
7702}
7703
Vitaly Kuznetsov02d41602019-08-13 15:53:32 +02007704static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
7705{
7706 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
7707}
7708
Mathias Krause0225fb52012-08-30 01:30:16 +02007709static const struct x86_emulate_ops emulate_ops = {
Avi Kivitydd856ef2012-08-27 23:46:17 +03007710 .read_gpr = emulator_read_gpr,
7711 .write_gpr = emulator_write_gpr,
Paolo Bonzinice14e868a2018-06-06 17:37:49 +02007712 .read_std = emulator_read_std,
7713 .write_std = emulator_write_std,
Radim Krčmář7a036a62015-10-30 16:36:24 +01007714 .read_phys = kvm_read_guest_phys_system,
Gleb Natapov1871c602010-02-10 14:21:32 +02007715 .fetch = kvm_fetch_guest_virt,
Carsten Ottebbd9b642007-10-30 18:44:21 +01007716 .read_emulated = emulator_read_emulated,
7717 .write_emulated = emulator_write_emulated,
7718 .cmpxchg_emulated = emulator_cmpxchg_emulated,
Avi Kivity3cb16fe2011-04-20 15:38:44 +03007719 .invlpg = emulator_invlpg,
Gleb Natapovcf8f70b2010-03-18 15:20:23 +02007720 .pio_in_emulated = emulator_pio_in_emulated,
7721 .pio_out_emulated = emulator_pio_out_emulated,
Avi Kivity1aa36612011-04-27 13:20:30 +03007722 .get_segment = emulator_get_segment,
7723 .set_segment = emulator_set_segment,
Gleb Natapov5951c442010-04-28 19:15:29 +03007724 .get_cached_segment_base = emulator_get_cached_segment_base,
Gleb Natapov2dafc6c2010-03-18 15:20:16 +02007725 .get_gdt = emulator_get_gdt,
Mohammed Gamal160ce1f2010-08-04 05:44:24 +03007726 .get_idt = emulator_get_idt,
Avi Kivity1ac9d0c2011-04-20 15:12:00 +03007727 .set_gdt = emulator_set_gdt,
7728 .set_idt = emulator_set_idt,
Gleb Natapov52a46612010-03-18 15:20:03 +02007729 .get_cr = emulator_get_cr,
7730 .set_cr = emulator_set_cr,
Gleb Natapov9c537242010-03-18 15:20:05 +02007731 .cpl = emulator_get_cpl,
Gleb Natapov35aa5372010-04-28 19:15:27 +03007732 .get_dr = emulator_get_dr,
7733 .set_dr = emulator_set_dr,
Paolo Bonzini64d60672015-05-07 11:36:11 +02007734 .get_smbase = emulator_get_smbase,
7735 .set_smbase = emulator_set_smbase,
Avi Kivity717746e2011-04-20 13:37:53 +03007736 .set_msr = emulator_set_msr,
7737 .get_msr = emulator_get_msr,
Nadav Amit67f4d422014-06-02 18:34:09 +03007738 .check_pmc = emulator_check_pmc,
Avi Kivity222d21a2011-11-10 14:57:30 +02007739 .read_pmc = emulator_read_pmc,
Avi Kivity6c3287f2011-04-20 15:43:05 +03007740 .halt = emulator_halt,
Avi Kivitybcaf5cc2011-04-20 15:53:23 +03007741 .wbinvd = emulator_wbinvd,
Avi Kivityd6aa1002011-04-20 15:47:13 +03007742 .fix_hypercall = emulator_fix_hypercall,
Avi Kivityc4f035c2011-04-04 12:39:22 +02007743 .intercept = emulator_intercept,
Stephan Bärwolfbdb42f52012-01-12 16:43:03 +01007744 .get_cpuid = emulator_get_cpuid,
Sean Christopherson5ae78e92019-12-17 13:32:38 -08007745 .guest_has_long_mode = emulator_guest_has_long_mode,
7746 .guest_has_movbe = emulator_guest_has_movbe,
7747 .guest_has_fxsr = emulator_guest_has_fxsr,
Nadav Amit801806d2015-01-26 09:32:23 +02007748 .set_nmi_mask = emulator_set_nmi_mask,
Ladi Prosek6ed071f2017-04-25 16:42:44 +02007749 .get_hflags = emulator_get_hflags,
Sean Christophersonedce4652021-06-09 11:56:13 -07007750 .exiting_smm = emulator_exiting_smm,
Sean Christophersonecc513e2021-06-09 11:56:19 -07007751 .leave_smm = emulator_leave_smm,
Sean Christopherson25b17222021-06-09 11:56:12 -07007752 .triple_fault = emulator_triple_fault,
Vitaly Kuznetsov02d41602019-08-13 15:53:32 +02007753 .set_xcr = emulator_set_xcr,
Carsten Ottebbd9b642007-10-30 18:44:21 +01007754};
7755
Gleb Natapov95cb2292010-04-28 19:15:43 +03007756static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
7757{
Jason Baronb36464772021-01-14 22:27:56 -05007758 u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
Gleb Natapov95cb2292010-04-28 19:15:43 +03007759 /*
7760 * an sti; sti; sequence only disable interrupts for the first
7761 * instruction. So, if the last instruction, be it emulated or
7762 * not, left the system with the INT_STI flag enabled, it
7763 * means that the last instruction is an sti. We should not
7764 * leave the flag on in this case. The same goes for mov ss
7765 */
Paolo Bonzini37ccdcb2014-05-20 14:29:47 +02007766 if (int_shadow & mask)
7767 mask = 0;
Paolo Bonzini6addfc42014-03-27 11:29:28 +01007768 if (unlikely(int_shadow || mask)) {
Jason Baronb36464772021-01-14 22:27:56 -05007769 static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
Paolo Bonzini6addfc42014-03-27 11:29:28 +01007770 if (!mask)
7771 kvm_make_request(KVM_REQ_EVENT, vcpu);
7772 }
Gleb Natapov95cb2292010-04-28 19:15:43 +03007773}
7774
Paolo Bonzinief54bcf2014-09-04 19:46:15 +02007775static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
Gleb Natapov54b84862010-04-28 19:15:44 +03007776{
Sean Christophersonc9b8b072020-02-18 15:29:48 -08007777 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Avi Kivityda9cb572010-11-22 17:53:21 +02007778 if (ctxt->exception.vector == PF_VECTOR)
Sean Christopherson53b3d8e2020-03-20 14:28:01 -07007779 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
Paolo Bonzinief54bcf2014-09-04 19:46:15 +02007780
7781 if (ctxt->exception.error_code_valid)
Avi Kivityda9cb572010-11-22 17:53:21 +02007782 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
7783 ctxt->exception.error_code);
Gleb Natapov54b84862010-04-28 19:15:44 +03007784 else
Avi Kivityda9cb572010-11-22 17:53:21 +02007785 kvm_queue_exception(vcpu, ctxt->exception.vector);
Paolo Bonzinief54bcf2014-09-04 19:46:15 +02007786 return false;
Gleb Natapov54b84862010-04-28 19:15:44 +03007787}
7788
Sean Christophersonc9b8b072020-02-18 15:29:48 -08007789static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
7790{
7791 struct x86_emulate_ctxt *ctxt;
7792
7793 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
7794 if (!ctxt) {
7795 pr_err("kvm: failed to allocate vcpu's emulator\n");
7796 return NULL;
7797 }
7798
7799 ctxt->vcpu = vcpu;
7800 ctxt->ops = &emulate_ops;
7801 vcpu->arch.emulate_ctxt = ctxt;
7802
7803 return ctxt;
7804}
7805
Mohammed Gamal8ec47222010-08-16 00:47:01 +03007806static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
7807{
Sean Christophersonc9b8b072020-02-18 15:29:48 -08007808 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Mohammed Gamal8ec47222010-08-16 00:47:01 +03007809 int cs_db, cs_l;
7810
Jason Baronb36464772021-01-14 22:27:56 -05007811 static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
Mohammed Gamal8ec47222010-08-16 00:47:01 +03007812
Sean Christopherson744e6992020-02-18 15:03:09 -08007813 ctxt->gpa_available = false;
Takuya Yoshikawaadf52232011-05-25 11:06:16 +09007814 ctxt->eflags = kvm_get_rflags(vcpu);
Paolo Bonzinic8401dd2017-06-07 15:13:14 +02007815 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
7816
Takuya Yoshikawaadf52232011-05-25 11:06:16 +09007817 ctxt->eip = kvm_rip_read(vcpu);
7818 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
7819 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
Nadav Amit42bf5492014-04-18 07:11:34 +03007820 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
Takuya Yoshikawaadf52232011-05-25 11:06:16 +09007821 cs_db ? X86EMUL_MODE_PROT32 :
7822 X86EMUL_MODE_PROT16;
Paolo Bonzinia5845392015-04-01 18:18:53 +02007823 BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
Paolo Bonzini64d60672015-05-07 11:36:11 +02007824 BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
7825 BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
Takuya Yoshikawaadf52232011-05-25 11:06:16 +09007826
Wanpeng Lida6393c2021-05-27 17:01:36 -07007827 ctxt->interruptibility = 0;
7828 ctxt->have_exception = false;
7829 ctxt->exception.vector = -1;
7830 ctxt->perm_ok = false;
7831
Avi Kivitydd856ef2012-08-27 23:46:17 +03007832 init_decode_cache(ctxt);
Gleb Natapov7ae441e2011-03-31 12:06:41 +02007833 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
Mohammed Gamal8ec47222010-08-16 00:47:01 +03007834}
7835
Sean Christopherson9497e1f2019-08-27 14:40:36 -07007836void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
Mohammed Gamal63995652010-09-19 14:34:06 +02007837{
Sean Christophersonc9b8b072020-02-18 15:29:48 -08007838 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Mohammed Gamal63995652010-09-19 14:34:06 +02007839 int ret;
7840
7841 init_emulate_ctxt(vcpu);
7842
Avi Kivity9dac77f2011-06-01 15:34:25 +03007843 ctxt->op_bytes = 2;
7844 ctxt->ad_bytes = 2;
7845 ctxt->_eip = ctxt->eip + inc_eip;
Takuya Yoshikawa9d741912011-05-29 21:53:48 +09007846 ret = emulate_int_real(ctxt, irq);
Mohammed Gamal63995652010-09-19 14:34:06 +02007847
Sean Christopherson9497e1f2019-08-27 14:40:36 -07007848 if (ret != X86EMUL_CONTINUE) {
7849 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7850 } else {
7851 ctxt->eip = ctxt->_eip;
7852 kvm_rip_write(vcpu, ctxt->eip);
7853 kvm_set_rflags(vcpu, ctxt->eflags);
7854 }
Mohammed Gamal63995652010-09-19 14:34:06 +02007855}
7856EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
7857
David Edmondsone615e352021-09-20 11:37:36 +01007858static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
7859 u8 ndata, u8 *insn_bytes, u8 insn_size)
Aaron Lewis19238e72021-05-10 07:48:33 -07007860{
Aaron Lewis19238e72021-05-10 07:48:33 -07007861 struct kvm_run *run = vcpu->run;
David Edmondsone615e352021-09-20 11:37:36 +01007862 u64 info[5];
7863 u8 info_start;
7864
7865 /*
7866 * Zero the whole array used to retrieve the exit info, as casting to
7867 * u32 for select entries will leave some chunks uninitialized.
7868 */
7869 memset(&info, 0, sizeof(info));
7870
7871 static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
7872 &info[2], (u32 *)&info[3],
7873 (u32 *)&info[4]);
Aaron Lewis19238e72021-05-10 07:48:33 -07007874
7875 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7876 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
David Edmondsone615e352021-09-20 11:37:36 +01007877
7878 /*
7879 * There's currently space for 13 entries, but 5 are used for the exit
7880 * reason and info. Restrict to 4 to reduce the maintenance burden
7881 * when expanding kvm_run.emulation_failure in the future.
7882 */
7883 if (WARN_ON_ONCE(ndata > 4))
7884 ndata = 4;
7885
7886 /* Always include the flags as a 'data' entry. */
7887 info_start = 1;
Aaron Lewis19238e72021-05-10 07:48:33 -07007888 run->emulation_failure.flags = 0;
7889
7890 if (insn_size) {
David Edmondsone615e352021-09-20 11:37:36 +01007891 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
7892 sizeof(run->emulation_failure.insn_bytes) != 16));
7893 info_start += 2;
Aaron Lewis19238e72021-05-10 07:48:33 -07007894 run->emulation_failure.flags |=
7895 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
7896 run->emulation_failure.insn_size = insn_size;
7897 memset(run->emulation_failure.insn_bytes, 0x90,
7898 sizeof(run->emulation_failure.insn_bytes));
David Edmondsone615e352021-09-20 11:37:36 +01007899 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
Aaron Lewis19238e72021-05-10 07:48:33 -07007900 }
David Edmondsone615e352021-09-20 11:37:36 +01007901
7902 memcpy(&run->internal.data[info_start], info, sizeof(info));
7903 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
7904 ndata * sizeof(data[0]));
7905
7906 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
Aaron Lewis19238e72021-05-10 07:48:33 -07007907}
7908
David Edmondsone615e352021-09-20 11:37:36 +01007909static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
7910{
7911 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7912
7913 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
7914 ctxt->fetch.end - ctxt->fetch.data);
7915}
7916
7917void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
7918 u8 ndata)
7919{
7920 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
7921}
7922EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
7923
7924void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
7925{
7926 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
7927}
7928EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
7929
Liran Alone2366172018-03-12 13:12:49 +02007930static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
Gleb Natapov6d77dbf2010-05-10 11:16:56 +03007931{
Aaron Lewis19238e72021-05-10 07:48:33 -07007932 struct kvm *kvm = vcpu->kvm;
7933
Gleb Natapov6d77dbf2010-05-10 11:16:56 +03007934 ++vcpu->stat.insn_emulation_fail;
7935 trace_kvm_emulate_insn_failed(vcpu);
Liran Alone2366172018-03-12 13:12:49 +02007936
Sean Christopherson42cbf062019-08-27 14:40:31 -07007937 if (emulation_type & EMULTYPE_VMWARE_GP) {
7938 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07007939 return 1;
Sean Christopherson42cbf062019-08-27 14:40:31 -07007940 }
Liran Alone2366172018-03-12 13:12:49 +02007941
Aaron Lewis19238e72021-05-10 07:48:33 -07007942 if (kvm->arch.exit_on_emulation_error ||
7943 (emulation_type & EMULTYPE_SKIP)) {
David Edmondsone615e352021-09-20 11:37:36 +01007944 prepare_emulation_ctxt_failure_exit(vcpu);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07007945 return 0;
Sean Christopherson738fece2019-08-27 14:40:34 -07007946 }
7947
Sean Christopherson22da61c2019-08-27 14:40:28 -07007948 kvm_queue_exception(vcpu, UD_VECTOR);
7949
Jason Baronb36464772021-01-14 22:27:56 -05007950 if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
David Edmondsone615e352021-09-20 11:37:36 +01007951 prepare_emulation_ctxt_failure_exit(vcpu);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07007952 return 0;
Joerg Roedelfc3a9152010-11-29 17:51:49 +01007953 }
Liran Alone2366172018-03-12 13:12:49 +02007954
Sean Christopherson60fc3d02019-08-27 14:40:38 -07007955 return 1;
Gleb Natapov6d77dbf2010-05-10 11:16:56 +03007956}
7957
Sean Christopherson736c2912019-12-06 15:57:14 -08007958static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
Gleb Natapov991eebf2013-04-11 12:10:51 +03007959 bool write_fault_to_shadow_pgtable,
7960 int emulation_type)
Gleb Natapova6f177e2010-07-08 12:41:12 +03007961{
Sean Christopherson736c2912019-12-06 15:57:14 -08007962 gpa_t gpa = cr2_or_gpa;
Dan Williamsba049e92016-01-15 16:56:11 -08007963 kvm_pfn_t pfn;
Gleb Natapova6f177e2010-07-08 12:41:12 +03007964
Sean Christopherson92daa482020-02-18 15:03:08 -08007965 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
Gleb Natapov991eebf2013-04-11 12:10:51 +03007966 return false;
7967
Sean Christopherson92daa482020-02-18 15:03:08 -08007968 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
7969 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
Sean Christopherson6c3dfeb2018-08-23 13:56:51 -07007970 return false;
7971
Vitaly Kuznetsov44dd3ff2018-10-08 21:28:05 +02007972 if (!vcpu->arch.mmu->direct_map) {
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08007973 /*
7974 * Write permission should be allowed since only
7975 * write access need to be emulated.
7976 */
Sean Christopherson736c2912019-12-06 15:57:14 -08007977 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
Gleb Natapov68be0802010-07-14 19:05:45 +03007978
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08007979 /*
7980 * If the mapping is invalid in guest, let cpu retry
7981 * it to generate fault.
7982 */
7983 if (gpa == UNMAPPED_GVA)
7984 return true;
7985 }
Gleb Natapova6f177e2010-07-08 12:41:12 +03007986
Xiao Guangrong8e3d9d02012-08-21 10:57:42 +08007987 /*
7988 * Do not retry the unhandleable instruction if it faults on the
7989 * readonly host memory, otherwise it will goto a infinite loop:
7990 * retry instruction -> write #PF -> emulation fail -> retry
7991 * instruction -> ...
7992 */
7993 pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08007994
7995 /*
7996 * If the instruction failed on the error pfn, it can not be fixed,
7997 * report the error to userspace.
7998 */
7999 if (is_error_noslot_pfn(pfn))
8000 return false;
8001
8002 kvm_release_pfn_clean(pfn);
8003
8004 /* The instructions are well-emulated on direct mmu. */
Vitaly Kuznetsov44dd3ff2018-10-08 21:28:05 +02008005 if (vcpu->arch.mmu->direct_map) {
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08008006 unsigned int indirect_shadow_pages;
8007
Ben Gardon531810c2021-02-02 10:57:24 -08008008 write_lock(&vcpu->kvm->mmu_lock);
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08008009 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
Ben Gardon531810c2021-02-02 10:57:24 -08008010 write_unlock(&vcpu->kvm->mmu_lock);
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08008011
8012 if (indirect_shadow_pages)
8013 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
8014
Gleb Natapova6f177e2010-07-08 12:41:12 +03008015 return true;
Xiao Guangrong8e3d9d02012-08-21 10:57:42 +08008016 }
Gleb Natapova6f177e2010-07-08 12:41:12 +03008017
Xiao Guangrong95b3cf62013-01-13 23:46:52 +08008018 /*
8019 * if emulation was due to access to shadowed page table
8020 * and it failed try to unshadow page and re-enter the
8021 * guest to let CPU execute the instruction.
8022 */
8023 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
Xiao Guangrong93c05d32013-01-13 23:49:07 +08008024
8025 /*
8026 * If the access faults on its page table, it can not
8027 * be fixed by unprotecting shadow page and it should
8028 * be reported to userspace.
8029 */
8030 return !write_fault_to_shadow_pgtable;
Gleb Natapova6f177e2010-07-08 12:41:12 +03008031}
8032
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008033static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
Sean Christopherson736c2912019-12-06 15:57:14 -08008034 gpa_t cr2_or_gpa, int emulation_type)
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008035{
8036 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Sean Christopherson736c2912019-12-06 15:57:14 -08008037 unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008038
8039 last_retry_eip = vcpu->arch.last_retry_eip;
8040 last_retry_addr = vcpu->arch.last_retry_addr;
8041
8042 /*
8043 * If the emulation is caused by #PF and it is non-page_table
8044 * writing instruction, it means the VM-EXIT is caused by shadow
8045 * page protected, we can zap the shadow page and retry this
8046 * instruction directly.
8047 *
8048 * Note: if the guest uses a non-page-table modifying instruction
8049 * on the PDE that points to the instruction, then we will unmap
8050 * the instruction and go to an infinite loop. So, we cache the
8051 * last retried eip and the last fault address, if we meet the eip
8052 * and the address again, we can break out of the potential infinite
8053 * loop.
8054 */
8055 vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
8056
Sean Christopherson92daa482020-02-18 15:03:08 -08008057 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008058 return false;
8059
Sean Christopherson92daa482020-02-18 15:03:08 -08008060 if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
8061 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
Sean Christopherson6c3dfeb2018-08-23 13:56:51 -07008062 return false;
8063
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008064 if (x86_page_table_writing_insn(ctxt))
8065 return false;
8066
Sean Christopherson736c2912019-12-06 15:57:14 -08008067 if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008068 return false;
8069
8070 vcpu->arch.last_retry_eip = ctxt->eip;
Sean Christopherson736c2912019-12-06 15:57:14 -08008071 vcpu->arch.last_retry_addr = cr2_or_gpa;
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008072
Vitaly Kuznetsov44dd3ff2018-10-08 21:28:05 +02008073 if (!vcpu->arch.mmu->direct_map)
Sean Christopherson736c2912019-12-06 15:57:14 -08008074 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008075
Xiao Guangrong22368022013-01-13 23:44:12 +08008076 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008077
8078 return true;
8079}
8080
Gleb Natapov716d51a2012-09-03 15:24:26 +03008081static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8082static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8083
Sean Christophersondc872752021-06-09 11:56:15 -07008084static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm)
Paolo Bonzinia5845392015-04-01 18:18:53 +02008085{
Sean Christopherson1270e642021-06-09 11:56:17 -07008086 trace_kvm_smm_transition(vcpu->vcpu_id, vcpu->arch.smbase, entering_smm);
Sean Christopherson0d7ee6f2021-06-09 11:56:16 -07008087
Sean Christophersondc872752021-06-09 11:56:15 -07008088 if (entering_smm) {
8089 vcpu->arch.hflags |= HF_SMM_MASK;
8090 } else {
8091 vcpu->arch.hflags &= ~(HF_SMM_MASK | HF_SMM_INSIDE_NMI_MASK);
8092
Paolo Bonzinic43203c2016-06-01 22:26:00 +02008093 /* Process a latched INIT or SMI, if any. */
8094 kvm_make_request(KVM_REQ_EVENT, vcpu);
Maxim Levitsky37687c42021-09-13 17:09:50 +03008095
8096 /*
8097 * Even if KVM_SET_SREGS2 loaded PDPTRs out of band,
8098 * on SMM exit we still need to reload them from
8099 * guest memory
8100 */
8101 vcpu->arch.pdptrs_from_userspace = false;
Paolo Bonzini64d60672015-05-07 11:36:11 +02008102 }
Paolo Bonzini699023e2015-05-18 15:03:39 +02008103
8104 kvm_mmu_reset_context(vcpu);
Paolo Bonzini64d60672015-05-07 11:36:11 +02008105}
8106
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008107static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8108 unsigned long *db)
8109{
8110 u32 dr6 = 0;
8111 int i;
8112 u32 enable, rwlen;
8113
8114 enable = dr7;
8115 rwlen = dr7 >> 16;
8116 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8117 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8118 dr6 |= (1 << i);
8119 return dr6;
8120}
8121
Sean Christopherson120c2c42019-08-27 14:40:29 -07008122static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
Paolo Bonzini663f4c62013-06-25 18:32:07 +02008123{
8124 struct kvm_run *kvm_run = vcpu->run;
8125
Paolo Bonzinic8401dd2017-06-07 15:13:14 +02008126 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +08008127 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
Peter Xud5d260c2020-05-05 16:49:59 -04008128 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
Paolo Bonzinic8401dd2017-06-07 15:13:14 +02008129 kvm_run->debug.arch.exception = DB_VECTOR;
8130 kvm_run->exit_reason = KVM_EXIT_DEBUG;
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008131 return 0;
Paolo Bonzini663f4c62013-06-25 18:32:07 +02008132 }
Sean Christopherson120c2c42019-08-27 14:40:29 -07008133 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008134 return 1;
Paolo Bonzini663f4c62013-06-25 18:32:07 +02008135}
8136
Kyle Huey6affcbe2016-11-29 12:40:40 -08008137int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8138{
Jason Baronb36464772021-01-14 22:27:56 -05008139 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
Vitaly Kuznetsovf8ea7c62019-08-13 15:53:30 +02008140 int r;
Kyle Huey6affcbe2016-11-29 12:40:40 -08008141
Jason Baronb36464772021-01-14 22:27:56 -05008142 r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008143 if (unlikely(!r))
Vitaly Kuznetsovf8ea7c62019-08-13 15:53:30 +02008144 return 0;
Paolo Bonzinic8401dd2017-06-07 15:13:14 +02008145
Eric Hankland9cd803d2021-11-30 15:42:20 +08008146 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
8147
Paolo Bonzinic8401dd2017-06-07 15:13:14 +02008148 /*
8149 * rflags is the old, "raw" value of the flags. The new value has
8150 * not been saved yet.
8151 *
8152 * This is correct even for TF set by the guest, because "the
8153 * processor will not generate this exception after the instruction
8154 * that sets the TF flag".
8155 */
8156 if (unlikely(rflags & X86_EFLAGS_TF))
Sean Christopherson120c2c42019-08-27 14:40:29 -07008157 r = kvm_vcpu_do_singlestep(vcpu);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008158 return r;
Kyle Huey6affcbe2016-11-29 12:40:40 -08008159}
8160EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
8161
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008162static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
8163{
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008164 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
8165 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
Nadav Amit82b32772014-11-02 11:54:45 +02008166 struct kvm_run *kvm_run = vcpu->run;
8167 unsigned long eip = kvm_get_linear_rip(vcpu);
8168 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008169 vcpu->arch.guest_debug_dr7,
8170 vcpu->arch.eff_db);
8171
8172 if (dr6 != 0) {
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +08008173 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
Nadav Amit82b32772014-11-02 11:54:45 +02008174 kvm_run->debug.arch.pc = eip;
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008175 kvm_run->debug.arch.exception = DB_VECTOR;
8176 kvm_run->exit_reason = KVM_EXIT_DEBUG;
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008177 *r = 0;
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008178 return true;
8179 }
8180 }
8181
Nadav Amit4161a562014-07-17 01:19:31 +03008182 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
8183 !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
Nadav Amit82b32772014-11-02 11:54:45 +02008184 unsigned long eip = kvm_get_linear_rip(vcpu);
8185 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008186 vcpu->arch.dr7,
8187 vcpu->arch.db);
8188
8189 if (dr6 != 0) {
Paolo Bonzini4d5523c2020-05-05 07:33:20 -04008190 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008191 *r = 1;
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008192 return true;
8193 }
8194 }
8195
8196 return false;
8197}
8198
Liran Alon04789b62018-03-12 13:12:50 +02008199static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
8200{
Arbel Moshe2d7921c2018-03-12 13:12:53 +02008201 switch (ctxt->opcode_len) {
8202 case 1:
8203 switch (ctxt->b) {
8204 case 0xe4: /* IN */
8205 case 0xe5:
8206 case 0xec:
8207 case 0xed:
8208 case 0xe6: /* OUT */
8209 case 0xe7:
8210 case 0xee:
8211 case 0xef:
8212 case 0x6c: /* INS */
8213 case 0x6d:
8214 case 0x6e: /* OUTS */
8215 case 0x6f:
8216 return true;
8217 }
8218 break;
8219 case 2:
8220 switch (ctxt->b) {
8221 case 0x33: /* RDPMC */
8222 return true;
8223 }
8224 break;
Liran Alon04789b62018-03-12 13:12:50 +02008225 }
8226
8227 return false;
8228}
8229
Wei Huang4aa26912021-01-26 03:18:28 -05008230/*
8231 * Decode to be emulated instruction. Return EMULATION_OK if success.
8232 */
8233int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
8234 void *insn, int insn_len)
8235{
8236 int r = EMULATION_OK;
8237 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8238
8239 init_emulate_ctxt(vcpu);
8240
8241 /*
8242 * We will reenter on the same instruction since we do not set
8243 * complete_userspace_io. This does not handle watchpoints yet,
8244 * those would be handled in the emulate_ops.
8245 */
8246 if (!(emulation_type & EMULTYPE_SKIP) &&
8247 kvm_vcpu_check_breakpoint(vcpu, &r))
8248 return r;
8249
Wanpeng Lib35491e2021-05-27 17:01:37 -07008250 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
Wei Huang4aa26912021-01-26 03:18:28 -05008251
8252 trace_kvm_emulate_insn_start(vcpu);
8253 ++vcpu->stat.insn_emulation;
8254
8255 return r;
8256}
8257EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
8258
Sean Christopherson736c2912019-12-06 15:57:14 -08008259int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
8260 int emulation_type, void *insn, int insn_len)
Carsten Ottebbd9b642007-10-30 18:44:21 +01008261{
Gleb Natapov95cb2292010-04-28 19:15:43 +03008262 int r;
Sean Christophersonc9b8b072020-02-18 15:29:48 -08008263 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008264 bool writeback = true;
Sean Christopherson09e3e2a2020-09-15 16:27:02 -07008265 bool write_fault_to_spt;
8266
Sean Christopherson4d31d9e2022-01-20 01:07:15 +00008267 if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
Sean Christopherson09e3e2a2020-09-15 16:27:02 -07008268 return 1;
Carsten Ottebbd9b642007-10-30 18:44:21 +01008269
Paolo Bonzinic595cee2018-07-02 13:07:14 +02008270 vcpu->arch.l1tf_flush_l1d = true;
8271
Xiao Guangrong93c05d32013-01-13 23:49:07 +08008272 /*
8273 * Clear write_fault_to_shadow_pgtable here to ensure it is
8274 * never reused.
8275 */
Sean Christopherson09e3e2a2020-09-15 16:27:02 -07008276 write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
Xiao Guangrong93c05d32013-01-13 23:49:07 +08008277 vcpu->arch.write_fault_to_shadow_pgtable = false;
Gleb Natapov8d7d81022011-04-12 12:36:21 +03008278
Sheng Yang571008d2008-01-02 14:49:22 +08008279 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
Wei Huang4aa26912021-01-26 03:18:28 -05008280 kvm_clear_exception_queue(vcpu);
Paolo Bonzini4a1e10d2013-05-30 11:48:30 +02008281
Wei Huang4aa26912021-01-26 03:18:28 -05008282 r = x86_decode_emulated_instruction(vcpu, emulation_type,
8283 insn, insn_len);
Takuya Yoshikawa1d2887e2011-07-30 18:03:34 +09008284 if (r != EMULATION_OK) {
Sean Christophersonb4000602019-08-27 14:40:32 -07008285 if ((emulation_type & EMULTYPE_TRAP_UD) ||
Sean Christophersonc83fad65e2019-08-27 14:40:33 -07008286 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
8287 kvm_queue_exception(vcpu, UD_VECTOR);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008288 return 1;
Sean Christophersonc83fad65e2019-08-27 14:40:33 -07008289 }
Sean Christopherson736c2912019-12-06 15:57:14 -08008290 if (reexecute_instruction(vcpu, cr2_or_gpa,
8291 write_fault_to_spt,
8292 emulation_type))
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008293 return 1;
Jan Dakinevich8530a792019-08-27 13:07:09 +00008294 if (ctxt->have_exception) {
Jan Dakinevichc8848ce2019-08-27 13:07:08 +00008295 /*
8296 * #UD should result in just EMULATION_FAILED, and trap-like
8297 * exception should not be encountered during decode.
8298 */
8299 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
8300 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
Jan Dakinevich8530a792019-08-27 13:07:09 +00008301 inject_emulated_exception(vcpu);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008302 return 1;
Jan Dakinevich8530a792019-08-27 13:07:09 +00008303 }
Liran Alone2366172018-03-12 13:12:49 +02008304 return handle_emulation_failure(vcpu, emulation_type);
Carsten Ottebbd9b642007-10-30 18:44:21 +01008305 }
8306 }
8307
Sean Christopherson42cbf062019-08-27 14:40:31 -07008308 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
8309 !is_vmware_backdoor_opcode(ctxt)) {
8310 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008311 return 1;
Sean Christopherson42cbf062019-08-27 14:40:31 -07008312 }
Liran Alon04789b62018-03-12 13:12:50 +02008313
Sean Christopherson1957aa62019-08-27 14:40:39 -07008314 /*
Hou Wenlong906fa902021-11-02 17:15:30 +08008315 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
8316 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
8317 * The caller is responsible for updating interruptibility state and
8318 * injecting single-step #DBs.
Sean Christopherson1957aa62019-08-27 14:40:39 -07008319 */
Gleb Natapovba8afb62009-04-12 13:36:57 +03008320 if (emulation_type & EMULTYPE_SKIP) {
Sean Christopherson5e854862021-11-02 17:15:29 +08008321 if (ctxt->mode != X86EMUL_MODE_PROT64)
8322 ctxt->eip = (u32)ctxt->_eip;
8323 else
8324 ctxt->eip = ctxt->_eip;
8325
Hou Wenlong906fa902021-11-02 17:15:30 +08008326 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
8327 r = 1;
8328 goto writeback;
8329 }
8330
Sean Christopherson5e854862021-11-02 17:15:29 +08008331 kvm_rip_write(vcpu, ctxt->eip);
Nadav Amitbb663c72014-07-21 14:37:26 +03008332 if (ctxt->eflags & X86_EFLAGS_RF)
8333 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008334 return 1;
Gleb Natapovba8afb62009-04-12 13:36:57 +03008335 }
8336
Sean Christopherson736c2912019-12-06 15:57:14 -08008337 if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008338 return 1;
Xiao Guangrong1cb3f3a2011-09-22 17:02:48 +08008339
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008340 /* this is needed for vmware backdoor interface to work since it
Gleb Natapov4d2179e2010-04-28 19:15:42 +03008341 changes registers values during IO operation */
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008342 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
8343 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
Avi Kivitydd856ef2012-08-27 23:46:17 +03008344 emulator_invalidate_register_cache(ctxt);
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008345 }
Gleb Natapov4d2179e2010-04-28 19:15:42 +03008346
Gleb Natapov5cd21912010-03-18 15:20:26 +02008347restart:
Sean Christopherson92daa482020-02-18 15:03:08 -08008348 if (emulation_type & EMULTYPE_PF) {
8349 /* Save the faulting GPA (cr2) in the address field */
8350 ctxt->exception.address = cr2_or_gpa;
8351
8352 /* With shadow page tables, cr2 contains a GVA or nGPA. */
8353 if (vcpu->arch.mmu->direct_map) {
Sean Christopherson744e6992020-02-18 15:03:09 -08008354 ctxt->gpa_available = true;
8355 ctxt->gpa_val = cr2_or_gpa;
Sean Christopherson92daa482020-02-18 15:03:08 -08008356 }
8357 } else {
8358 /* Sanitize the address out of an abundance of paranoia. */
8359 ctxt->exception.address = 0;
8360 }
Tom Lendacky0f89b202016-12-14 14:59:23 -05008361
Takuya Yoshikawa9d741912011-05-29 21:53:48 +09008362 r = x86_emulate_insn(ctxt);
Gleb Natapovc3cd7ff2010-04-28 19:15:35 +03008363
Joerg Roedel775fde82011-04-04 12:39:24 +02008364 if (r == EMULATION_INTERCEPTED)
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008365 return 1;
Joerg Roedel775fde82011-04-04 12:39:24 +02008366
Gleb Natapovd2ddd1c2010-08-25 12:47:43 +03008367 if (r == EMULATION_FAILED) {
Sean Christopherson736c2912019-12-06 15:57:14 -08008368 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
Gleb Natapov991eebf2013-04-11 12:10:51 +03008369 emulation_type))
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008370 return 1;
Gleb Natapovc3cd7ff2010-04-28 19:15:35 +03008371
Liran Alone2366172018-03-12 13:12:49 +02008372 return handle_emulation_failure(vcpu, emulation_type);
Carsten Ottebbd9b642007-10-30 18:44:21 +01008373 }
8374
Takuya Yoshikawa9d741912011-05-29 21:53:48 +09008375 if (ctxt->have_exception) {
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008376 r = 1;
Paolo Bonzinief54bcf2014-09-04 19:46:15 +02008377 if (inject_emulated_exception(vcpu))
8378 return r;
Gleb Natapovd2ddd1c2010-08-25 12:47:43 +03008379 } else if (vcpu->arch.pio.count) {
Paolo Bonzini0912c972013-08-27 15:41:43 +02008380 if (!vcpu->arch.pio.in) {
8381 /* FIXME: return into emulator if single-stepping. */
Gleb Natapove85d28f2010-07-29 15:11:52 +03008382 vcpu->arch.pio.count = 0;
Paolo Bonzini0912c972013-08-27 15:41:43 +02008383 } else {
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008384 writeback = false;
Gleb Natapov716d51a2012-09-03 15:24:26 +03008385 vcpu->arch.complete_userspace_io = complete_emulated_pio;
8386 }
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008387 r = 0;
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008388 } else if (vcpu->mmio_needed) {
Sean Christophersonbc8a0aa2019-08-27 14:40:27 -07008389 ++vcpu->stat.mmio_exits;
8390
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008391 if (!vcpu->mmio_is_write)
8392 writeback = false;
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008393 r = 0;
Gleb Natapov716d51a2012-09-03 15:24:26 +03008394 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
Hou Wenlongadbfb122021-11-02 17:15:32 +08008395 } else if (vcpu->arch.complete_userspace_io) {
8396 writeback = false;
8397 r = 0;
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008398 } else if (r == EMULATION_RESTART)
Gleb Natapove85d28f2010-07-29 15:11:52 +03008399 goto restart;
Gleb Natapovd2ddd1c2010-08-25 12:47:43 +03008400 else
Sean Christopherson60fc3d02019-08-27 14:40:38 -07008401 r = 1;
Gleb Natapove85d28f2010-07-29 15:11:52 +03008402
Hou Wenlong906fa902021-11-02 17:15:30 +08008403writeback:
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008404 if (writeback) {
Jason Baronb36464772021-01-14 22:27:56 -05008405 unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
Takuya Yoshikawa9d741912011-05-29 21:53:48 +09008406 toggle_interruptibility(vcpu, ctxt->interruptibility);
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008407 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
Nadav Amit38827db2014-11-02 11:54:53 +02008408 if (!ctxt->have_exception ||
Sean Christopherson75ee23b2019-08-23 13:55:44 -07008409 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
Eric Hankland9cd803d2021-11-30 15:42:20 +08008410 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
Eric Hankland018d70f2021-11-30 15:42:21 +08008411 if (ctxt->is_branch)
8412 kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
Sean Christopherson75ee23b2019-08-23 13:55:44 -07008413 kvm_rip_write(vcpu, ctxt->eip);
Felipe Franciosi384dea12020-05-19 08:11:22 +00008414 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
Sean Christopherson120c2c42019-08-27 14:40:29 -07008415 r = kvm_vcpu_do_singlestep(vcpu);
Sean Christophersonafaf0b22020-03-21 13:26:00 -07008416 if (kvm_x86_ops.update_emulated_instruction)
Jason Baronb36464772021-01-14 22:27:56 -05008417 static_call(kvm_x86_update_emulated_instruction)(vcpu);
Nadav Amit38827db2014-11-02 11:54:53 +02008418 __kvm_set_rflags(vcpu, ctxt->eflags);
Sean Christopherson75ee23b2019-08-23 13:55:44 -07008419 }
Paolo Bonzini6addfc42014-03-27 11:29:28 +01008420
8421 /*
8422 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
8423 * do nothing, and it will be requested again as soon as
8424 * the shadow expires. But we still need to check here,
8425 * because POPF has no interrupt shadow.
8426 */
8427 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
8428 kvm_make_request(KVM_REQ_EVENT, vcpu);
Gleb Natapov7ae441e2011-03-31 12:06:41 +02008429 } else
8430 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
Gleb Natapov3457e412010-04-28 19:15:38 +03008431
Gleb Natapove85d28f2010-07-29 15:11:52 +03008432 return r;
Carsten Ottebbd9b642007-10-30 18:44:21 +01008433}
Sean Christophersonc60658d2018-08-23 13:56:53 -07008434
8435int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
8436{
8437 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
8438}
8439EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
8440
8441int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
8442 void *insn, int insn_len)
8443{
8444 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
8445}
8446EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
Carsten Ottebbd9b642007-10-30 18:44:21 +01008447
Sean Christopherson8764ed52019-04-29 07:04:15 -07008448static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
8449{
8450 vcpu->arch.pio.count = 0;
8451 return 1;
8452}
8453
Sean Christopherson45def772019-03-11 20:01:05 -07008454static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
8455{
8456 vcpu->arch.pio.count = 0;
8457
8458 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
8459 return 1;
8460
8461 return kvm_skip_emulated_instruction(vcpu);
8462}
8463
Sean Christophersondca7f122018-03-08 08:57:27 -08008464static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
8465 unsigned short port)
Carsten Ottede7d7892007-10-30 18:44:25 +01008466{
Sean Christophersonde3cd112019-04-30 10:36:17 -07008467 unsigned long val = kvm_rax_read(vcpu);
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08008468 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
8469
Sean Christopherson8764ed52019-04-29 07:04:15 -07008470 if (ret)
8471 return ret;
Sean Christopherson45def772019-03-11 20:01:05 -07008472
Sean Christopherson8764ed52019-04-29 07:04:15 -07008473 /*
8474 * Workaround userspace that relies on old KVM behavior of %rip being
8475 * incremented prior to exiting to userspace to handle "OUT 0x7e".
8476 */
8477 if (port == 0x7e &&
8478 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
8479 vcpu->arch.complete_userspace_io =
8480 complete_fast_pio_out_port_0x7e;
8481 kvm_skip_emulated_instruction(vcpu);
8482 } else {
Sean Christopherson45def772019-03-11 20:01:05 -07008483 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
8484 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
8485 }
Sean Christopherson8764ed52019-04-29 07:04:15 -07008486 return 0;
Carsten Ottede7d7892007-10-30 18:44:25 +01008487}
Carsten Ottede7d7892007-10-30 18:44:25 +01008488
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008489static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
8490{
8491 unsigned long val;
8492
8493 /* We should only ever be called with arch.pio.count equal to 1 */
8494 BUG_ON(vcpu->arch.pio.count != 1);
8495
Sean Christopherson45def772019-03-11 20:01:05 -07008496 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
8497 vcpu->arch.pio.count = 0;
8498 return 1;
8499 }
8500
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008501 /* For size less than 4 we merge, else we zero extend */
Sean Christophersonde3cd112019-04-30 10:36:17 -07008502 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008503
8504 /*
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08008505 * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008506 * the copy and tracing
8507 */
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08008508 emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
Sean Christophersonde3cd112019-04-30 10:36:17 -07008509 kvm_rax_write(vcpu, val);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008510
Sean Christopherson45def772019-03-11 20:01:05 -07008511 return kvm_skip_emulated_instruction(vcpu);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008512}
8513
Sean Christophersondca7f122018-03-08 08:57:27 -08008514static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
8515 unsigned short port)
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008516{
8517 unsigned long val;
8518 int ret;
8519
8520 /* For size less than 4 we merge, else we zero extend */
Sean Christophersonde3cd112019-04-30 10:36:17 -07008521 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008522
Sean Christopherson2e3bb4d2020-02-18 15:29:41 -08008523 ret = emulator_pio_in(vcpu, size, port, &val, 1);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008524 if (ret) {
Sean Christophersonde3cd112019-04-30 10:36:17 -07008525 kvm_rax_write(vcpu, val);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008526 return ret;
8527 }
8528
Sean Christopherson45def772019-03-11 20:01:05 -07008529 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008530 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
8531
8532 return 0;
8533}
Sean Christophersondca7f122018-03-08 08:57:27 -08008534
8535int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
8536{
Sean Christopherson45def772019-03-11 20:01:05 -07008537 int ret;
Sean Christophersondca7f122018-03-08 08:57:27 -08008538
Sean Christophersondca7f122018-03-08 08:57:27 -08008539 if (in)
Sean Christopherson45def772019-03-11 20:01:05 -07008540 ret = kvm_fast_pio_in(vcpu, size, port);
Sean Christophersondca7f122018-03-08 08:57:27 -08008541 else
Sean Christopherson45def772019-03-11 20:01:05 -07008542 ret = kvm_fast_pio_out(vcpu, size, port);
8543 return ret && kvm_skip_emulated_instruction(vcpu);
Sean Christophersondca7f122018-03-08 08:57:27 -08008544}
8545EXPORT_SYMBOL_GPL(kvm_fast_pio);
Tom Lendacky8370c3d2016-11-23 12:01:50 -05008546
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008547static int kvmclock_cpu_down_prep(unsigned int cpu)
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008548{
Tejun Heo0a3aee02010-12-18 16:28:55 +01008549 __this_cpu_write(cpu_tsc_khz, 0);
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008550 return 0;
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008551}
8552
8553static void tsc_khz_changed(void *data)
8554{
8555 struct cpufreq_freqs *freq = data;
8556 unsigned long khz = 0;
8557
8558 if (data)
8559 khz = freq->new;
8560 else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8561 khz = cpufreq_quick_get(raw_smp_processor_id());
8562 if (!khz)
8563 khz = tsc_khz;
Tejun Heo0a3aee02010-12-18 16:28:55 +01008564 __this_cpu_write(cpu_tsc_khz, khz);
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008565}
8566
Thomas Gleixner5fa4ec92018-01-31 09:41:40 +01008567#ifdef CONFIG_X86_64
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008568static void kvm_hyperv_tsc_notifier(void)
8569{
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008570 struct kvm *kvm;
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008571 int cpu;
8572
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008573 mutex_lock(&kvm_lock);
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008574 list_for_each_entry(kvm, &vm_list, vm_list)
8575 kvm_make_mclock_inprogress_request(kvm);
8576
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00008577 /* no guest entries from this point */
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008578 hyperv_stop_tsc_emulation();
8579
8580 /* TSC frequency always matches when on Hyper-V */
8581 for_each_present_cpu(cpu)
8582 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
8583 kvm_max_guest_tsc_khz = tsc_khz;
8584
8585 list_for_each_entry(kvm, &vm_list, vm_list) {
Paolo Bonzini869b4422021-09-16 18:15:36 +00008586 __kvm_start_pvclock_update(kvm);
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008587 pvclock_update_vm_gtod_copy(kvm);
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00008588 kvm_end_pvclock_update(kvm);
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008589 }
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00008590
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008591 mutex_unlock(&kvm_lock);
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008592}
Thomas Gleixner5fa4ec92018-01-31 09:41:40 +01008593#endif
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008594
Viresh Kumardf240142019-04-29 15:03:58 +05308595static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008596{
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008597 struct kvm *kvm;
8598 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +00008599 int send_ipi = 0;
8600 unsigned long i;
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008601
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008602 /*
8603 * We allow guests to temporarily run on slowing clocks,
8604 * provided we notify them after, or to run on accelerating
8605 * clocks, provided we notify them before. Thus time never
8606 * goes backwards.
8607 *
8608 * However, we have a problem. We can't atomically update
8609 * the frequency of a given CPU from this function; it is
8610 * merely a notifier, which can be called from any CPU.
8611 * Changing the TSC frequency at arbitrary points in time
8612 * requires a recomputation of local variables related to
8613 * the TSC for each VCPU. We must flag these local variables
8614 * to be updated and be sure the update takes place with the
8615 * new frequency before any guests proceed.
8616 *
8617 * Unfortunately, the combination of hotplug CPU and frequency
8618 * change creates an intractable locking scenario; the order
8619 * of when these callouts happen is undefined with respect to
8620 * CPU hotplug, and they can race with each other. As such,
8621 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
8622 * undefined; you can actually have a CPU frequency change take
8623 * place in between the computation of X and the setting of the
8624 * variable. To protect against this problem, all updates of
8625 * the per_cpu tsc_khz variable are done in an interrupt
8626 * protected IPI, and all callers wishing to update the value
8627 * must wait for a synchronous IPI to complete (which is trivial
8628 * if the caller is on the CPU already). This establishes the
8629 * necessary total order on variable updates.
8630 *
8631 * Note that because a guest time update may take place
8632 * anytime after the setting of the VCPU's request bit, the
8633 * correct TSC value must be set before the request. However,
8634 * to ensure the update actually makes it to any guest which
8635 * starts running in hardware virtualization between the set
8636 * and the acquisition of the spinlock, we must also ping the
8637 * CPU after setting the request bit.
8638 *
8639 */
8640
Viresh Kumardf240142019-04-29 15:03:58 +05308641 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008642
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008643 mutex_lock(&kvm_lock);
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008644 list_for_each_entry(kvm, &vm_list, vm_list) {
Gleb Natapov988a2ca2009-06-09 15:56:29 +03008645 kvm_for_each_vcpu(i, vcpu, kvm) {
Viresh Kumardf240142019-04-29 15:03:58 +05308646 if (vcpu->cpu != cpu)
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008647 continue;
Zachary Amsdenc2855452010-09-18 14:38:15 -10008648 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008649 if (vcpu->cpu != raw_smp_processor_id())
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008650 send_ipi = 1;
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008651 }
8652 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008653 mutex_unlock(&kvm_lock);
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008654
8655 if (freq->old < freq->new && send_ipi) {
8656 /*
8657 * We upscale the frequency. Must make the guest
8658 * doesn't see old kvmclock values while running with
8659 * the new frequency, otherwise we risk the guest sees
8660 * time go backwards.
8661 *
8662 * In case we update the frequency for another cpu
8663 * (which might be in guest context) send an interrupt
8664 * to kick the cpu out of guest context. Next time
8665 * guest context is entered kvmclock will be updated,
8666 * so the guest will not see stale values.
8667 */
Viresh Kumardf240142019-04-29 15:03:58 +05308668 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008669 }
Viresh Kumardf240142019-04-29 15:03:58 +05308670}
8671
8672static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
8673 void *data)
8674{
8675 struct cpufreq_freqs *freq = data;
8676 int cpu;
8677
8678 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
8679 return 0;
8680 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
8681 return 0;
8682
8683 for_each_cpu(cpu, freq->policy->cpus)
8684 __kvmclock_cpufreq_notifier(freq, cpu);
8685
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008686 return 0;
8687}
8688
8689static struct notifier_block kvmclock_cpufreq_notifier_block = {
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008690 .notifier_call = kvmclock_cpufreq_notifier
8691};
8692
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008693static int kvmclock_cpu_online(unsigned int cpu)
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008694{
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008695 tsc_khz_changed(NULL);
8696 return 0;
Zachary Amsden8cfdc002010-08-19 22:07:21 -10008697}
8698
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008699static void kvm_timer_init(void)
8700{
Zachary Amsdenc2855452010-09-18 14:38:15 -10008701 max_tsc_khz = tsc_khz;
Srivatsa S. Bhat460dd422014-03-11 02:09:01 +05308702
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008703 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
Zachary Amsdenc2855452010-09-18 14:38:15 -10008704#ifdef CONFIG_CPU_FREQ
Paolo Bonziniaaec7c02020-02-28 10:49:10 +01008705 struct cpufreq_policy *policy;
Borislav Petkov758f5882016-09-04 19:13:57 +02008706 int cpu;
8707
Avi Kivity3e26f232010-12-16 12:16:34 +02008708 cpu = get_cpu();
Paolo Bonziniaaec7c02020-02-28 10:49:10 +01008709 policy = cpufreq_cpu_get(cpu);
Wanpeng Li9a119972020-03-02 15:15:36 +08008710 if (policy) {
8711 if (policy->cpuinfo.max_freq)
8712 max_tsc_khz = policy->cpuinfo.max_freq;
8713 cpufreq_cpu_put(policy);
8714 }
Avi Kivity3e26f232010-12-16 12:16:34 +02008715 put_cpu();
Zachary Amsdenc2855452010-09-18 14:38:15 -10008716#endif
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008717 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
8718 CPUFREQ_TRANSITION_NOTIFIER);
8719 }
Srivatsa S. Bhat460dd422014-03-11 02:09:01 +05308720
Thomas Gleixner73c1b412016-12-21 20:19:54 +01008721 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008722 kvmclock_cpu_online, kvmclock_cpu_down_prep);
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008723}
8724
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008725#ifdef CONFIG_X86_64
8726static void pvclock_gtod_update_fn(struct work_struct *work)
8727{
Marcelo Tosattid8281992012-11-27 23:29:01 -02008728 struct kvm *kvm;
Marcelo Tosattid8281992012-11-27 23:29:01 -02008729 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +00008730 unsigned long i;
Marcelo Tosattid8281992012-11-27 23:29:01 -02008731
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008732 mutex_lock(&kvm_lock);
Marcelo Tosattid8281992012-11-27 23:29:01 -02008733 list_for_each_entry(kvm, &vm_list, vm_list)
8734 kvm_for_each_vcpu(i, vcpu, kvm)
Guo Hui Liu105b21b2014-09-12 13:43:19 +08008735 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
Marcelo Tosattid8281992012-11-27 23:29:01 -02008736 atomic_set(&kvm_guest_has_master_clock, 0);
Junaid Shahid0d9ce162019-01-03 17:14:28 -08008737 mutex_unlock(&kvm_lock);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008738}
8739
8740static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
8741
8742/*
Thomas Gleixner3f804f62021-05-06 15:21:37 +02008743 * Indirection to move queue_work() out of the tk_core.seq write held
8744 * region to prevent possible deadlocks against time accessors which
8745 * are invoked with work related locks held.
8746 */
8747static void pvclock_irq_work_fn(struct irq_work *w)
8748{
8749 queue_work(system_long_wq, &pvclock_gtod_work);
8750}
8751
8752static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
8753
8754/*
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008755 * Notification about pvclock gtod data update.
8756 */
8757static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
8758 void *priv)
8759{
8760 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
8761 struct timekeeper *tk = priv;
8762
8763 update_pvclock_gtod(tk);
8764
Thomas Gleixner3f804f62021-05-06 15:21:37 +02008765 /*
8766 * Disable master clock if host does not trust, or does not use,
8767 * TSC based clocksource. Delegate queue_work() to irq_work as
8768 * this is invoked with tk_core.seq write held.
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008769 */
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +01008770 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008771 atomic_read(&kvm_guest_has_master_clock) != 0)
Thomas Gleixner3f804f62021-05-06 15:21:37 +02008772 irq_work_queue(&pvclock_irq_work);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008773 return 0;
8774}
8775
8776static struct notifier_block pvclock_gtod_notifier = {
8777 .notifier_call = pvclock_gtod_notify,
8778};
8779#endif
8780
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008781int kvm_arch_init(void *opaque)
Carsten Otte043405e2007-10-10 17:16:19 +02008782{
Sean Christophersond008dfd2020-03-21 13:25:56 -07008783 struct kvm_x86_init_ops *ops = opaque;
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008784 int r;
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008785
Sean Christophersonafaf0b22020-03-21 13:26:00 -07008786 if (kvm_x86_ops.hardware_enable) {
Sean Christopherson9dadfc42021-10-18 11:39:28 -07008787 pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008788 r = -EEXIST;
8789 goto out;
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008790 }
8791
8792 if (!ops->cpu_has_kvm_support()) {
Sean Christopherson9dadfc42021-10-18 11:39:28 -07008793 pr_err_ratelimited("kvm: no hardware support for '%s'\n",
8794 ops->runtime_ops->name);
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008795 r = -EOPNOTSUPP;
8796 goto out;
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008797 }
8798 if (ops->disabled_by_bios()) {
Sean Christopherson9dadfc42021-10-18 11:39:28 -07008799 pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
8800 ops->runtime_ops->name);
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008801 r = -EOPNOTSUPP;
8802 goto out;
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008803 }
8804
Marc Orrb666a4b2018-11-06 14:53:56 -08008805 /*
8806 * KVM explicitly assumes that the guest has an FPU and
8807 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
8808 * vCPU's FPU state as a fxregs_state struct.
8809 */
8810 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
8811 printk(KERN_ERR "kvm: inadequate fpu\n");
8812 r = -EOPNOTSUPP;
8813 goto out;
8814 }
8815
Marcelo Tosatti013f6a52013-01-03 11:41:39 -02008816 r = -ENOMEM;
Marc Orrb666a4b2018-11-06 14:53:56 -08008817
Sean Christophersonc9b8b072020-02-18 15:29:48 -08008818 x86_emulator_cache = kvm_alloc_emulator_cache();
8819 if (!x86_emulator_cache) {
8820 pr_err("kvm: failed to allocate cache for x86 emulator\n");
Thomas Gleixnerd69c1382021-10-22 20:55:53 +02008821 goto out;
Sean Christophersonc9b8b072020-02-18 15:29:48 -08008822 }
8823
Sean Christopherson7e34fbd2020-09-23 11:03:55 -07008824 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
8825 if (!user_return_msrs) {
8826 printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
Sean Christophersonc9b8b072020-02-18 15:29:48 -08008827 goto out_free_x86_emulator_cache;
Marcelo Tosatti013f6a52013-01-03 11:41:39 -02008828 }
Sean Christophersone5fda4b2021-05-04 10:17:32 -07008829 kvm_nr_uret_msrs = 0;
Marcelo Tosatti013f6a52013-01-03 11:41:39 -02008830
Avi Kivity97db56c2008-01-13 13:23:56 +02008831 r = kvm_mmu_module_init();
8832 if (r)
Marcelo Tosatti013f6a52013-01-03 11:41:39 -02008833 goto out_free_percpu;
Avi Kivity97db56c2008-01-13 13:23:56 +02008834
Zachary Amsdenb820cc02009-09-29 11:38:34 -10008835 kvm_timer_init();
Gerd Hoffmannc8076602009-02-04 17:52:04 +01008836
Sean Christophersoncfc48182020-03-02 15:56:23 -08008837 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
Dexuan Cui2acf9232010-06-10 11:27:12 +08008838 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
Sean Christophersoncfc48182020-03-02 15:56:23 -08008839 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
8840 }
Dexuan Cui2acf9232010-06-10 11:27:12 +08008841
Wanpeng Li0c5f81d2019-07-06 09:26:51 +08008842 if (pi_inject_timer == -1)
8843 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008844#ifdef CONFIG_X86_64
8845 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008846
Thomas Gleixner5fa4ec92018-01-31 09:41:40 +01008847 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008848 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008849#endif
8850
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008851 return 0;
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008852
Marcelo Tosatti013f6a52013-01-03 11:41:39 -02008853out_free_percpu:
Sean Christopherson7e34fbd2020-09-23 11:03:55 -07008854 free_percpu(user_return_msrs);
Sean Christophersonc9b8b072020-02-18 15:29:48 -08008855out_free_x86_emulator_cache:
8856 kmem_cache_destroy(x86_emulator_cache);
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008857out:
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008858 return r;
Carsten Otte043405e2007-10-10 17:16:19 +02008859}
Hollis Blanchard8776e512007-10-31 17:24:24 -05008860
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008861void kvm_arch_exit(void)
8862{
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008863#ifdef CONFIG_X86_64
Thomas Gleixner5fa4ec92018-01-31 09:41:40 +01008864 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
Vitaly Kuznetsov0092e432018-01-24 14:23:37 +01008865 clear_hv_tscchange_cb();
8866#endif
David Matlackcef84c32016-12-16 14:30:36 -08008867 kvm_lapic_exit();
Zhang, Yanminff9d07a2010-04-19 13:32:45 +08008868
Jan Kiszka888d2562009-04-17 19:24:58 +02008869 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8870 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
8871 CPUFREQ_TRANSITION_NOTIFIER);
Sebastian Andrzej Siewior251a5fd2016-07-13 17:16:33 +00008872 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008873#ifdef CONFIG_X86_64
8874 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
Thomas Gleixner3f804f62021-05-06 15:21:37 +02008875 irq_work_sync(&pvclock_irq_work);
Thomas Gleixner594b27e2021-05-05 23:48:17 +02008876 cancel_work_sync(&pvclock_gtod_work);
Marcelo Tosatti16e8d742012-11-27 23:29:00 -02008877#endif
Sean Christophersonafaf0b22020-03-21 13:26:00 -07008878 kvm_x86_ops.hardware_enable = NULL;
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008879 kvm_mmu_module_exit();
Sean Christopherson7e34fbd2020-09-23 11:03:55 -07008880 free_percpu(user_return_msrs);
Wanpeng Lidfdc0a72021-06-10 21:59:33 -07008881 kmem_cache_destroy(x86_emulator_cache);
Paolo Bonzinib59b1532021-02-26 04:54:45 -05008882#ifdef CONFIG_KVM_XEN
Paolo Bonzinic462f852021-02-26 04:49:06 -05008883 static_key_deferred_flush(&kvm_xen_enabled);
David Woodhouse7d6bbeb2021-02-02 15:48:05 +00008884 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
Paolo Bonzinib59b1532021-02-26 04:54:45 -05008885#endif
Zhang Xiantao56c6d282007-11-18 20:43:21 +08008886}
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08008887
Sean Christopherson14601792021-10-08 19:12:05 -07008888static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
Hollis Blanchard8776e512007-10-31 17:24:24 -05008889{
Sean Christopherson91b99ea2021-10-08 19:12:06 -07008890 /*
8891 * The vCPU has halted, e.g. executed HLT. Update the run state if the
8892 * local APIC is in-kernel, the run loop will detect the non-runnable
8893 * state and halt the vCPU. Exit to userspace if the local APIC is
8894 * managed by userspace, in which case userspace is responsible for
8895 * handling wake events.
8896 */
Hollis Blanchard8776e512007-10-31 17:24:24 -05008897 ++vcpu->stat.halt_exits;
Paolo Bonzini35754c92015-07-29 12:05:37 +02008898 if (lapic_in_kernel(vcpu)) {
Tom Lendacky647daca2021-01-04 14:20:01 -06008899 vcpu->arch.mp_state = state;
Hollis Blanchard8776e512007-10-31 17:24:24 -05008900 return 1;
8901 } else {
Tom Lendacky647daca2021-01-04 14:20:01 -06008902 vcpu->run->exit_reason = reason;
Hollis Blanchard8776e512007-10-31 17:24:24 -05008903 return 0;
8904 }
8905}
Tom Lendacky647daca2021-01-04 14:20:01 -06008906
Sean Christopherson14601792021-10-08 19:12:05 -07008907int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
Tom Lendacky647daca2021-01-04 14:20:01 -06008908{
Sean Christopherson14601792021-10-08 19:12:05 -07008909 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
Tom Lendacky647daca2021-01-04 14:20:01 -06008910}
Sean Christopherson14601792021-10-08 19:12:05 -07008911EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
Joel Schopp5cb56052015-03-02 13:43:31 -06008912
8913int kvm_emulate_halt(struct kvm_vcpu *vcpu)
8914{
Kyle Huey6affcbe2016-11-29 12:40:40 -08008915 int ret = kvm_skip_emulated_instruction(vcpu);
8916 /*
8917 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
8918 * KVM_EXIT_DEBUG here.
8919 */
Sean Christopherson14601792021-10-08 19:12:05 -07008920 return kvm_emulate_halt_noskip(vcpu) && ret;
Joel Schopp5cb56052015-03-02 13:43:31 -06008921}
Hollis Blanchard8776e512007-10-31 17:24:24 -05008922EXPORT_SYMBOL_GPL(kvm_emulate_halt);
8923
Tom Lendacky647daca2021-01-04 14:20:01 -06008924int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
8925{
8926 int ret = kvm_skip_emulated_instruction(vcpu);
8927
Sean Christopherson14601792021-10-08 19:12:05 -07008928 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
8929 KVM_EXIT_AP_RESET_HOLD) && ret;
Tom Lendacky647daca2021-01-04 14:20:01 -06008930}
8931EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
8932
Arnd Bergmann8ef81a92017-02-09 16:10:42 +01008933#ifdef CONFIG_X86_64
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02008934static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
8935 unsigned long clock_type)
8936{
8937 struct kvm_clock_pairing clock_pairing;
Arnd Bergmann899a31f2018-04-23 10:04:26 +02008938 struct timespec64 ts;
Paolo Bonzini80fbd892017-02-08 10:57:24 +01008939 u64 cycle;
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02008940 int ret;
8941
8942 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
8943 return -KVM_EOPNOTSUPP;
8944
YANG LI7ca7f3b2021-01-11 17:32:58 +08008945 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02008946 return -KVM_EOPNOTSUPP;
8947
8948 clock_pairing.sec = ts.tv_sec;
8949 clock_pairing.nsec = ts.tv_nsec;
8950 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
8951 clock_pairing.flags = 0;
Liran Alonbcbfbd82018-11-08 00:43:06 +02008952 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02008953
8954 ret = 0;
8955 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
8956 sizeof(struct kvm_clock_pairing)))
8957 ret = -KVM_EFAULT;
8958
8959 return ret;
8960}
Arnd Bergmann8ef81a92017-02-09 16:10:42 +01008961#endif
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02008962
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05308963/*
8964 * kvm_pv_kick_cpu_op: Kick a vcpu.
8965 *
8966 * @apicid - apicid of vcpu to be kicked.
8967 */
8968static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
8969{
Raghavendra K T24d21662013-08-26 14:18:35 +05308970 struct kvm_lapic_irq lapic_irq;
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05308971
Peter Xu150a84f2019-12-04 20:07:21 +01008972 lapic_irq.shorthand = APIC_DEST_NOSHORT;
Peter Xuc96001c2019-12-04 20:07:18 +01008973 lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
Longpeng(Mike)ebd28fc2017-08-02 11:20:51 +08008974 lapic_irq.level = 0;
Raghavendra K T24d21662013-08-26 14:18:35 +05308975 lapic_irq.dest_id = apicid;
James Sullivan93bbf0b2015-03-18 19:26:03 -06008976 lapic_irq.msi_redir_hint = false;
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05308977
Raghavendra K T24d21662013-08-26 14:18:35 +05308978 lapic_irq.delivery_mode = APIC_DM_REMRD;
Xiubo Li795a1492015-03-13 17:39:44 +08008979 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05308980}
8981
Suravee Suthikulpanit4e19c362019-11-14 14:15:05 -06008982bool kvm_apicv_activated(struct kvm *kvm)
8983{
8984 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
8985}
8986EXPORT_SYMBOL_GPL(kvm_apicv_activated);
8987
Vitaly Kuznetsov4651fc52021-06-09 17:09:09 +02008988static void kvm_apicv_init(struct kvm *kvm)
Suravee Suthikulpanit4e19c362019-11-14 14:15:05 -06008989{
Sean Christopherson187c8832021-10-21 17:49:27 -07008990 init_rwsem(&kvm->arch.apicv_update_lock);
Maxim Levitskyb0a16372021-08-10 23:52:44 +03008991
Paolo Bonzinief8b4b72021-11-30 07:37:45 -05008992 set_bit(APICV_INHIBIT_REASON_ABSENT,
8993 &kvm->arch.apicv_inhibit_reasons);
8994 if (!enable_apicv)
Suravee Suthikulpanit4e19c362019-11-14 14:15:05 -06008995 set_bit(APICV_INHIBIT_REASON_DISABLE,
8996 &kvm->arch.apicv_inhibit_reasons);
8997}
Suravee Suthikulpanit4e19c362019-11-14 14:15:05 -06008998
Wanpeng Li4a7132e2021-04-09 12:18:30 +08008999static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
Wanpeng Li71506292019-06-11 20:23:49 +08009000{
9001 struct kvm_vcpu *target = NULL;
9002 struct kvm_apic_map *map;
9003
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009004 vcpu->stat.directed_yield_attempted++;
9005
Wanpeng Li72b268a2021-05-18 05:00:32 -07009006 if (single_task_running())
9007 goto no_yield;
9008
Wanpeng Li71506292019-06-11 20:23:49 +08009009 rcu_read_lock();
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009010 map = rcu_dereference(vcpu->kvm->arch.apic_map);
Wanpeng Li71506292019-06-11 20:23:49 +08009011
9012 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
9013 target = map->phys_map[dest_id]->vcpu;
9014
9015 rcu_read_unlock();
9016
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009017 if (!target || !READ_ONCE(target->ready))
9018 goto no_yield;
9019
Wanpeng Lia1fa4cb2021-04-09 12:18:31 +08009020 /* Ignore requests to yield to self */
9021 if (vcpu == target)
9022 goto no_yield;
9023
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009024 if (kvm_vcpu_yield_to(target) <= 0)
9025 goto no_yield;
9026
9027 vcpu->stat.directed_yield_successful++;
9028
9029no_yield:
9030 return;
Wanpeng Li71506292019-06-11 20:23:49 +08009031}
9032
Ashish Kalra0dbb1122021-06-08 18:05:43 +00009033static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
9034{
9035 u64 ret = vcpu->run->hypercall.ret;
9036
9037 if (!is_64_bit_mode(vcpu))
9038 ret = (u32)ret;
9039 kvm_rax_write(vcpu, ret);
9040 ++vcpu->stat.hypercalls;
9041 return kvm_skip_emulated_instruction(vcpu);
9042}
9043
Hollis Blanchard8776e512007-10-31 17:24:24 -05009044int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
9045{
9046 unsigned long nr, a0, a1, a2, a3, ret;
Marian Rotariu6356ee02018-04-30 12:23:01 +03009047 int op_64_bit;
Hollis Blanchard8776e512007-10-31 17:24:24 -05009048
Joao Martins23200b72018-06-13 09:55:44 -04009049 if (kvm_xen_hypercall_enabled(vcpu->kvm))
9050 return kvm_xen_hypercall(vcpu);
9051
Vitaly Kuznetsov8f014552021-01-26 14:48:14 +01009052 if (kvm_hv_hypercall_enabled(vcpu))
Radim Krčmář696ca772018-05-24 17:50:56 +02009053 return kvm_hv_hypercall(vcpu);
Gleb Natapov55cd8e52010-01-17 15:51:22 +02009054
Sean Christophersonde3cd112019-04-30 10:36:17 -07009055 nr = kvm_rax_read(vcpu);
9056 a0 = kvm_rbx_read(vcpu);
9057 a1 = kvm_rcx_read(vcpu);
9058 a2 = kvm_rdx_read(vcpu);
9059 a3 = kvm_rsi_read(vcpu);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009060
Marcelo Tosatti229456f2009-06-17 09:22:14 -03009061 trace_kvm_hypercall(nr, a0, a1, a2, a3);
Feng (Eric) Liu2714d1d2008-04-10 15:31:10 -04009062
Tom Lendackyb5aead02021-05-24 12:48:57 -05009063 op_64_bit = is_64_bit_hypercall(vcpu);
Nadav Amita449c7a2014-06-18 17:19:24 +03009064 if (!op_64_bit) {
Hollis Blanchard8776e512007-10-31 17:24:24 -05009065 nr &= 0xFFFFFFFF;
9066 a0 &= 0xFFFFFFFF;
9067 a1 &= 0xFFFFFFFF;
9068 a2 &= 0xFFFFFFFF;
9069 a3 &= 0xFFFFFFFF;
9070 }
9071
Jason Baronb36464772021-01-14 22:27:56 -05009072 if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
Jan Kiszka07708c42009-08-03 18:43:28 +02009073 ret = -KVM_EPERM;
Radim Krčmář696ca772018-05-24 17:50:56 +02009074 goto out;
Jan Kiszka07708c42009-08-03 18:43:28 +02009075 }
9076
Oliver Upton66570e92020-08-18 15:24:28 +00009077 ret = -KVM_ENOSYS;
9078
Hollis Blanchard8776e512007-10-31 17:24:24 -05009079 switch (nr) {
Avi Kivityb93463a2007-10-25 16:52:32 +02009080 case KVM_HC_VAPIC_POLL_IRQ:
9081 ret = 0;
9082 break;
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05309083 case KVM_HC_KICK_CPU:
Oliver Upton66570e92020-08-18 15:24:28 +00009084 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
9085 break;
9086
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05309087 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009088 kvm_sched_yield(vcpu, a1);
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +05309089 ret = 0;
9090 break;
Arnd Bergmann8ef81a92017-02-09 16:10:42 +01009091#ifdef CONFIG_X86_64
Marcelo Tosatti55dd00a2017-01-24 15:09:39 -02009092 case KVM_HC_CLOCK_PAIRING:
9093 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
9094 break;
Sean Christopherson1ed199a2019-01-23 09:22:39 -08009095#endif
Wanpeng Li4180bf12018-07-23 14:39:54 +08009096 case KVM_HC_SEND_IPI:
Oliver Upton66570e92020-08-18 15:24:28 +00009097 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
9098 break;
9099
Wanpeng Li4180bf12018-07-23 14:39:54 +08009100 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
9101 break;
Wanpeng Li71506292019-06-11 20:23:49 +08009102 case KVM_HC_SCHED_YIELD:
Oliver Upton66570e92020-08-18 15:24:28 +00009103 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
9104 break;
9105
Wanpeng Li4a7132e2021-04-09 12:18:30 +08009106 kvm_sched_yield(vcpu, a0);
Wanpeng Li71506292019-06-11 20:23:49 +08009107 ret = 0;
9108 break;
Ashish Kalra0dbb1122021-06-08 18:05:43 +00009109 case KVM_HC_MAP_GPA_RANGE: {
9110 u64 gpa = a0, npages = a1, attrs = a2;
9111
9112 ret = -KVM_ENOSYS;
9113 if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
9114 break;
9115
9116 if (!PAGE_ALIGNED(gpa) || !npages ||
9117 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
9118 ret = -KVM_EINVAL;
9119 break;
9120 }
9121
9122 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
9123 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
9124 vcpu->run->hypercall.args[0] = gpa;
9125 vcpu->run->hypercall.args[1] = npages;
9126 vcpu->run->hypercall.args[2] = attrs;
9127 vcpu->run->hypercall.longmode = op_64_bit;
9128 vcpu->arch.complete_userspace_io = complete_hypercall_exit;
9129 return 0;
9130 }
Hollis Blanchard8776e512007-10-31 17:24:24 -05009131 default:
9132 ret = -KVM_ENOSYS;
9133 break;
9134 }
Radim Krčmář696ca772018-05-24 17:50:56 +02009135out:
Nadav Amita449c7a2014-06-18 17:19:24 +03009136 if (!op_64_bit)
9137 ret = (u32)ret;
Sean Christophersonde3cd112019-04-30 10:36:17 -07009138 kvm_rax_write(vcpu, ret);
Marian Rotariu6356ee02018-04-30 12:23:01 +03009139
Amit Shahf11c3a82008-02-21 01:00:30 +05309140 ++vcpu->stat.hypercalls;
Marian Rotariu6356ee02018-04-30 12:23:01 +03009141 return kvm_skip_emulated_instruction(vcpu);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009142}
9143EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
9144
Jan Kiszkab6785de2012-09-20 07:43:17 +02009145static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
Hollis Blanchard8776e512007-10-31 17:24:24 -05009146{
Avi Kivityd6aa1002011-04-20 15:47:13 +03009147 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009148 char instruction[3];
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -03009149 unsigned long rip = kvm_rip_read(vcpu);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009150
Jason Baronb36464772021-01-14 22:27:56 -05009151 static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009152
Dmitry Vyukovce2e8522017-01-17 14:51:04 +01009153 return emulator_write_emulated(ctxt, rip, instruction, 3,
9154 &ctxt->exception);
Hollis Blanchard8776e512007-10-31 17:24:24 -05009155}
9156
Avi Kivity851ba692009-08-24 11:10:17 +03009157static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009158{
Matt Gingell782d4222015-11-16 15:26:00 -08009159 return vcpu->run->request_interrupt_window &&
9160 likely(!pic_in_kernel(vcpu->kvm));
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009161}
9162
Avi Kivity851ba692009-08-24 11:10:17 +03009163static void post_kvm_run_save(struct kvm_vcpu *vcpu)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009164{
Avi Kivity851ba692009-08-24 11:10:17 +03009165 struct kvm_run *kvm_run = vcpu->run;
9166
Marc Orrc5063552021-12-09 07:52:57 -08009167 kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
Avi Kivity2d3ad1f2008-02-24 11:20:43 +02009168 kvm_run->cr8 = kvm_get_cr8(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009169 kvm_run->apic_base = kvm_get_apic_base(vcpu);
David Woodhousef3d14362021-10-26 04:12:38 +01009170
9171 /*
9172 * The call to kvm_ready_for_interrupt_injection() may end up in
9173 * kvm_xen_has_interrupt() which may require the srcu lock to be
9174 * held, to protect against changes in the vcpu_info address.
9175 */
9176 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
Matt Gingell127a4572015-11-17 17:32:05 +01009177 kvm_run->ready_for_interrupt_injection =
9178 pic_in_kernel(vcpu->kvm) ||
Matt Gingell782d4222015-11-16 15:26:00 -08009179 kvm_vcpu_ready_for_interrupt_injection(vcpu);
David Woodhousef3d14362021-10-26 04:12:38 +01009180 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
Chenyi Qiang15aad3b2020-11-06 17:03:13 +08009181
9182 if (is_smm(vcpu))
9183 kvm_run->flags |= KVM_RUN_X86_SMM;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009184}
9185
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009186static void update_cr8_intercept(struct kvm_vcpu *vcpu)
9187{
9188 int max_irr, tpr;
9189
Sean Christophersonafaf0b22020-03-21 13:26:00 -07009190 if (!kvm_x86_ops.update_cr8_intercept)
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009191 return;
9192
Paolo Bonzinibce87cc2016-01-08 13:48:51 +01009193 if (!lapic_in_kernel(vcpu))
Avi Kivity88c808f2009-08-17 22:49:40 +03009194 return;
9195
Andrey Smetanind62caab2015-11-10 15:36:33 +03009196 if (vcpu->arch.apicv_active)
9197 return;
9198
Gleb Natapov8db3baa2009-05-11 13:35:54 +03009199 if (!vcpu->arch.apic->vapic_addr)
9200 max_irr = kvm_lapic_find_highest_irr(vcpu);
9201 else
9202 max_irr = -1;
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009203
9204 if (max_irr != -1)
9205 max_irr >>= 4;
9206
9207 tpr = kvm_lapic_get_cr8(vcpu);
9208
Jason Baronb36464772021-01-14 22:27:56 -05009209 static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009210}
9211
Maxim Levitskyb97f0742021-02-25 17:41:32 +02009212
Sean Christophersoncb6a32c2021-03-02 09:45:14 -08009213int kvm_check_nested_events(struct kvm_vcpu *vcpu)
9214{
Sean Christophersoncb6a32c2021-03-02 09:45:14 -08009215 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
9216 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9217 return 1;
9218 }
9219
9220 return kvm_x86_ops.nested_ops->check_events(vcpu);
9221}
9222
Maxim Levitskyb97f0742021-02-25 17:41:32 +02009223static void kvm_inject_exception(struct kvm_vcpu *vcpu)
9224{
9225 if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
9226 vcpu->arch.exception.error_code = false;
9227 static_call(kvm_x86_queue_exception)(vcpu);
9228}
9229
Jim Mattsona5f69092021-06-04 10:26:03 -07009230static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009231{
Jan Kiszkab6b8a142014-03-07 20:03:12 +01009232 int r;
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009233 bool can_inject = true;
Jan Kiszkab6b8a142014-03-07 20:03:12 +01009234
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009235 /* try to reinject previous events if any */
Wanpeng Li664f8e22017-08-24 03:35:09 -07009236
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009237 if (vcpu->arch.exception.injected) {
Maxim Levitskyb97f0742021-02-25 17:41:32 +02009238 kvm_inject_exception(vcpu);
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009239 can_inject = false;
9240 }
Wanpeng Li664f8e22017-08-24 03:35:09 -07009241 /*
Liran Alona042c262018-03-23 03:01:32 +03009242 * Do not inject an NMI or interrupt if there is a pending
9243 * exception. Exceptions and interrupts are recognized at
9244 * instruction boundaries, i.e. the start of an instruction.
9245 * Trap-like exceptions, e.g. #DB, have higher priority than
9246 * NMIs and interrupts, i.e. traps are recognized before an
9247 * NMI/interrupt that's pending on the same instruction.
9248 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
9249 * priority, but are only generated (pended) during instruction
9250 * execution, i.e. a pending fault-like exception means the
9251 * fault occurred on the *previous* instruction and must be
9252 * serviced prior to recognizing any new events in order to
9253 * fully complete the previous instruction.
Wanpeng Li664f8e22017-08-24 03:35:09 -07009254 */
Liran Alon1a680e32018-03-23 03:01:33 +03009255 else if (!vcpu->arch.exception.pending) {
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009256 if (vcpu->arch.nmi_injected) {
Jason Baronb36464772021-01-14 22:27:56 -05009257 static_call(kvm_x86_set_nmi)(vcpu);
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009258 can_inject = false;
9259 } else if (vcpu->arch.interrupt.injected) {
Jason Baronb36464772021-01-14 22:27:56 -05009260 static_call(kvm_x86_set_irq)(vcpu);
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009261 can_inject = false;
9262 }
Wanpeng Li664f8e22017-08-24 03:35:09 -07009263 }
9264
Sean Christopherson3b82b8d2020-04-22 19:25:47 -07009265 WARN_ON_ONCE(vcpu->arch.exception.injected &&
9266 vcpu->arch.exception.pending);
9267
Liran Alon1a680e32018-03-23 03:01:33 +03009268 /*
9269 * Call check_nested_events() even if we reinjected a previous event
9270 * in order for caller to determine if it should require immediate-exit
9271 * from L2 to L1 due to pending L1 events which require exit
9272 * from L2 to L1.
9273 */
Paolo Bonzini56083bd2020-04-17 10:32:53 -04009274 if (is_guest_mode(vcpu)) {
Sean Christophersoncb6a32c2021-03-02 09:45:14 -08009275 r = kvm_check_nested_events(vcpu);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009276 if (r < 0)
Jim Mattsona5f69092021-06-04 10:26:03 -07009277 goto out;
Wanpeng Li664f8e22017-08-24 03:35:09 -07009278 }
9279
9280 /* try to inject new event if pending */
Gleb Natapovb59bb7b2009-07-09 15:33:51 +03009281 if (vcpu->arch.exception.pending) {
Avi Kivity5c1c85d02010-03-11 13:01:59 +02009282 trace_kvm_inj_exception(vcpu->arch.exception.nr,
9283 vcpu->arch.exception.has_error_code,
9284 vcpu->arch.exception.error_code);
Nadav Amitd6e8c852014-07-24 14:51:24 +03009285
Wanpeng Li664f8e22017-08-24 03:35:09 -07009286 vcpu->arch.exception.pending = false;
9287 vcpu->arch.exception.injected = true;
9288
Nadav Amitd6e8c852014-07-24 14:51:24 +03009289 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
9290 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
9291 X86_EFLAGS_RF);
9292
Jim Mattsonf10c7292018-10-16 14:29:23 -07009293 if (vcpu->arch.exception.nr == DB_VECTOR) {
Jim Mattsonf10c7292018-10-16 14:29:23 -07009294 kvm_deliver_exception_payload(vcpu);
9295 if (vcpu->arch.dr7 & DR7_GD) {
9296 vcpu->arch.dr7 &= ~DR7_GD;
9297 kvm_update_dr7(vcpu);
9298 }
Nadav Amit6bdf0662014-09-30 20:49:14 +03009299 }
9300
Maxim Levitskyb97f0742021-02-25 17:41:32 +02009301 kvm_inject_exception(vcpu);
Paolo Bonzinic6b22f52020-05-26 09:05:27 -04009302 can_inject = false;
Liran Alon1a680e32018-03-23 03:01:33 +03009303 }
9304
Maxim Levitsky61e5f692021-08-11 15:29:26 +03009305 /* Don't inject interrupts if the user asked to avoid doing so */
9306 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
9307 return 0;
9308
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009309 /*
9310 * Finally, inject interrupt events. If an event cannot be injected
9311 * due to architectural conditions (e.g. IF=0) a window-open exit
9312 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
9313 * and can architecturally be injected, but we cannot do it right now:
9314 * an interrupt could have arrived just now and we have to inject it
9315 * as a vmexit, or there could already an event in the queue, which is
9316 * indicated by can_inject. In that case we request an immediate exit
9317 * in order to make progress and get back here for another iteration.
9318 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
9319 */
9320 if (vcpu->arch.smi_pending) {
Jason Baronb36464772021-01-14 22:27:56 -05009321 r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009322 if (r < 0)
Jim Mattsona5f69092021-06-04 10:26:03 -07009323 goto out;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009324 if (r) {
9325 vcpu->arch.smi_pending = false;
9326 ++vcpu->arch.smi_count;
9327 enter_smm(vcpu);
9328 can_inject = false;
9329 } else
Jason Baronb36464772021-01-14 22:27:56 -05009330 static_call(kvm_x86_enable_smi_window)(vcpu);
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009331 }
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009332
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009333 if (vcpu->arch.nmi_pending) {
Jason Baronb36464772021-01-14 22:27:56 -05009334 r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009335 if (r < 0)
Jim Mattsona5f69092021-06-04 10:26:03 -07009336 goto out;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009337 if (r) {
9338 --vcpu->arch.nmi_pending;
9339 vcpu->arch.nmi_injected = true;
Jason Baronb36464772021-01-14 22:27:56 -05009340 static_call(kvm_x86_set_nmi)(vcpu);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009341 can_inject = false;
Jason Baronb36464772021-01-14 22:27:56 -05009342 WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009343 }
9344 if (vcpu->arch.nmi_pending)
Jason Baronb36464772021-01-14 22:27:56 -05009345 static_call(kvm_x86_enable_nmi_window)(vcpu);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009346 }
9347
9348 if (kvm_cpu_has_injectable_intr(vcpu)) {
Jason Baronb36464772021-01-14 22:27:56 -05009349 r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009350 if (r < 0)
Jim Mattsona5f69092021-06-04 10:26:03 -07009351 goto out;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009352 if (r) {
9353 kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
Jason Baronb36464772021-01-14 22:27:56 -05009354 static_call(kvm_x86_set_irq)(vcpu);
9355 WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009356 }
9357 if (kvm_cpu_has_injectable_intr(vcpu))
Jason Baronb36464772021-01-14 22:27:56 -05009358 static_call(kvm_x86_enable_irq_window)(vcpu);
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009359 }
9360
9361 if (is_guest_mode(vcpu) &&
9362 kvm_x86_ops.nested_ops->hv_timer_pending &&
9363 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
9364 *req_immediate_exit = true;
9365
9366 WARN_ON(vcpu->arch.exception.pending);
Jim Mattsona5f69092021-06-04 10:26:03 -07009367 return 0;
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009368
Jim Mattsona5f69092021-06-04 10:26:03 -07009369out:
9370 if (r == -EBUSY) {
9371 *req_immediate_exit = true;
9372 r = 0;
9373 }
9374 return r;
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009375}
9376
Avi Kivity7460fb4a2011-09-20 13:43:14 +03009377static void process_nmi(struct kvm_vcpu *vcpu)
9378{
9379 unsigned limit = 2;
9380
9381 /*
9382 * x86 is limited to one NMI running, and one NMI pending after it.
9383 * If an NMI is already in progress, limit further NMIs to just one.
9384 * Otherwise, allow two (and we'll inject the first one immediately).
9385 */
Jason Baronb36464772021-01-14 22:27:56 -05009386 if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
Avi Kivity7460fb4a2011-09-20 13:43:14 +03009387 limit = 1;
9388
9389 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
9390 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
9391 kvm_make_request(KVM_REQ_EVENT, vcpu);
9392}
9393
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009394static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009395{
9396 u32 flags = 0;
9397 flags |= seg->g << 23;
9398 flags |= seg->db << 22;
9399 flags |= seg->l << 21;
9400 flags |= seg->avl << 20;
9401 flags |= seg->present << 15;
9402 flags |= seg->dpl << 13;
9403 flags |= seg->s << 12;
9404 flags |= seg->type << 8;
9405 return flags;
9406}
9407
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009408static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009409{
9410 struct kvm_segment seg;
9411 int offset;
9412
9413 kvm_get_segment(vcpu, &seg, n);
9414 put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
9415
9416 if (n < 3)
9417 offset = 0x7f84 + n * 12;
9418 else
9419 offset = 0x7f2c + (n - 3) * 12;
9420
9421 put_smstate(u32, buf, offset + 8, seg.base);
9422 put_smstate(u32, buf, offset + 4, seg.limit);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009423 put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009424}
9425
Alexander Kuleshovefbb2882015-09-06 19:35:41 +06009426#ifdef CONFIG_X86_64
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009427static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009428{
9429 struct kvm_segment seg;
9430 int offset;
9431 u16 flags;
9432
9433 kvm_get_segment(vcpu, &seg, n);
9434 offset = 0x7e00 + n * 16;
9435
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009436 flags = enter_smm_get_segment_flags(&seg) >> 8;
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009437 put_smstate(u16, buf, offset, seg.selector);
9438 put_smstate(u16, buf, offset + 2, flags);
9439 put_smstate(u32, buf, offset + 4, seg.limit);
9440 put_smstate(u64, buf, offset + 8, seg.base);
9441}
Alexander Kuleshovefbb2882015-09-06 19:35:41 +06009442#endif
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009443
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009444static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009445{
9446 struct desc_ptr dt;
9447 struct kvm_segment seg;
9448 unsigned long val;
9449 int i;
9450
9451 put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
9452 put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
9453 put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
9454 put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
9455
9456 for (i = 0; i < 8; i++)
Sean Christopherson27b4a9c42021-04-21 19:21:28 -07009457 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read_raw(vcpu, i));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009458
9459 kvm_get_dr(vcpu, 6, &val);
9460 put_smstate(u32, buf, 0x7fcc, (u32)val);
9461 kvm_get_dr(vcpu, 7, &val);
9462 put_smstate(u32, buf, 0x7fc8, (u32)val);
9463
9464 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
9465 put_smstate(u32, buf, 0x7fc4, seg.selector);
9466 put_smstate(u32, buf, 0x7f64, seg.base);
9467 put_smstate(u32, buf, 0x7f60, seg.limit);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009468 put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009469
9470 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
9471 put_smstate(u32, buf, 0x7fc0, seg.selector);
9472 put_smstate(u32, buf, 0x7f80, seg.base);
9473 put_smstate(u32, buf, 0x7f7c, seg.limit);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009474 put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009475
Jason Baronb36464772021-01-14 22:27:56 -05009476 static_call(kvm_x86_get_gdt)(vcpu, &dt);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009477 put_smstate(u32, buf, 0x7f74, dt.address);
9478 put_smstate(u32, buf, 0x7f70, dt.size);
9479
Jason Baronb36464772021-01-14 22:27:56 -05009480 static_call(kvm_x86_get_idt)(vcpu, &dt);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009481 put_smstate(u32, buf, 0x7f58, dt.address);
9482 put_smstate(u32, buf, 0x7f54, dt.size);
9483
9484 for (i = 0; i < 6; i++)
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009485 enter_smm_save_seg_32(vcpu, buf, i);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009486
9487 put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
9488
9489 /* revision id */
9490 put_smstate(u32, buf, 0x7efc, 0x00020000);
9491 put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
9492}
9493
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009494#ifdef CONFIG_X86_64
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009495static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009496{
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009497 struct desc_ptr dt;
9498 struct kvm_segment seg;
9499 unsigned long val;
9500 int i;
9501
9502 for (i = 0; i < 16; i++)
Sean Christopherson27b4a9c42021-04-21 19:21:28 -07009503 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read_raw(vcpu, i));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009504
9505 put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
9506 put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
9507
9508 kvm_get_dr(vcpu, 6, &val);
9509 put_smstate(u64, buf, 0x7f68, val);
9510 kvm_get_dr(vcpu, 7, &val);
9511 put_smstate(u64, buf, 0x7f60, val);
9512
9513 put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
9514 put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
9515 put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
9516
9517 put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
9518
9519 /* revision id */
9520 put_smstate(u32, buf, 0x7efc, 0x00020064);
9521
9522 put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
9523
9524 kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
9525 put_smstate(u16, buf, 0x7e90, seg.selector);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009526 put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009527 put_smstate(u32, buf, 0x7e94, seg.limit);
9528 put_smstate(u64, buf, 0x7e98, seg.base);
9529
Jason Baronb36464772021-01-14 22:27:56 -05009530 static_call(kvm_x86_get_idt)(vcpu, &dt);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009531 put_smstate(u32, buf, 0x7e84, dt.size);
9532 put_smstate(u64, buf, 0x7e88, dt.address);
9533
9534 kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
9535 put_smstate(u16, buf, 0x7e70, seg.selector);
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009536 put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009537 put_smstate(u32, buf, 0x7e74, seg.limit);
9538 put_smstate(u64, buf, 0x7e78, seg.base);
9539
Jason Baronb36464772021-01-14 22:27:56 -05009540 static_call(kvm_x86_get_gdt)(vcpu, &dt);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009541 put_smstate(u32, buf, 0x7e64, dt.size);
9542 put_smstate(u64, buf, 0x7e68, dt.address);
9543
9544 for (i = 0; i < 6; i++)
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009545 enter_smm_save_seg_64(vcpu, buf, i);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009546}
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009547#endif
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009548
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009549static void enter_smm(struct kvm_vcpu *vcpu)
Paolo Bonzini64d60672015-05-07 11:36:11 +02009550{
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009551 struct kvm_segment cs, ds;
Paolo Bonzini18c36262015-08-07 12:27:54 +02009552 struct desc_ptr dt;
Sean Christophersondbc47392021-06-22 10:56:59 -07009553 unsigned long cr0;
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009554 char buf[512];
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009555
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009556 memset(buf, 0, 512);
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009557#ifdef CONFIG_X86_64
Radim Krčmářd6321d42017-08-05 00:12:49 +02009558 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009559 enter_smm_save_state_64(vcpu, buf);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009560 else
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009561#endif
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009562 enter_smm_save_state_32(vcpu, buf);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009563
Ladi Prosek0234bf82017-10-11 16:54:40 +02009564 /*
Sean Christophersonecc513e2021-06-09 11:56:19 -07009565 * Give enter_smm() a chance to make ISA-specific changes to the vCPU
9566 * state (e.g. leave guest mode) after we've saved the state into the
9567 * SMM state-save area.
Ladi Prosek0234bf82017-10-11 16:54:40 +02009568 */
Sean Christophersonecc513e2021-06-09 11:56:19 -07009569 static_call(kvm_x86_enter_smm)(vcpu, buf);
Ladi Prosek0234bf82017-10-11 16:54:40 +02009570
Sean Christophersondc872752021-06-09 11:56:15 -07009571 kvm_smm_changed(vcpu, true);
Paolo Bonzini54bf36a2015-04-08 15:39:23 +02009572 kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009573
Jason Baronb36464772021-01-14 22:27:56 -05009574 if (static_call(kvm_x86_get_nmi_mask)(vcpu))
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009575 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
9576 else
Jason Baronb36464772021-01-14 22:27:56 -05009577 static_call(kvm_x86_set_nmi_mask)(vcpu, true);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009578
9579 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
9580 kvm_rip_write(vcpu, 0x8000);
9581
9582 cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
Jason Baronb36464772021-01-14 22:27:56 -05009583 static_call(kvm_x86_set_cr0)(vcpu, cr0);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009584 vcpu->arch.cr0 = cr0;
9585
Jason Baronb36464772021-01-14 22:27:56 -05009586 static_call(kvm_x86_set_cr4)(vcpu, 0);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009587
Paolo Bonzini18c36262015-08-07 12:27:54 +02009588 /* Undocumented: IDT limit is set to zero on entry to SMM. */
9589 dt.address = dt.size = 0;
Jason Baronb36464772021-01-14 22:27:56 -05009590 static_call(kvm_x86_set_idt)(vcpu, &dt);
Paolo Bonzini18c36262015-08-07 12:27:54 +02009591
Paolo Bonzini996ff542020-12-14 07:49:54 -05009592 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009593
9594 cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
9595 cs.base = vcpu->arch.smbase;
9596
9597 ds.selector = 0;
9598 ds.base = 0;
9599
9600 cs.limit = ds.limit = 0xffffffff;
9601 cs.type = ds.type = 0x3;
9602 cs.dpl = ds.dpl = 0;
9603 cs.db = ds.db = 0;
9604 cs.s = ds.s = 1;
9605 cs.l = ds.l = 0;
9606 cs.g = ds.g = 1;
9607 cs.avl = ds.avl = 0;
9608 cs.present = ds.present = 1;
9609 cs.unusable = ds.unusable = 0;
9610 cs.padding = ds.padding = 0;
9611
9612 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9613 kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
9614 kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
9615 kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
9616 kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
9617 kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
9618
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009619#ifdef CONFIG_X86_64
Radim Krčmářd6321d42017-08-05 00:12:49 +02009620 if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
Jason Baronb36464772021-01-14 22:27:56 -05009621 static_call(kvm_x86_set_efer)(vcpu, 0);
Sean Christophersonb68f3cc2019-04-02 08:10:48 -07009622#endif
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009623
Xiaoyao Liaedbaf42020-07-09 12:34:23 +08009624 kvm_update_cpuid_runtime(vcpu);
Paolo Bonzini660a5d52015-05-05 11:50:23 +02009625 kvm_mmu_reset_context(vcpu);
Paolo Bonzini64d60672015-05-07 11:36:11 +02009626}
9627
Paolo Bonziniee2cd4b2016-06-01 22:26:01 +02009628static void process_smi(struct kvm_vcpu *vcpu)
Paolo Bonzinic43203c2016-06-01 22:26:00 +02009629{
9630 vcpu->arch.smi_pending = true;
9631 kvm_make_request(KVM_REQ_EVENT, vcpu);
9632}
9633
Nitesh Narayan Lal7ee30bc2019-11-07 07:53:43 -05009634void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
9635 unsigned long *vcpu_bitmap)
9636{
Vitaly Kuznetsov620b2432021-09-03 09:51:41 +02009637 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
Nitesh Narayan Lal7ee30bc2019-11-07 07:53:43 -05009638}
9639
Paolo Bonzini2860c4b2016-01-07 15:05:10 +01009640void kvm_make_scan_ioapic_request(struct kvm *kvm)
9641{
9642 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
9643}
9644
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009645void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
9646{
Maxim Levitsky06ef8132021-08-10 23:52:48 +03009647 bool activate;
9648
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009649 if (!lapic_in_kernel(vcpu))
9650 return;
9651
Sean Christopherson187c8832021-10-21 17:49:27 -07009652 down_read(&vcpu->kvm->arch.apicv_update_lock);
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009653
Maxim Levitsky06ef8132021-08-10 23:52:48 +03009654 activate = kvm_apicv_activated(vcpu->kvm);
9655 if (vcpu->arch.apicv_active == activate)
9656 goto out;
9657
9658 vcpu->arch.apicv_active = activate;
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009659 kvm_apic_update_apicv(vcpu);
Jason Baronb36464772021-01-14 22:27:56 -05009660 static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
Vitaly Kuznetsovbca66db2021-06-09 17:09:10 +02009661
9662 /*
9663 * When APICv gets disabled, we may still have injected interrupts
9664 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
9665 * still active when the interrupt got accepted. Make sure
9666 * inject_pending_event() is called to check for that.
9667 */
9668 if (!vcpu->arch.apicv_active)
9669 kvm_make_request(KVM_REQ_EVENT, vcpu);
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009670
Maxim Levitsky06ef8132021-08-10 23:52:48 +03009671out:
Sean Christopherson187c8832021-10-21 17:49:27 -07009672 up_read(&vcpu->kvm->arch.apicv_update_lock);
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009673}
9674EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
9675
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009676void __kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009677{
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009678 unsigned long old, new;
Paolo Bonzini8e205a62020-03-14 12:29:23 +01009679
Sean Christopherson187c8832021-10-21 17:49:27 -07009680 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
9681
Sean Christophersonafaf0b22020-03-21 13:26:00 -07009682 if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
Jason Baronb36464772021-01-14 22:27:56 -05009683 !static_call(kvm_x86_check_apicv_inhibit_reasons)(bit))
Suravee Suthikulpanitef8efd72019-11-14 14:15:10 -06009684 return;
9685
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009686 old = new = kvm->arch.apicv_inhibit_reasons;
9687
9688 if (activate)
9689 __clear_bit(bit, &new);
9690 else
9691 __set_bit(bit, &new);
Paolo Bonzini8e205a62020-03-14 12:29:23 +01009692
Maxim Levitsky36222b12021-08-10 23:52:43 +03009693 if (!!old != !!new) {
9694 trace_kvm_apicv_update_request(activate, bit);
Sean Christophersonee49a892021-10-21 17:49:25 -07009695 /*
9696 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
9697 * false positives in the sanity check WARN in svm_vcpu_run().
9698 * This task will wait for all vCPUs to ack the kick IRQ before
9699 * updating apicv_inhibit_reasons, and all other vCPUs will
9700 * block on acquiring apicv_update_lock so that vCPUs can't
9701 * redo svm_vcpu_run() without seeing the new inhibit state.
9702 *
9703 * Note, holding apicv_update_lock and taking it in the read
9704 * side (handling the request) also prevents other vCPUs from
9705 * servicing the request with a stale apicv_inhibit_reasons.
9706 */
Maxim Levitsky36222b12021-08-10 23:52:43 +03009707 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009708 kvm->arch.apicv_inhibit_reasons = new;
Maxim Levitsky36222b12021-08-10 23:52:43 +03009709 if (new) {
9710 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
Maxim Levitsky36222b12021-08-10 23:52:43 +03009711 kvm_zap_gfn_range(kvm, gfn, gfn+1);
9712 }
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009713 } else
9714 kvm->arch.apicv_inhibit_reasons = new;
9715}
9716EXPORT_SYMBOL_GPL(__kvm_request_apicv_update);
Suravee Suthikulpanit7d611232020-05-06 21:35:39 -05009717
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009718void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
9719{
Sean Christopherson187c8832021-10-21 17:49:27 -07009720 down_write(&kvm->arch.apicv_update_lock);
Maxim Levitskyb0a16372021-08-10 23:52:44 +03009721 __kvm_request_apicv_update(kvm, activate, bit);
Sean Christopherson187c8832021-10-21 17:49:27 -07009722 up_write(&kvm->arch.apicv_update_lock);
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009723}
9724EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
9725
Yang Zhang3d81bc72013-04-11 19:25:13 +08009726static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
Yang Zhangc7c9c562013-01-25 10:18:51 +08009727{
Wanpeng Lidcbd3e42018-12-17 10:43:23 +08009728 if (!kvm_apic_present(vcpu))
Yang Zhang3d81bc72013-04-11 19:25:13 +08009729 return;
Yang Zhangc7c9c562013-01-25 10:18:51 +08009730
Andrey Smetanin63086302015-11-10 15:36:32 +03009731 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
Yang Zhangc7c9c562013-01-25 10:18:51 +08009732
Steve Rutherfordb053b2a2015-07-29 23:32:35 -07009733 if (irqchip_split(vcpu->kvm))
Andrey Smetanin63086302015-11-10 15:36:32 +03009734 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
Radim Krčmářdb2bdcb2015-10-08 20:23:34 +02009735 else {
Paolo Bonzini37c4dbf2021-11-22 19:43:10 -05009736 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
Wanpeng Lie97f8522018-11-20 16:34:18 +08009737 if (ioapic_in_kernel(vcpu->kvm))
9738 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
Radim Krčmářdb2bdcb2015-10-08 20:23:34 +02009739 }
Liran Alone40ff1d2018-03-21 02:50:31 +02009740
9741 if (is_guest_mode(vcpu))
9742 vcpu->arch.load_eoi_exitmap_pending = true;
9743 else
9744 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
9745}
9746
9747static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
9748{
9749 u64 eoi_exit_bitmap[4];
9750
9751 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
9752 return;
9753
黄乐c5adbb3a2021-11-15 14:08:29 +00009754 if (to_hv_vcpu(vcpu)) {
Vitaly Kuznetsovf2bc14b2021-01-26 14:48:12 +01009755 bitmap_or((ulong *)eoi_exit_bitmap,
9756 vcpu->arch.ioapic_handled_vectors,
9757 to_hv_synic(vcpu)->vec_bitmap, 256);
黄乐c5adbb3a2021-11-15 14:08:29 +00009758 static_call(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
9759 return;
9760 }
Vitaly Kuznetsovf2bc14b2021-01-26 14:48:12 +01009761
黄乐c5adbb3a2021-11-15 14:08:29 +00009762 static_call(kvm_x86_load_eoi_exitmap)(
9763 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
Yang Zhangc7c9c562013-01-25 10:18:51 +08009764}
9765
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +09009766void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
9767 unsigned long start, unsigned long end)
Radim Krčmářb1394e72017-11-30 19:05:45 +01009768{
9769 unsigned long apic_address;
9770
9771 /*
9772 * The physical address of apic access page is stored in the VMCS.
9773 * Update it when it becomes invalid.
9774 */
9775 apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
9776 if (start <= apic_address && apic_address < end)
9777 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
9778}
9779
Quanfa Fud081a342021-12-19 17:14:46 +08009780static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
Tang Chen4256f432014-09-24 15:57:54 +08009781{
Paolo Bonzini35754c92015-07-29 12:05:37 +02009782 if (!lapic_in_kernel(vcpu))
Paolo Bonzinif439ed22014-10-02 13:53:24 +02009783 return;
9784
Sean Christophersonafaf0b22020-03-21 13:26:00 -07009785 if (!kvm_x86_ops.set_apic_access_page_addr)
Tang Chen4256f432014-09-24 15:57:54 +08009786 return;
9787
Jason Baronb36464772021-01-14 22:27:56 -05009788 static_call(kvm_x86_set_apic_access_page_addr)(vcpu);
Tang Chen4256f432014-09-24 15:57:54 +08009789}
Tang Chen4256f432014-09-24 15:57:54 +08009790
Sean Christophersond264ee02018-08-27 15:21:12 -07009791void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
9792{
9793 smp_send_reschedule(vcpu->cpu);
9794}
9795EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
9796
Takuya Yoshikawa9357d932013-12-13 15:08:38 +09009797/*
Paolo Bonzini362c6982015-02-06 12:48:04 +01009798 * Returns 1 to let vcpu_run() continue the guest execution loop without
Takuya Yoshikawa9357d932013-12-13 15:08:38 +09009799 * exiting to the userspace. Otherwise, the value will be returned to the
9800 * userspace.
9801 */
Avi Kivity851ba692009-08-24 11:10:17 +03009802static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009803{
9804 int r;
Matt Gingell62a193e2015-11-16 15:26:07 -08009805 bool req_int_win =
9806 dm_request_for_irq_injection(vcpu) &&
9807 kvm_cpu_accept_dm_intr(vcpu);
Wanpeng Li404d5d72020-04-28 14:23:25 +08009808 fastpath_t exit_fastpath;
Matt Gingell62a193e2015-11-16 15:26:07 -08009809
Jan Kiszka730dca42013-04-28 10:50:52 +02009810 bool req_immediate_exit = false;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05009811
Peter Xufb04a1e2020-09-30 21:22:22 -04009812 /* Forbid vmenter if vcpu dirty ring is soft-full */
9813 if (unlikely(vcpu->kvm->dirty_ring_size &&
9814 kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
9815 vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
9816 trace_kvm_dirty_ring_exit(vcpu);
9817 r = 0;
9818 goto out;
9819 }
9820
Radim Krčmář2fa6e1e2017-06-04 14:43:52 +02009821 if (kvm_request_pending(vcpu)) {
Paolo Bonzinif4d31652021-11-11 10:13:38 -05009822 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
Sean Christopherson67369272021-07-02 15:04:25 -07009823 r = -EIO;
9824 goto out;
9825 }
Paolo Bonzini729c15c2020-09-22 06:53:57 -04009826 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
Paolo Bonzini9a78e152021-01-08 11:43:08 -05009827 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
Jim Mattson671ddc72019-10-15 10:44:05 -07009828 r = 0;
9829 goto out;
9830 }
9831 }
Avi Kivitya8eeb042010-05-10 12:34:53 +03009832 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
Marcelo Tosatti2e53d632008-02-20 14:47:24 -05009833 kvm_mmu_unload(vcpu);
Avi Kivitya8eeb042010-05-10 12:34:53 +03009834 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
Marcelo Tosatti2f599712008-05-27 12:10:20 -03009835 __kvm_migrate_timers(vcpu);
Marcelo Tosattid8281992012-11-27 23:29:01 -02009836 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
Paolo Bonzini6b6fcd22021-09-16 18:15:32 +00009837 kvm_update_masterclock(vcpu->kvm);
Marcelo Tosatti0061d53d2013-05-09 20:21:41 -03009838 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
9839 kvm_gen_kvmclock_update(vcpu);
Zachary Amsden34c238a2010-09-18 14:38:14 -10009840 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
9841 r = kvm_guest_time_update(vcpu);
Zachary Amsden8cfdc002010-08-19 22:07:21 -10009842 if (unlikely(r))
9843 goto out;
9844 }
Avi Kivitya8eeb042010-05-10 12:34:53 +03009845 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
Marcelo Tosatti4731d4c2008-09-23 13:18:39 -03009846 kvm_mmu_sync_roots(vcpu);
Paolo Bonzini727a7e22020-03-05 03:52:50 -05009847 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
9848 kvm_mmu_load_pgd(vcpu);
Sean Christophersoneeeb4f62020-03-20 14:28:20 -07009849 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
Sean Christopherson77809382020-03-20 14:28:18 -07009850 kvm_vcpu_flush_tlb_all(vcpu);
Sean Christophersoneeeb4f62020-03-20 14:28:20 -07009851
9852 /* Flushing all ASIDs flushes the current ASID... */
9853 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
9854 }
Sean Christopherson40e5f9082021-11-25 01:49:43 +00009855 kvm_service_local_tlb_flush_requests(vcpu);
Sean Christophersoneeeb4f62020-03-20 14:28:20 -07009856
Avi Kivitya8eeb042010-05-10 12:34:53 +03009857 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
Avi Kivity851ba692009-08-24 11:10:17 +03009858 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
Avi Kivityb93463a2007-10-25 16:52:32 +02009859 r = 0;
9860 goto out;
9861 }
Avi Kivitya8eeb042010-05-10 12:34:53 +03009862 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
Sean Christophersoncb6a32c2021-03-02 09:45:14 -08009863 if (is_guest_mode(vcpu)) {
9864 kvm_x86_ops.nested_ops->triple_fault(vcpu);
9865 } else {
9866 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
9867 vcpu->mmio_needed = 0;
9868 r = 0;
9869 goto out;
9870 }
Joerg Roedel71c4dfa2008-02-26 16:49:16 +01009871 }
Gleb Natapovaf585b92010-10-14 11:22:46 +02009872 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
9873 /* Page is swapped out. Do synthetic halt */
9874 vcpu->arch.apf.halted = true;
9875 r = 1;
9876 goto out;
9877 }
Glauber Costac9aaa892011-07-11 15:28:14 -04009878 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
9879 record_steal_time(vcpu);
Paolo Bonzini64d60672015-05-07 11:36:11 +02009880 if (kvm_check_request(KVM_REQ_SMI, vcpu))
9881 process_smi(vcpu);
Avi Kivity7460fb4a2011-09-20 13:43:14 +03009882 if (kvm_check_request(KVM_REQ_NMI, vcpu))
9883 process_nmi(vcpu);
Gleb Natapovf5132b02011-11-10 14:57:22 +02009884 if (kvm_check_request(KVM_REQ_PMU, vcpu))
Wei Huangc6702c92015-06-19 13:44:45 +02009885 kvm_pmu_handle_event(vcpu);
Gleb Natapovf5132b02011-11-10 14:57:22 +02009886 if (kvm_check_request(KVM_REQ_PMI, vcpu))
Wei Huangc6702c92015-06-19 13:44:45 +02009887 kvm_pmu_deliver_pmi(vcpu);
Steve Rutherford7543a632015-07-29 23:21:41 -07009888 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
9889 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
9890 if (test_bit(vcpu->arch.pending_ioapic_eoi,
Andrey Smetanin63086302015-11-10 15:36:32 +03009891 vcpu->arch.ioapic_handled_vectors)) {
Steve Rutherford7543a632015-07-29 23:21:41 -07009892 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
9893 vcpu->run->eoi.vector =
9894 vcpu->arch.pending_ioapic_eoi;
9895 r = 0;
9896 goto out;
9897 }
9898 }
Yang Zhang3d81bc72013-04-11 19:25:13 +08009899 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
9900 vcpu_scan_ioapic(vcpu);
Liran Alone40ff1d2018-03-21 02:50:31 +02009901 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
9902 vcpu_load_eoi_exitmap(vcpu);
Tang Chen4256f432014-09-24 15:57:54 +08009903 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
9904 kvm_vcpu_reload_apic_access_page(vcpu);
Andrey Smetanin2ce79182015-07-03 15:01:41 +03009905 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
9906 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9907 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
9908 r = 0;
9909 goto out;
9910 }
Andrey Smetanine516ceb2015-09-16 12:29:48 +03009911 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
9912 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
9913 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
9914 r = 0;
9915 goto out;
9916 }
Andrey Smetanindb3975712015-11-10 15:36:35 +03009917 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
Vitaly Kuznetsov9ff5e032021-01-26 14:48:11 +01009918 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
9919
Andrey Smetanindb3975712015-11-10 15:36:35 +03009920 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
Vitaly Kuznetsov9ff5e032021-01-26 14:48:11 +01009921 vcpu->run->hyperv = hv_vcpu->exit;
Andrey Smetanindb3975712015-11-10 15:36:35 +03009922 r = 0;
9923 goto out;
9924 }
Andrey Smetaninf3b138c2015-12-28 18:27:24 +03009925
9926 /*
9927 * KVM_REQ_HV_STIMER has to be processed after
9928 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
9929 * depend on the guest clock being up-to-date
9930 */
Andrey Smetanin1f4b34f2015-11-30 19:22:21 +03009931 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
9932 kvm_hv_process_stimers(vcpu);
Suravee Suthikulpanit8df14af2019-11-14 14:15:06 -06009933 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
9934 kvm_vcpu_update_apicv(vcpu);
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +02009935 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
9936 kvm_check_async_pf_completion(vcpu);
Alexander Graf1a1552542020-09-25 16:34:21 +02009937 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
Jason Baronb36464772021-01-14 22:27:56 -05009938 static_call(kvm_x86_msr_filter_changed)(vcpu);
Makarand Sonarea85863c2021-02-12 16:50:12 -08009939
9940 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
9941 static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
Avi Kivity2f52d582008-01-16 12:49:30 +02009942 }
Avi Kivityb93463a2007-10-25 16:52:32 +02009943
David Woodhouse40da8cc2020-12-09 20:08:30 +00009944 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
9945 kvm_xen_has_interrupt(vcpu)) {
Paolo Bonzini0f1e2612016-12-17 16:05:19 +01009946 ++vcpu->stat.req_event;
Jim Mattson4fe09bc2021-06-04 10:26:04 -07009947 r = kvm_apic_accept_events(vcpu);
9948 if (r < 0) {
9949 r = 0;
9950 goto out;
9951 }
Jan Kiszka66450a22013-03-13 12:42:34 +01009952 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
9953 r = 1;
9954 goto out;
9955 }
9956
Jim Mattsona5f69092021-06-04 10:26:03 -07009957 r = inject_pending_event(vcpu, &req_immediate_exit);
9958 if (r < 0) {
9959 r = 0;
9960 goto out;
9961 }
Paolo Bonzinic9d40912020-05-22 11:21:49 -04009962 if (req_int_win)
Jason Baronb36464772021-01-14 22:27:56 -05009963 static_call(kvm_x86_enable_irq_window)(vcpu);
Gleb Natapov6a8b1d12009-05-11 13:35:51 +03009964
Avi Kivity3842d132010-07-27 12:30:24 +03009965 if (kvm_lapic_enabled(vcpu)) {
9966 update_cr8_intercept(vcpu);
9967 kvm_lapic_sync_to_vapic(vcpu);
9968 }
Gleb Natapov95ba8273132009-04-21 17:45:08 +03009969 }
Avi Kivityb93463a2007-10-25 16:52:32 +02009970
Avi Kivityd8368af2012-05-14 18:07:56 +03009971 r = kvm_mmu_reload(vcpu);
9972 if (unlikely(r)) {
Michael S. Tsirkind905c062012-06-24 19:25:00 +03009973 goto cancel_injection;
Avi Kivityd8368af2012-05-14 18:07:56 +03009974 }
9975
Jan Kiszka42dbaa52008-12-15 13:52:10 +01009976 preempt_disable();
9977
Jason Baronb36464772021-01-14 22:27:56 -05009978 static_call(kvm_x86_prepare_guest_switch)(vcpu);
Paolo Bonzinib95234c2016-12-19 13:57:33 +01009979
9980 /*
9981 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
9982 * IPI are then delayed after guest entry, which ensures that they
9983 * result in virtual interrupt delivery.
9984 */
9985 local_irq_disable();
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +08009986 vcpu->mode = IN_GUEST_MODE;
9987
Michael S. Tsirkin01b71912013-11-04 22:36:25 +02009988 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
9989
Lan Tianyu0f127d12016-03-13 11:10:29 +08009990 /*
Paolo Bonzinib95234c2016-12-19 13:57:33 +01009991 * 1) We should set ->mode before checking ->requests. Please see
Andrew Jonescde9af62017-04-26 22:32:24 +02009992 * the comment in kvm_vcpu_exiting_guest_mode().
Paolo Bonzinib95234c2016-12-19 13:57:33 +01009993 *
Luwei Kang81b01662019-01-31 16:52:02 +08009994 * 2) For APICv, we should set ->mode before checking PID.ON. This
Paolo Bonzinib95234c2016-12-19 13:57:33 +01009995 * pairs with the memory barrier implicit in pi_test_and_set_on
9996 * (see vmx_deliver_posted_interrupt).
9997 *
9998 * 3) This also orders the write to mode from any reads to the page
9999 * tables done while the VCPU is running. Please see the comment
10000 * in kvm_flush_remote_tlbs.
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +080010001 */
Michael S. Tsirkin01b71912013-11-04 22:36:25 +020010002 smp_mb__after_srcu_read_unlock();
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010003
Paolo Bonzinib95234c2016-12-19 13:57:33 +010010004 /*
Sean Christopherson0f65a9d32021-12-08 01:52:26 +000010005 * Process pending posted interrupts to handle the case where the
10006 * notification IRQ arrived in the host, or was never sent (because the
10007 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
10008 * status, KVM doesn't update assigned devices when APICv is inhibited,
10009 * i.e. they can post interrupts even if APICv is temporarily disabled.
Paolo Bonzinib95234c2016-12-19 13:57:33 +010010010 */
Paolo Bonzini37c4dbf2021-11-22 19:43:10 -050010011 if (kvm_lapic_enabled(vcpu))
10012 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010013
Wanpeng Li5a9f5442020-04-28 14:23:26 +080010014 if (kvm_vcpu_exit_request(vcpu)) {
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +080010015 vcpu->mode = OUTSIDE_GUEST_MODE;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010016 smp_wmb();
10017 local_irq_enable();
10018 preempt_enable();
Michael S. Tsirkin01b71912013-11-04 22:36:25 +020010019 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010020 r = 1;
Michael S. Tsirkind905c062012-06-24 19:25:00 +030010021 goto cancel_injection;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010022 }
10023
Paolo Bonzinic43203c2016-06-01 22:26:00 +020010024 if (req_immediate_exit) {
10025 kvm_make_request(KVM_REQ_EVENT, vcpu);
Jason Baronb36464772021-01-14 22:27:56 -050010026 static_call(kvm_x86_request_immediate_exit)(vcpu);
Paolo Bonzinic43203c2016-06-01 22:26:00 +020010027 }
Nadav Har'Eld6185f22011-09-22 13:52:56 +030010028
Sean Christopherson2620fe22020-01-17 11:30:51 -080010029 fpregs_assert_state_consistent();
10030 if (test_thread_flag(TIF_NEED_FPU_LOAD))
10031 switch_fpu_return();
Rik van Riel5f409e22019-04-03 18:41:52 +020010032
Jing Liuec5be882022-01-05 04:35:23 -080010033 if (vcpu->arch.guest_fpu.xfd_err)
10034 wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
10035
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010036 if (unlikely(vcpu->arch.switch_db_regs)) {
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010037 set_debugreg(0, 7);
10038 set_debugreg(vcpu->arch.eff_db[0], 0);
10039 set_debugreg(vcpu->arch.eff_db[1], 1);
10040 set_debugreg(vcpu->arch.eff_db[2], 2);
10041 set_debugreg(vcpu->arch.eff_db[3], 3);
Lai Jiangshanf85d4012021-06-29 01:26:32 +080010042 } else if (unlikely(hw_breakpoint_active())) {
10043 set_debugreg(0, 7);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010044 }
10045
Mark Rutlandb2d2af72022-02-01 13:29:24 +000010046 guest_timing_enter_irqoff();
10047
Paolo Bonzinid89d04a2021-02-02 10:44:23 -050010048 for (;;) {
Sean Christophersonee49a892021-10-21 17:49:25 -070010049 /*
10050 * Assert that vCPU vs. VM APICv state is consistent. An APICv
10051 * update must kick and wait for all vCPUs before toggling the
10052 * per-VM state, and responsing vCPUs must wait for the update
10053 * to complete before servicing KVM_REQ_APICV_UPDATE.
10054 */
10055 WARN_ON_ONCE(kvm_apicv_activated(vcpu->kvm) != kvm_vcpu_apicv_active(vcpu));
10056
Paolo Bonzinid89d04a2021-02-02 10:44:23 -050010057 exit_fastpath = static_call(kvm_x86_run)(vcpu);
10058 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
10059 break;
10060
Paolo Bonzini37c4dbf2021-11-22 19:43:10 -050010061 if (kvm_lapic_enabled(vcpu))
10062 static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
Paolo Bonzinide7cd3f2021-10-20 06:27:36 -040010063
10064 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
Paolo Bonzinid89d04a2021-02-02 10:44:23 -050010065 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
10066 break;
10067 }
Paolo Bonzinide7cd3f2021-10-20 06:27:36 -040010068 }
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010069
Frederic Weisbecker24f1e32c2009-09-09 19:22:48 +020010070 /*
Paolo Bonzinic77fb5f2014-02-21 10:17:24 +010010071 * Do this here before restoring debug registers on the host. And
10072 * since we do this before handling the vmexit, a DR access vmexit
10073 * can (a) read the correct value of the debug registers, (b) set
10074 * KVM_DEBUGREG_WONT_EXIT again.
10075 */
10076 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
Paolo Bonzinic77fb5f2014-02-21 10:17:24 +010010077 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
Jason Baronb36464772021-01-14 22:27:56 -050010078 static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
Paolo Bonzini70e4da72016-02-26 12:28:40 +010010079 kvm_update_dr0123(vcpu);
Paolo Bonzini70e4da72016-02-26 12:28:40 +010010080 kvm_update_dr7(vcpu);
Paolo Bonzinic77fb5f2014-02-21 10:17:24 +010010081 }
10082
10083 /*
Frederic Weisbecker24f1e32c2009-09-09 19:22:48 +020010084 * If the guest has used debug registers, at least dr7
10085 * will be disabled while returning to the host.
10086 * If we don't have active breakpoints in the host, we don't
10087 * care about the messed up debug address registers. But if
10088 * we have some of them active, restore the old state.
10089 */
Frederic Weisbecker59d8eb52009-11-10 11:03:12 +010010090 if (hw_breakpoint_active())
Frederic Weisbecker24f1e32c2009-09-09 19:22:48 +020010091 hw_breakpoint_restore();
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010092
Jim Mattsonc9671182020-06-03 16:56:23 -070010093 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
Haozhong Zhang4ba76532015-10-20 15:39:07 +080010094 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
Zachary Amsden1d5f0662010-08-19 22:07:30 -100010095
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +080010096 vcpu->mode = OUTSIDE_GUEST_MODE;
Avi Kivityd94e1dc2010-05-03 16:54:48 +030010097 smp_wmb();
Yang Zhanga547c6d2013-04-11 19:25:10 +080010098
Kevin Tianb5274b12022-01-05 04:35:32 -080010099 /*
10100 * Sync xfd before calling handle_exit_irqoff() which may
10101 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
10102 * in #NM irqoff handler).
10103 */
10104 if (vcpu->arch.xfd_no_write_intercept)
10105 fpu_sync_guest_vmexit_xfd_state();
10106
Jason Baronb36464772021-01-14 22:27:56 -050010107 static_call(kvm_x86_handle_exit_irqoff)(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010108
Jing Liuec5be882022-01-05 04:35:23 -080010109 if (vcpu->arch.guest_fpu.xfd_err)
10110 wrmsrl(MSR_IA32_XFD_ERR, 0);
10111
Sean Christophersond7a08882019-07-10 09:07:34 -070010112 /*
10113 * Consume any pending interrupts, including the possible source of
10114 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
10115 * An instruction is required after local_irq_enable() to fully unblock
10116 * interrupts on processors that implement an interrupt shadow, the
10117 * stat.exits increment will do nicely.
10118 */
Sean Christophersondb215752021-11-11 02:07:32 +000010119 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
Sean Christophersond7a08882019-07-10 09:07:34 -070010120 local_irq_enable();
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010121 ++vcpu->stat.exits;
Sean Christophersond7a08882019-07-10 09:07:34 -070010122 local_irq_disable();
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010123 kvm_after_interrupt(vcpu);
10124
Wanpeng Li16045712021-05-04 17:27:30 -070010125 /*
10126 * Wait until after servicing IRQs to account guest time so that any
10127 * ticks that occurred while running the guest are properly accounted
10128 * to the guest. Waiting until IRQs are enabled degrades the accuracy
10129 * of accounting via context tracking, but the loss of accuracy is
10130 * acceptable for all known use cases.
10131 */
Mark Rutlandb2d2af72022-02-01 13:29:24 +000010132 guest_timing_exit_irqoff();
Wanpeng Li16045712021-05-04 17:27:30 -070010133
Wanpeng Liec0671d2019-05-20 16:18:08 +080010134 if (lapic_in_kernel(vcpu)) {
10135 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
10136 if (delta != S64_MIN) {
10137 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
10138 vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
10139 }
10140 }
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010141
Paolo Bonzinif2485b32016-06-15 15:23:11 +020010142 local_irq_enable();
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010143 preempt_enable();
10144
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010145 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
Marcelo Tosatti3200f402008-03-29 20:17:59 -030010146
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010147 /*
10148 * Profile KVM exit RIPs:
10149 */
10150 if (unlikely(prof_on == KVM_PROFILING)) {
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -030010151 unsigned long rip = kvm_rip_read(vcpu);
10152 profile_hit(KVM_PROFILING, (void *)rip);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010153 }
10154
Zachary Amsdencc578282012-02-03 15:43:50 -020010155 if (unlikely(vcpu->arch.tsc_always_catchup))
10156 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Avi Kivity298101d2007-11-25 13:41:11 +020010157
Michael S. Tsirkin5cfb1d52012-06-24 19:24:54 +030010158 if (vcpu->arch.apic_attention)
10159 kvm_lapic_sync_from_vapic(vcpu);
Avi Kivityb93463a2007-10-25 16:52:32 +020010160
Jason Baronb36464772021-01-14 22:27:56 -050010161 r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
Michael S. Tsirkind905c062012-06-24 19:25:00 +030010162 return r;
10163
10164cancel_injection:
Sean Christopherson8081ad02020-04-22 19:25:40 -070010165 if (req_immediate_exit)
10166 kvm_make_request(KVM_REQ_EVENT, vcpu);
Jason Baronb36464772021-01-14 22:27:56 -050010167 static_call(kvm_x86_cancel_injection)(vcpu);
Michael S. Tsirkinae7a2a32012-06-24 19:25:07 +030010168 if (unlikely(vcpu->arch.apic_attention))
10169 kvm_lapic_sync_from_vapic(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010170out:
Marcelo Tosattid7690172008-09-08 15:23:48 -030010171 return r;
10172}
10173
Paolo Bonzini362c6982015-02-06 12:48:04 +010010174static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
10175{
Sean Christopherson98c25ea2021-12-08 01:52:17 +000010176 bool hv_timer;
10177
Sean Christophersonc3e8abf2021-12-08 01:52:19 +000010178 if (!kvm_arch_vcpu_runnable(vcpu)) {
Sean Christopherson98c25ea2021-12-08 01:52:17 +000010179 /*
10180 * Switch to the software timer before halt-polling/blocking as
10181 * the guest's timer may be a break event for the vCPU, and the
10182 * hypervisor timer runs only when the CPU is in guest mode.
10183 * Switch before halt-polling so that KVM recognizes an expired
10184 * timer before blocking.
10185 */
10186 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
10187 if (hv_timer)
10188 kvm_lapic_switch_to_sw_timer(vcpu);
10189
Paolo Bonzini9c8fd1b2015-02-06 12:58:42 +010010190 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
Sean Christophersoncdafece2021-10-08 19:12:11 -070010191 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10192 kvm_vcpu_halt(vcpu);
10193 else
10194 kvm_vcpu_block(vcpu);
Paolo Bonzini9c8fd1b2015-02-06 12:58:42 +010010195 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
Feng Wubf9f6ac2015-09-18 22:29:55 +080010196
Sean Christopherson98c25ea2021-12-08 01:52:17 +000010197 if (hv_timer)
10198 kvm_lapic_switch_to_hv_timer(vcpu);
10199
Paolo Bonzini9c8fd1b2015-02-06 12:58:42 +010010200 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
10201 return 1;
10202 }
Gleb Natapov09cec752009-03-23 15:11:44 +020010203
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010204 if (kvm_apic_accept_events(vcpu) < 0)
10205 return 0;
Paolo Bonzini362c6982015-02-06 12:48:04 +010010206 switch(vcpu->arch.mp_state) {
10207 case KVM_MP_STATE_HALTED:
Tom Lendacky647daca2021-01-04 14:20:01 -060010208 case KVM_MP_STATE_AP_RESET_HOLD:
Paolo Bonzini362c6982015-02-06 12:48:04 +010010209 vcpu->arch.pv.pv_unhalted = false;
10210 vcpu->arch.mp_state =
10211 KVM_MP_STATE_RUNNABLE;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050010212 fallthrough;
Paolo Bonzini362c6982015-02-06 12:48:04 +010010213 case KVM_MP_STATE_RUNNABLE:
10214 vcpu->arch.apf.halted = false;
10215 break;
10216 case KVM_MP_STATE_INIT_RECEIVED:
10217 break;
10218 default:
10219 return -EINTR;
Paolo Bonzini362c6982015-02-06 12:48:04 +010010220 }
10221 return 1;
10222}
10223
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020010224static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
10225{
Paolo Bonzini56083bd2020-04-17 10:32:53 -040010226 if (is_guest_mode(vcpu))
Sean Christophersoncb6a32c2021-03-02 09:45:14 -080010227 kvm_check_nested_events(vcpu);
Paolo Bonzini0ad3bed2016-12-19 15:23:54 +010010228
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020010229 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
10230 !vcpu->arch.apf.halted);
10231}
10232
Paolo Bonzini362c6982015-02-06 12:48:04 +010010233static int vcpu_run(struct kvm_vcpu *vcpu)
Marcelo Tosattid7690172008-09-08 15:23:48 -030010234{
10235 int r;
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010236 struct kvm *kvm = vcpu->kvm;
Marcelo Tosattid7690172008-09-08 15:23:48 -030010237
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010238 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
Paolo Bonzinic595cee2018-07-02 13:07:14 +020010239 vcpu->arch.l1tf_flush_l1d = true;
Marcelo Tosattid7690172008-09-08 15:23:48 -030010240
Paolo Bonzini362c6982015-02-06 12:48:04 +010010241 for (;;) {
Paolo Bonzini58f800d2015-10-13 21:32:50 +020010242 if (kvm_vcpu_running(vcpu)) {
Avi Kivity851ba692009-08-24 11:10:17 +030010243 r = vcpu_enter_guest(vcpu);
Feng Wubf9f6ac2015-09-18 22:29:55 +080010244 } else {
Paolo Bonzini362c6982015-02-06 12:48:04 +010010245 r = vcpu_block(kvm, vcpu);
Feng Wubf9f6ac2015-09-18 22:29:55 +080010246 }
10247
Gleb Natapov09cec752009-03-23 15:11:44 +020010248 if (r <= 0)
10249 break;
10250
Marcelo Tosatti084071d2021-05-25 10:41:17 -030010251 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
Gleb Natapov09cec752009-03-23 15:11:44 +020010252 if (kvm_cpu_has_pending_timer(vcpu))
10253 kvm_inject_pending_timer_irqs(vcpu);
10254
Matt Gingell782d4222015-11-16 15:26:00 -080010255 if (dm_request_for_irq_injection(vcpu) &&
10256 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
Paolo Bonzini4ca7dd82015-07-30 10:32:16 +020010257 r = 0;
10258 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
Gleb Natapov09cec752009-03-23 15:11:44 +020010259 ++vcpu->stat.request_irq_exits;
Paolo Bonzini362c6982015-02-06 12:48:04 +010010260 break;
Gleb Natapov09cec752009-03-23 15:11:44 +020010261 }
Gleb Natapovaf585b92010-10-14 11:22:46 +020010262
Thomas Gleixnerf3020b82020-07-30 09:19:01 +020010263 if (__xfer_to_guest_mode_work_pending()) {
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010264 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
Thomas Gleixner72c3c0f2020-07-23 00:00:09 +020010265 r = xfer_to_guest_mode_handle_work(vcpu);
10266 if (r)
10267 return r;
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010268 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
Marcelo Tosattid7690172008-09-08 15:23:48 -030010269 }
10270 }
10271
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010272 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010273
10274 return r;
10275}
10276
Gleb Natapov716d51a2012-09-03 15:24:26 +030010277static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
10278{
10279 int r;
Sean Christopherson60fc3d02019-08-27 14:40:38 -070010280
Gleb Natapov716d51a2012-09-03 15:24:26 +030010281 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
Sean Christopherson0ce97a22018-08-23 13:56:52 -070010282 r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
Gleb Natapov716d51a2012-09-03 15:24:26 +030010283 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
Sean Christopherson60fc3d02019-08-27 14:40:38 -070010284 return r;
Gleb Natapov716d51a2012-09-03 15:24:26 +030010285}
10286
10287static int complete_emulated_pio(struct kvm_vcpu *vcpu)
10288{
10289 BUG_ON(!vcpu->arch.pio.count);
10290
10291 return complete_emulated_io(vcpu);
10292}
10293
Avi Kivityf78146b2012-04-18 19:22:47 +030010294/*
10295 * Implements the following, as a state machine:
10296 *
10297 * read:
10298 * for each fragment
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010299 * for each mmio piece in the fragment
10300 * write gpa, len
10301 * exit
10302 * copy data
Avi Kivityf78146b2012-04-18 19:22:47 +030010303 * execute insn
10304 *
10305 * write:
10306 * for each fragment
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010307 * for each mmio piece in the fragment
10308 * write gpa, len
10309 * copy data
10310 * exit
Avi Kivityf78146b2012-04-18 19:22:47 +030010311 */
Gleb Natapov716d51a2012-09-03 15:24:26 +030010312static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
Avi Kivity5287f192010-01-19 14:20:10 +020010313{
10314 struct kvm_run *run = vcpu->run;
Avi Kivityf78146b2012-04-18 19:22:47 +030010315 struct kvm_mmio_fragment *frag;
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010316 unsigned len;
Avi Kivity5287f192010-01-19 14:20:10 +020010317
Gleb Natapov716d51a2012-09-03 15:24:26 +030010318 BUG_ON(!vcpu->mmio_needed);
Avi Kivity5287f192010-01-19 14:20:10 +020010319
Gleb Natapov716d51a2012-09-03 15:24:26 +030010320 /* Complete previous fragment */
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010321 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
10322 len = min(8u, frag->len);
Gleb Natapov716d51a2012-09-03 15:24:26 +030010323 if (!vcpu->mmio_is_write)
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010324 memcpy(frag->data, run->mmio.data, len);
10325
10326 if (frag->len <= 8) {
10327 /* Switch to the next fragment. */
10328 frag++;
10329 vcpu->mmio_cur_fragment++;
10330 } else {
10331 /* Go forward to the next mmio piece. */
10332 frag->data += len;
10333 frag->gpa += len;
10334 frag->len -= len;
10335 }
10336
Andrew Honiga08d3b32014-02-27 19:35:14 +010010337 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
Gleb Natapov716d51a2012-09-03 15:24:26 +030010338 vcpu->mmio_needed = 0;
Paolo Bonzini0912c972013-08-27 15:41:43 +020010339
10340 /* FIXME: return into emulator if single-stepping. */
Avi Kivitycef4dea2010-01-20 12:01:20 +020010341 if (vcpu->mmio_is_write)
Gleb Natapov716d51a2012-09-03 15:24:26 +030010342 return 1;
10343 vcpu->mmio_read_completed = 1;
10344 return complete_emulated_io(vcpu);
Avi Kivity5287f192010-01-19 14:20:10 +020010345 }
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010346
Gleb Natapov716d51a2012-09-03 15:24:26 +030010347 run->exit_reason = KVM_EXIT_MMIO;
10348 run->mmio.phys_addr = frag->gpa;
10349 if (vcpu->mmio_is_write)
Xiao Guangrong87da7e62012-10-24 14:07:59 +080010350 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
10351 run->mmio.len = min(8u, frag->len);
Gleb Natapov716d51a2012-09-03 15:24:26 +030010352 run->mmio.is_write = vcpu->mmio_is_write;
10353 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
10354 return 0;
Avi Kivity5287f192010-01-19 14:20:10 +020010355}
10356
Sebastian Andrzej Siewior822f3122018-09-12 15:33:45 +020010357/* Swap (qemu) user FPU context for the guest FPU context. */
10358static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
10359{
Tom Lendackyed02b212020-12-10 11:10:01 -060010360 /*
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020010361 * Exclude PKRU from restore as restored separately in
10362 * kvm_x86_ops.run().
Tom Lendackyed02b212020-12-10 11:10:01 -060010363 */
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020010364 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
Sebastian Andrzej Siewior822f3122018-09-12 15:33:45 +020010365 trace_kvm_fpu(1);
10366}
10367
10368/* When vcpu_run ends, restore user space FPU context. */
10369static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
10370{
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020010371 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
Sebastian Andrzej Siewior822f3122018-09-12 15:33:45 +020010372 ++vcpu->stat.fpu_reload;
10373 trace_kvm_fpu(0);
10374}
10375
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +080010376int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010377{
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +080010378 struct kvm_run *kvm_run = vcpu->run;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010379 int r;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010380
Christoffer Dallaccb7572017-12-04 21:35:25 +010010381 vcpu_load(vcpu);
Jan H. Schönherr20b70352017-11-24 22:39:01 +010010382 kvm_sigset_activate(vcpu);
Chenyi Qiang15aad3b2020-11-06 17:03:13 +080010383 kvm_run->flags = 0;
Peter Xu5663d8f2017-12-12 17:15:02 +010010384 kvm_load_guest_fpu(vcpu);
10385
Avi Kivityac9f6dc2008-07-06 15:48:31 +030010386 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
Jan H. Schönherr2f173d22017-09-06 18:34:06 +020010387 if (kvm_run->immediate_exit) {
10388 r = -EINTR;
10389 goto out;
10390 }
Sean Christopherson98c25ea2021-12-08 01:52:17 +000010391 /*
10392 * It should be impossible for the hypervisor timer to be in
10393 * use before KVM has ever run the vCPU.
10394 */
10395 WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
Sean Christophersonc91d4492021-10-08 19:12:10 -070010396 kvm_vcpu_block(vcpu);
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010397 if (kvm_apic_accept_events(vcpu) < 0) {
10398 r = 0;
10399 goto out;
10400 }
Radim Krčmář72875d82017-04-26 22:32:19 +020010401 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
Avi Kivityac9f6dc2008-07-06 15:48:31 +030010402 r = -EAGAIN;
Jan H. Schönherra0595002017-09-06 00:27:19 +020010403 if (signal_pending(current)) {
10404 r = -EINTR;
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +080010405 kvm_run->exit_reason = KVM_EXIT_INTR;
Jan H. Schönherra0595002017-09-06 00:27:19 +020010406 ++vcpu->stat.signal_exits;
10407 }
Avi Kivityac9f6dc2008-07-06 15:48:31 +030010408 goto out;
10409 }
10410
Sean Christophersone489a4a2021-07-02 15:04:29 -070010411 if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
10412 (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
Ken Hofsass01643c52018-01-31 16:03:36 -080010413 r = -EINVAL;
10414 goto out;
10415 }
10416
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +080010417 if (kvm_run->kvm_dirty_regs) {
Ken Hofsass01643c52018-01-31 16:03:36 -080010418 r = sync_regs(vcpu);
10419 if (r != 0)
10420 goto out;
10421 }
10422
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010423 /* re-sync apic's tpr */
Paolo Bonzini35754c92015-07-29 12:05:37 +020010424 if (!lapic_in_kernel(vcpu)) {
Andre Przywaraeea1cff2010-12-21 11:12:00 +010010425 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
10426 r = -EINVAL;
10427 goto out;
10428 }
10429 }
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010430
Gleb Natapov716d51a2012-09-03 15:24:26 +030010431 if (unlikely(vcpu->arch.complete_userspace_io)) {
10432 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
10433 vcpu->arch.complete_userspace_io = NULL;
10434 r = cui(vcpu);
10435 if (r <= 0)
Peter Xu5663d8f2017-12-12 17:15:02 +010010436 goto out;
Gleb Natapov716d51a2012-09-03 15:24:26 +030010437 } else
10438 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
Avi Kivity5287f192010-01-19 14:20:10 +020010439
Sean Christophersonfc4fad72021-12-28 23:24:36 +000010440 if (kvm_run->immediate_exit) {
Paolo Bonzini460df4c2017-02-08 11:50:15 +010010441 r = -EINTR;
Sean Christophersonfc4fad72021-12-28 23:24:36 +000010442 goto out;
10443 }
10444
10445 r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
10446 if (r <= 0)
10447 goto out;
10448
10449 r = vcpu_run(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010450
10451out:
Peter Xu5663d8f2017-12-12 17:15:02 +010010452 kvm_put_guest_fpu(vcpu);
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +080010453 if (kvm_run->kvm_valid_regs)
Ken Hofsass01643c52018-01-31 16:03:36 -080010454 store_regs(vcpu);
Marcelo Tosattif1d86e42010-05-03 23:04:27 -030010455 post_kvm_run_save(vcpu);
Jan H. Schönherr20b70352017-11-24 22:39:01 +010010456 kvm_sigset_deactivate(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010457
Christoffer Dallaccb7572017-12-04 21:35:25 +010010458 vcpu_put(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010459 return r;
10460}
10461
Ken Hofsass01643c52018-01-31 16:03:36 -080010462static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010463{
Gleb Natapov7ae441e2011-03-31 12:06:41 +020010464 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
10465 /*
10466 * We are here if userspace calls get_regs() in the middle of
10467 * instruction emulation. Registers state needs to be copied
Guo Chao4a969982012-06-28 15:17:27 +080010468 * back from emulation context to vcpu. Userspace shouldn't do
Gleb Natapov7ae441e2011-03-31 12:06:41 +020010469 * that usually, but some bad designed PV devices (vmware
10470 * backdoor interface) need this to work
10471 */
Sean Christophersonc9b8b072020-02-18 15:29:48 -080010472 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
Gleb Natapov7ae441e2011-03-31 12:06:41 +020010473 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10474 }
Sean Christophersonde3cd112019-04-30 10:36:17 -070010475 regs->rax = kvm_rax_read(vcpu);
10476 regs->rbx = kvm_rbx_read(vcpu);
10477 regs->rcx = kvm_rcx_read(vcpu);
10478 regs->rdx = kvm_rdx_read(vcpu);
10479 regs->rsi = kvm_rsi_read(vcpu);
10480 regs->rdi = kvm_rdi_read(vcpu);
Paolo Bonzinie9c16c72019-04-30 22:07:26 +020010481 regs->rsp = kvm_rsp_read(vcpu);
Sean Christophersonde3cd112019-04-30 10:36:17 -070010482 regs->rbp = kvm_rbp_read(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010483#ifdef CONFIG_X86_64
Sean Christophersonde3cd112019-04-30 10:36:17 -070010484 regs->r8 = kvm_r8_read(vcpu);
10485 regs->r9 = kvm_r9_read(vcpu);
10486 regs->r10 = kvm_r10_read(vcpu);
10487 regs->r11 = kvm_r11_read(vcpu);
10488 regs->r12 = kvm_r12_read(vcpu);
10489 regs->r13 = kvm_r13_read(vcpu);
10490 regs->r14 = kvm_r14_read(vcpu);
10491 regs->r15 = kvm_r15_read(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010492#endif
10493
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -030010494 regs->rip = kvm_rip_read(vcpu);
Jan Kiszka91586a32009-10-05 13:07:21 +020010495 regs->rflags = kvm_get_rflags(vcpu);
Ken Hofsass01643c52018-01-31 16:03:36 -080010496}
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010497
Ken Hofsass01643c52018-01-31 16:03:36 -080010498int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10499{
10500 vcpu_load(vcpu);
10501 __get_regs(vcpu, regs);
Christoffer Dall1fc9b762017-12-04 21:35:26 +010010502 vcpu_put(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010503 return 0;
10504}
10505
Ken Hofsass01643c52018-01-31 16:03:36 -080010506static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010507{
Gleb Natapov7ae441e2011-03-31 12:06:41 +020010508 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
10509 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
10510
Sean Christophersonde3cd112019-04-30 10:36:17 -070010511 kvm_rax_write(vcpu, regs->rax);
10512 kvm_rbx_write(vcpu, regs->rbx);
10513 kvm_rcx_write(vcpu, regs->rcx);
10514 kvm_rdx_write(vcpu, regs->rdx);
10515 kvm_rsi_write(vcpu, regs->rsi);
10516 kvm_rdi_write(vcpu, regs->rdi);
Paolo Bonzinie9c16c72019-04-30 22:07:26 +020010517 kvm_rsp_write(vcpu, regs->rsp);
Sean Christophersonde3cd112019-04-30 10:36:17 -070010518 kvm_rbp_write(vcpu, regs->rbp);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010519#ifdef CONFIG_X86_64
Sean Christophersonde3cd112019-04-30 10:36:17 -070010520 kvm_r8_write(vcpu, regs->r8);
10521 kvm_r9_write(vcpu, regs->r9);
10522 kvm_r10_write(vcpu, regs->r10);
10523 kvm_r11_write(vcpu, regs->r11);
10524 kvm_r12_write(vcpu, regs->r12);
10525 kvm_r13_write(vcpu, regs->r13);
10526 kvm_r14_write(vcpu, regs->r14);
10527 kvm_r15_write(vcpu, regs->r15);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010528#endif
10529
Marcelo Tosatti5fdbf972008-06-27 14:58:02 -030010530 kvm_rip_write(vcpu, regs->rip);
Wanpeng Lid73235d2017-12-07 00:30:08 -080010531 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010532
Jan Kiszkab4f14ab2008-04-30 17:59:04 +020010533 vcpu->arch.exception.pending = false;
10534
Avi Kivity3842d132010-07-27 12:30:24 +030010535 kvm_make_request(KVM_REQ_EVENT, vcpu);
Ken Hofsass01643c52018-01-31 16:03:36 -080010536}
Avi Kivity3842d132010-07-27 12:30:24 +030010537
Ken Hofsass01643c52018-01-31 16:03:36 -080010538int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
10539{
10540 vcpu_load(vcpu);
10541 __set_regs(vcpu, regs);
Christoffer Dall875656f2017-12-04 21:35:27 +010010542 vcpu_put(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010543 return 0;
10544}
10545
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010546void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
10547{
10548 struct kvm_segment cs;
10549
Guillaume Thouvenin3e6e0aa2008-05-27 10:18:46 +020010550 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010551 *db = cs.db;
10552 *l = cs.l;
10553}
10554EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
10555
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010556static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010557{
Gleb Natapov89a27f42010-02-16 10:51:48 +020010558 struct desc_ptr dt;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010559
Tom Lendacky52657132020-12-10 11:09:59 -060010560 if (vcpu->arch.guest_state_protected)
10561 goto skip_protected_regs;
10562
Guillaume Thouvenin3e6e0aa2008-05-27 10:18:46 +020010563 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
10564 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
10565 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
10566 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
10567 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
10568 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010569
Guillaume Thouvenin3e6e0aa2008-05-27 10:18:46 +020010570 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
10571 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010572
Jason Baronb36464772021-01-14 22:27:56 -050010573 static_call(kvm_x86_get_idt)(vcpu, &dt);
Gleb Natapov89a27f42010-02-16 10:51:48 +020010574 sregs->idt.limit = dt.size;
10575 sregs->idt.base = dt.address;
Jason Baronb36464772021-01-14 22:27:56 -050010576 static_call(kvm_x86_get_gdt)(vcpu, &dt);
Gleb Natapov89a27f42010-02-16 10:51:48 +020010577 sregs->gdt.limit = dt.size;
10578 sregs->gdt.base = dt.address;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010579
Zhang Xiantaoad312c72007-12-13 23:50:52 +080010580 sregs->cr2 = vcpu->arch.cr2;
Avi Kivity9f8fe502010-12-05 17:30:00 +020010581 sregs->cr3 = kvm_read_cr3(vcpu);
Tom Lendacky52657132020-12-10 11:09:59 -060010582
10583skip_protected_regs:
10584 sregs->cr0 = kvm_read_cr0(vcpu);
Avi Kivityfc78f512009-12-07 12:16:48 +020010585 sregs->cr4 = kvm_read_cr4(vcpu);
Avi Kivity2d3ad1f2008-02-24 11:20:43 +020010586 sregs->cr8 = kvm_get_cr8(vcpu);
Avi Kivityf6801df2010-01-21 15:31:50 +020010587 sregs->efer = vcpu->arch.efer;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010588 sregs->apic_base = kvm_get_apic_base(vcpu);
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010589}
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010590
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010591static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10592{
10593 __get_sregs_common(vcpu, sregs);
10594
10595 if (vcpu->arch.guest_state_protected)
10596 return;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010597
Liran Alon04140b42018-03-23 03:01:31 +030010598 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
Gleb Natapov14d0bc12009-04-21 17:45:11 +030010599 set_bit(vcpu->arch.interrupt.nr,
10600 (unsigned long *)sregs->interrupt_bitmap);
Ken Hofsass01643c52018-01-31 16:03:36 -080010601}
Gleb Natapov16d7a192009-04-21 17:45:10 +030010602
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010603static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
10604{
10605 int i;
10606
10607 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
10608
10609 if (vcpu->arch.guest_state_protected)
10610 return;
10611
10612 if (is_pae_paging(vcpu)) {
10613 for (i = 0 ; i < 4 ; i++)
10614 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
10615 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
10616 }
10617}
10618
Ken Hofsass01643c52018-01-31 16:03:36 -080010619int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
10620 struct kvm_sregs *sregs)
10621{
10622 vcpu_load(vcpu);
10623 __get_sregs(vcpu, sregs);
Christoffer Dallbcdec412017-12-04 21:35:28 +010010624 vcpu_put(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010625 return 0;
10626}
10627
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -030010628int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
10629 struct kvm_mp_state *mp_state)
10630{
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010631 int r;
10632
Christoffer Dallfd232562017-12-04 21:35:30 +010010633 vcpu_load(vcpu);
Sean Christophersonf958bd22019-12-09 12:19:31 -080010634 if (kvm_mpx_supported())
10635 kvm_load_guest_fpu(vcpu);
Christoffer Dallfd232562017-12-04 21:35:30 +010010636
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010637 r = kvm_apic_accept_events(vcpu);
10638 if (r < 0)
10639 goto out;
10640 r = 0;
10641
Tom Lendacky647daca2021-01-04 14:20:01 -060010642 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
10643 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
10644 vcpu->arch.pv.pv_unhalted)
Srivatsa Vaddagiri6aef2662013-08-26 14:18:34 +053010645 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
10646 else
10647 mp_state->mp_state = vcpu->arch.mp_state;
10648
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010649out:
Sean Christophersonf958bd22019-12-09 12:19:31 -080010650 if (kvm_mpx_supported())
10651 kvm_put_guest_fpu(vcpu);
Christoffer Dallfd232562017-12-04 21:35:30 +010010652 vcpu_put(vcpu);
Jim Mattson4fe09bc2021-06-04 10:26:04 -070010653 return r;
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -030010654}
10655
10656int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
10657 struct kvm_mp_state *mp_state)
10658{
Christoffer Dalle83dff52017-12-04 21:35:31 +010010659 int ret = -EINVAL;
10660
10661 vcpu_load(vcpu);
10662
Paolo Bonzinibce87cc2016-01-08 13:48:51 +010010663 if (!lapic_in_kernel(vcpu) &&
Jan Kiszka66450a22013-03-13 12:42:34 +010010664 mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
Christoffer Dalle83dff52017-12-04 21:35:31 +010010665 goto out;
Jan Kiszka66450a22013-03-13 12:42:34 +010010666
Liran Alon27cbe7d2019-11-11 11:16:40 +020010667 /*
10668 * KVM_MP_STATE_INIT_RECEIVED means the processor is in
10669 * INIT state; latched init should be reported using
10670 * KVM_SET_VCPU_EVENTS, so reject it here.
10671 */
10672 if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
David Hildenbrand28bf2882017-03-23 11:46:03 +010010673 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
10674 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
Christoffer Dalle83dff52017-12-04 21:35:31 +010010675 goto out;
David Hildenbrand28bf2882017-03-23 11:46:03 +010010676
Jan Kiszka66450a22013-03-13 12:42:34 +010010677 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
10678 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
10679 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
10680 } else
10681 vcpu->arch.mp_state = mp_state->mp_state;
Avi Kivity3842d132010-07-27 12:30:24 +030010682 kvm_make_request(KVM_REQ_EVENT, vcpu);
Christoffer Dalle83dff52017-12-04 21:35:31 +010010683
10684 ret = 0;
10685out:
10686 vcpu_put(vcpu);
10687 return ret;
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -030010688}
10689
Kevin Wolf7f3d35f2012-02-08 14:34:38 +010010690int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
10691 int reason, bool has_error_code, u32 error_code)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010692{
Sean Christophersonc9b8b072020-02-18 15:29:48 -080010693 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
Mohammed Gamal8ec47222010-08-16 00:47:01 +030010694 int ret;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010695
Mohammed Gamal8ec47222010-08-16 00:47:01 +030010696 init_emulate_ctxt(vcpu);
Izik Eidus37817f22008-03-24 23:14:53 +020010697
Kevin Wolf7f3d35f2012-02-08 14:34:38 +010010698 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
Takuya Yoshikawa9d741912011-05-29 21:53:48 +090010699 has_error_code, error_code);
Sean Christopherson10517782019-08-27 14:40:35 -070010700 if (ret) {
10701 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10702 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
10703 vcpu->run->internal.ndata = 0;
Sean Christopherson60fc3d02019-08-27 14:40:38 -070010704 return 0;
Sean Christopherson10517782019-08-27 14:40:35 -070010705 }
Gleb Natapovc6975182010-02-18 12:15:01 +020010706
Takuya Yoshikawa9d741912011-05-29 21:53:48 +090010707 kvm_rip_write(vcpu, ctxt->eip);
10708 kvm_set_rflags(vcpu, ctxt->eflags);
Sean Christopherson60fc3d02019-08-27 14:40:38 -070010709 return 1;
Izik Eidus37817f22008-03-24 23:14:53 +020010710}
10711EXPORT_SYMBOL_GPL(kvm_task_switch);
10712
Sean Christophersonee69c922020-10-06 18:44:16 -070010713static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
Lan Tianyuf2981032017-12-14 03:01:52 -050010714{
Tianyu Lan37b95952018-01-16 17:34:07 +080010715 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
Lan Tianyuf2981032017-12-14 03:01:52 -050010716 /*
10717 * When EFER.LME and CR0.PG are set, the processor is in
10718 * 64-bit mode (though maybe in a 32-bit code segment).
10719 * CR4.PAE and EFER.LMA must be set.
10720 */
Sean Christophersonee69c922020-10-06 18:44:16 -070010721 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
10722 return false;
Sean Christophersonca29e142021-02-03 16:01:12 -080010723 if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
Paolo Bonzinic1c35cf2020-11-13 08:30:38 -050010724 return false;
Lan Tianyuf2981032017-12-14 03:01:52 -050010725 } else {
10726 /*
10727 * Not in 64-bit mode: EFER.LMA is clear and the code
10728 * segment cannot be 64-bit.
10729 */
10730 if (sregs->efer & EFER_LMA || sregs->cs.l)
Sean Christophersonee69c922020-10-06 18:44:16 -070010731 return false;
Lan Tianyuf2981032017-12-14 03:01:52 -050010732 }
10733
Sean Christophersonee69c922020-10-06 18:44:16 -070010734 return kvm_is_valid_cr4(vcpu, sregs->cr4);
Lan Tianyuf2981032017-12-14 03:01:52 -050010735}
10736
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010737static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
10738 int *mmu_reset_needed, bool update_pdptrs)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010739{
Jan Kiszka58cb6282014-01-24 16:48:44 +010010740 struct msr_data apic_base_msr;
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010741 int idx;
Gleb Natapov89a27f42010-02-16 10:51:48 +020010742 struct desc_ptr dt;
Christoffer Dallb4ef9d42017-12-04 21:35:29 +010010743
Sean Christophersonee69c922020-10-06 18:44:16 -070010744 if (!kvm_is_valid_sregs(vcpu, sregs))
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010745 return -EINVAL;
Lan Tianyuf2981032017-12-14 03:01:52 -050010746
Jim Mattsond3802282017-08-10 10:14:13 -070010747 apic_base_msr.data = sregs->apic_base;
10748 apic_base_msr.host_initiated = true;
10749 if (kvm_set_apic_base(vcpu, &apic_base_msr))
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010750 return -EINVAL;
Petr Matousek6d1068b2012-11-06 19:24:07 +010010751
Tom Lendacky52657132020-12-10 11:09:59 -060010752 if (vcpu->arch.guest_state_protected)
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010753 return 0;
Tom Lendacky52657132020-12-10 11:09:59 -060010754
Gleb Natapov89a27f42010-02-16 10:51:48 +020010755 dt.size = sregs->idt.limit;
10756 dt.address = sregs->idt.base;
Jason Baronb36464772021-01-14 22:27:56 -050010757 static_call(kvm_x86_set_idt)(vcpu, &dt);
Gleb Natapov89a27f42010-02-16 10:51:48 +020010758 dt.size = sregs->gdt.limit;
10759 dt.address = sregs->gdt.base;
Jason Baronb36464772021-01-14 22:27:56 -050010760 static_call(kvm_x86_set_gdt)(vcpu, &dt);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010761
Zhang Xiantaoad312c72007-12-13 23:50:52 +080010762 vcpu->arch.cr2 = sregs->cr2;
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010763 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
Jan Kiszkadc7e7952009-07-01 20:52:03 +020010764 vcpu->arch.cr3 = sregs->cr3;
Lai Jiangshan3883bc9d2021-11-08 20:44:02 +080010765 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
Michael Roth405329f2021-12-16 11:13:54 -060010766 static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010767
Avi Kivity2d3ad1f2008-02-24 11:20:43 +020010768 kvm_set_cr8(vcpu, sregs->cr8);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010769
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010770 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
Jason Baronb36464772021-01-14 22:27:56 -050010771 static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010772
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010773 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
Jason Baronb36464772021-01-14 22:27:56 -050010774 static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
Paul Knowlesd7306162008-02-06 11:02:35 +000010775 vcpu->arch.cr0 = sregs->cr0;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010776
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010777 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
Jason Baronb36464772021-01-14 22:27:56 -050010778 static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
Xiao Guangrong63f42e02011-01-12 15:39:18 +080010779
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010780 if (update_pdptrs) {
10781 idx = srcu_read_lock(&vcpu->kvm->srcu);
10782 if (is_pae_paging(vcpu)) {
Lai Jiangshan2df4a5e2021-11-24 20:20:52 +080010783 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010784 *mmu_reset_needed = 1;
10785 }
10786 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Marcelo Tosatti7c93be442009-10-26 16:48:33 -020010787 }
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010788
Guillaume Thouvenin3e6e0aa2008-05-27 10:18:46 +020010789 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
10790 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
10791 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
10792 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
10793 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
10794 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010795
Guillaume Thouvenin3e6e0aa2008-05-27 10:18:46 +020010796 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
10797 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010798
Mikhail Ershov5f0269f2009-08-03 14:58:25 +030010799 update_cr8_intercept(vcpu);
10800
Marcelo Tosatti9c3e4aa2008-09-10 16:40:55 -030010801 /* Older userspace won't unhalt the vcpu on reset. */
Gleb Natapovc5af89b2009-06-09 15:56:26 +030010802 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
Marcelo Tosatti9c3e4aa2008-09-10 16:40:55 -030010803 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
Avi Kivity3eeb3282010-01-21 15:31:48 +020010804 !is_protmode(vcpu))
Marcelo Tosatti9c3e4aa2008-09-10 16:40:55 -030010805 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10806
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010807 return 0;
10808}
10809
10810static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
10811{
10812 int pending_vec, max_bits;
10813 int mmu_reset_needed = 0;
10814 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
10815
10816 if (ret)
10817 return ret;
10818
10819 if (mmu_reset_needed)
10820 kvm_mmu_reset_context(vcpu);
10821
Tom Lendacky52657132020-12-10 11:09:59 -060010822 max_bits = KVM_NR_INTERRUPTS;
10823 pending_vec = find_first_bit(
10824 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010825
Tom Lendacky52657132020-12-10 11:09:59 -060010826 if (pending_vec < max_bits) {
10827 kvm_queue_interrupt(vcpu, pending_vec, false);
10828 pr_debug("Set back pending irq %d\n", pending_vec);
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010829 kvm_make_request(KVM_REQ_EVENT, vcpu);
Tom Lendacky52657132020-12-10 11:09:59 -060010830 }
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010831 return 0;
10832}
Tom Lendacky52657132020-12-10 11:09:59 -060010833
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010834static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
10835{
10836 int mmu_reset_needed = 0;
10837 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
10838 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
10839 !(sregs2->efer & EFER_LMA);
10840 int i, ret;
Avi Kivity3842d132010-07-27 12:30:24 +030010841
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010842 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
10843 return -EINVAL;
10844
10845 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
10846 return -EINVAL;
10847
10848 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
10849 &mmu_reset_needed, !valid_pdptrs);
10850 if (ret)
10851 return ret;
10852
10853 if (valid_pdptrs) {
10854 for (i = 0; i < 4 ; i++)
10855 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
10856
10857 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
10858 mmu_reset_needed = 1;
Maxim Levitsky158a48e2021-06-07 12:02:03 +030010859 vcpu->arch.pdptrs_from_userspace = true;
Maxim Levitsky6dba9402021-06-07 12:02:02 +030010860 }
10861 if (mmu_reset_needed)
10862 kvm_mmu_reset_context(vcpu);
10863 return 0;
Ken Hofsass01643c52018-01-31 16:03:36 -080010864}
10865
10866int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
10867 struct kvm_sregs *sregs)
10868{
10869 int ret;
10870
10871 vcpu_load(vcpu);
10872 ret = __set_sregs(vcpu, sregs);
Christoffer Dallb4ef9d42017-12-04 21:35:29 +010010873 vcpu_put(vcpu);
10874 return ret;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010875}
10876
Maxim Levitskycae72dc2021-11-08 11:02:45 +020010877static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
10878{
10879 bool inhibit = false;
10880 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +000010881 unsigned long i;
Maxim Levitskycae72dc2021-11-08 11:02:45 +020010882
10883 down_write(&kvm->arch.apicv_update_lock);
10884
10885 kvm_for_each_vcpu(i, vcpu, kvm) {
10886 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
10887 inhibit = true;
10888 break;
10889 }
10890 }
10891 __kvm_request_apicv_update(kvm, !inhibit, APICV_INHIBIT_REASON_BLOCKIRQ);
10892 up_write(&kvm->arch.apicv_update_lock);
10893}
10894
Jan Kiszkad0bfb942008-12-15 13:52:10 +010010895int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
10896 struct kvm_guest_debug *dbg)
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010897{
Jan Kiszka355be0b2009-10-03 00:31:21 +020010898 unsigned long rflags;
Jan Kiszkaae675ef2008-12-15 13:52:10 +010010899 int i, r;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010900
Tom Lendacky8d4846b2020-12-10 11:09:43 -060010901 if (vcpu->arch.guest_state_protected)
10902 return -EINVAL;
10903
Christoffer Dall66b56562017-12-04 21:35:33 +010010904 vcpu_load(vcpu);
10905
Jan Kiszka4f926bf22009-10-30 12:46:59 +010010906 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
10907 r = -EBUSY;
10908 if (vcpu->arch.exception.pending)
Avi Kivity2122ff52010-05-13 11:25:04 +030010909 goto out;
Jan Kiszka4f926bf22009-10-30 12:46:59 +010010910 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
10911 kvm_queue_exception(vcpu, DB_VECTOR);
10912 else
10913 kvm_queue_exception(vcpu, BP_VECTOR);
10914 }
10915
Jan Kiszka91586a32009-10-05 13:07:21 +020010916 /*
10917 * Read rflags as long as potentially injected trace flags are still
10918 * filtered out.
10919 */
10920 rflags = kvm_get_rflags(vcpu);
Jan Kiszka355be0b2009-10-03 00:31:21 +020010921
10922 vcpu->guest_debug = dbg->control;
10923 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
10924 vcpu->guest_debug = 0;
10925
10926 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
Jan Kiszkaae675ef2008-12-15 13:52:10 +010010927 for (i = 0; i < KVM_NR_DB_REGS; ++i)
10928 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
Jan Kiszkac8639012012-09-21 05:42:55 +020010929 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
Jan Kiszkaae675ef2008-12-15 13:52:10 +010010930 } else {
10931 for (i = 0; i < KVM_NR_DB_REGS; i++)
10932 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
Jan Kiszkaae675ef2008-12-15 13:52:10 +010010933 }
Jan Kiszkac8639012012-09-21 05:42:55 +020010934 kvm_update_dr7(vcpu);
Jan Kiszkaae675ef2008-12-15 13:52:10 +010010935
Jan Kiszkaf92653e2010-02-23 17:47:55 +010010936 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
Yuan Yaoe87e46d2021-05-26 14:38:28 +080010937 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010938
Jan Kiszka91586a32009-10-05 13:07:21 +020010939 /*
10940 * Trigger an rflags update that will inject or remove the trace
10941 * flags.
10942 */
10943 kvm_set_rflags(vcpu, rflags);
Jan Kiszkad0bfb942008-12-15 13:52:10 +010010944
Jason Baronb36464772021-01-14 22:27:56 -050010945 static_call(kvm_x86_update_exception_bitmap)(vcpu);
Jan Kiszka355be0b2009-10-03 00:31:21 +020010946
Maxim Levitskycae72dc2021-11-08 11:02:45 +020010947 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
10948
Jan Kiszka4f926bf22009-10-30 12:46:59 +010010949 r = 0;
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010950
Avi Kivity2122ff52010-05-13 11:25:04 +030010951out:
Christoffer Dall66b56562017-12-04 21:35:33 +010010952 vcpu_put(vcpu);
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -050010953 return r;
10954}
10955
10956/*
Zhang Xiantao8b006792007-11-16 13:05:55 +080010957 * Translate a guest virtual address to a guest physical address.
10958 */
10959int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
10960 struct kvm_translation *tr)
10961{
10962 unsigned long vaddr = tr->linear_address;
10963 gpa_t gpa;
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010964 int idx;
Zhang Xiantao8b006792007-11-16 13:05:55 +080010965
Christoffer Dall1da5b612017-12-04 21:35:32 +010010966 vcpu_load(vcpu);
10967
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010968 idx = srcu_read_lock(&vcpu->kvm->srcu);
Gleb Natapov1871c602010-02-10 14:21:32 +020010969 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
Marcelo Tosattif656ce02009-12-23 14:35:25 -020010970 srcu_read_unlock(&vcpu->kvm->srcu, idx);
Zhang Xiantao8b006792007-11-16 13:05:55 +080010971 tr->physical_address = gpa;
10972 tr->valid = gpa != UNMAPPED_GVA;
10973 tr->writeable = 1;
10974 tr->usermode = 0;
Zhang Xiantao8b006792007-11-16 13:05:55 +080010975
Christoffer Dall1da5b612017-12-04 21:35:32 +010010976 vcpu_put(vcpu);
Zhang Xiantao8b006792007-11-16 13:05:55 +080010977 return 0;
10978}
10979
Hollis Blanchardd0752062007-10-31 17:24:25 -050010980int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
10981{
Christoffer Dall13931232017-12-04 21:35:34 +010010982 struct fxregs_state *fxsave;
Hollis Blanchardd0752062007-10-31 17:24:25 -050010983
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020010984 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
Tom Lendackyed02b212020-12-10 11:10:01 -060010985 return 0;
10986
Christoffer Dall13931232017-12-04 21:35:34 +010010987 vcpu_load(vcpu);
10988
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020010989 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
Hollis Blanchardd0752062007-10-31 17:24:25 -050010990 memcpy(fpu->fpr, fxsave->st_space, 128);
10991 fpu->fcw = fxsave->cwd;
10992 fpu->fsw = fxsave->swd;
10993 fpu->ftwx = fxsave->twd;
10994 fpu->last_opcode = fxsave->fop;
10995 fpu->last_ip = fxsave->rip;
10996 fpu->last_dp = fxsave->rdp;
Jordan Borgner0e96f312018-10-28 12:58:28 +000010997 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
Hollis Blanchardd0752062007-10-31 17:24:25 -050010998
Christoffer Dall13931232017-12-04 21:35:34 +010010999 vcpu_put(vcpu);
Hollis Blanchardd0752062007-10-31 17:24:25 -050011000 return 0;
11001}
11002
11003int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
11004{
Christoffer Dall6a96bc72017-12-04 21:35:35 +010011005 struct fxregs_state *fxsave;
11006
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011007 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
Tom Lendackyed02b212020-12-10 11:10:01 -060011008 return 0;
11009
Christoffer Dall6a96bc72017-12-04 21:35:35 +010011010 vcpu_load(vcpu);
11011
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011012 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
Hollis Blanchardd0752062007-10-31 17:24:25 -050011013
Hollis Blanchardd0752062007-10-31 17:24:25 -050011014 memcpy(fxsave->st_space, fpu->fpr, 128);
11015 fxsave->cwd = fpu->fcw;
11016 fxsave->swd = fpu->fsw;
11017 fxsave->twd = fpu->ftwx;
11018 fxsave->fop = fpu->last_opcode;
11019 fxsave->rip = fpu->last_ip;
11020 fxsave->rdp = fpu->last_dp;
Jordan Borgner0e96f312018-10-28 12:58:28 +000011021 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
Hollis Blanchardd0752062007-10-31 17:24:25 -050011022
Christoffer Dall6a96bc72017-12-04 21:35:35 +010011023 vcpu_put(vcpu);
Hollis Blanchardd0752062007-10-31 17:24:25 -050011024 return 0;
11025}
11026
Ken Hofsass01643c52018-01-31 16:03:36 -080011027static void store_regs(struct kvm_vcpu *vcpu)
11028{
11029 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
11030
11031 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
11032 __get_regs(vcpu, &vcpu->run->s.regs.regs);
11033
11034 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
11035 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
11036
11037 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
11038 kvm_vcpu_ioctl_x86_get_vcpu_events(
11039 vcpu, &vcpu->run->s.regs.events);
11040}
11041
11042static int sync_regs(struct kvm_vcpu *vcpu)
11043{
Ken Hofsass01643c52018-01-31 16:03:36 -080011044 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
11045 __set_regs(vcpu, &vcpu->run->s.regs.regs);
11046 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
11047 }
11048 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
11049 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
11050 return -EINVAL;
11051 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
11052 }
11053 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
11054 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
11055 vcpu, &vcpu->run->s.regs.events))
11056 return -EINVAL;
11057 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
11058 }
11059
11060 return 0;
11061}
11062
Sean Christopherson897cc382019-12-18 13:55:09 -080011063int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011064{
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +010011065 if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
Sean Christopherson897cc382019-12-18 13:55:09 -080011066 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
11067 "guest TSC will not be reliable\n");
Liang Lic447e762015-05-21 04:41:25 +080011068
Sean Christopherson897cc382019-12-18 13:55:09 -080011069 return 0;
Avi Kivity26e52152007-11-20 15:30:24 +020011070}
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011071
Sean Christophersone529ef62019-12-18 13:55:15 -080011072int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
Avi Kivity26e52152007-11-20 15:30:24 +020011073{
Sean Christopherson95a0d012019-12-18 13:55:23 -080011074 struct page *page;
11075 int r;
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011076
Sean Christopherson63f5a192021-06-22 10:56:52 -070011077 vcpu->arch.last_vmentry_cpu = -1;
Sean Christopherson71170032021-09-20 17:02:54 -070011078 vcpu->arch.regs_avail = ~0;
11079 vcpu->arch.regs_dirty = ~0;
Sean Christopherson63f5a192021-06-22 10:56:52 -070011080
Sean Christopherson95a0d012019-12-18 13:55:23 -080011081 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
11082 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11083 else
11084 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
11085
Sean Christopherson95a0d012019-12-18 13:55:23 -080011086 r = kvm_mmu_create(vcpu);
11087 if (r < 0)
11088 return r;
11089
11090 if (irqchip_in_kernel(vcpu->kvm)) {
Sean Christopherson95a0d012019-12-18 13:55:23 -080011091 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
11092 if (r < 0)
11093 goto fail_mmu_destroy;
Suravee Suthikulpanit4e19c362019-11-14 14:15:05 -060011094 if (kvm_apicv_activated(vcpu->kvm))
11095 vcpu->arch.apicv_active = true;
Sean Christopherson95a0d012019-12-18 13:55:23 -080011096 } else
Cun Li6e4e3b42021-01-11 23:24:35 +080011097 static_branch_inc(&kvm_has_noapic_vcpu);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011098
11099 r = -ENOMEM;
11100
Shakeel Butt93bb59c2020-12-18 14:01:38 -080011101 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011102 if (!page)
11103 goto fail_free_lapic;
11104 vcpu->arch.pio_data = page_address(page);
11105
11106 vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
11107 GFP_KERNEL_ACCOUNT);
11108 if (!vcpu->arch.mce_banks)
11109 goto fail_free_pio_data;
11110 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
11111
11112 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
11113 GFP_KERNEL_ACCOUNT))
11114 goto fail_free_mce_banks;
11115
Sean Christophersonc9b8b072020-02-18 15:29:48 -080011116 if (!alloc_emulate_ctxt(vcpu))
11117 goto free_wbinvd_dirty_mask;
11118
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011119 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
11120 pr_err("kvm: failed to allocate vcpu's fpu\n");
Sean Christophersonc9b8b072020-02-18 15:29:48 -080011121 goto free_emulate_ctxt;
Sean Christopherson95a0d012019-12-18 13:55:23 -080011122 }
11123
Sean Christopherson95a0d012019-12-18 13:55:23 -080011124 vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
Sean Christophersona8ac8642021-02-03 16:01:15 -080011125 vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011126
11127 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
11128
11129 kvm_async_pf_hash_reset(vcpu);
11130 kvm_pmu_init(vcpu);
11131
11132 vcpu->arch.pending_external_vector = -1;
11133 vcpu->arch.preempted_in_kernel = false;
11134
Vineeth Pillai3c86c0d2021-06-03 15:14:36 +000011135#if IS_ENABLED(CONFIG_HYPERV)
11136 vcpu->arch.hv_root_tdp = INVALID_PAGE;
11137#endif
11138
Jason Baronb36464772021-01-14 22:27:56 -050011139 r = static_call(kvm_x86_vcpu_create)(vcpu);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011140 if (r)
11141 goto free_guest_fpu;
Sean Christopherson5f73db12019-12-18 13:55:18 -080011142
Sean Christopherson0cf91352019-03-07 15:43:02 -080011143 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
Jim Mattsone53d88af2018-10-30 12:20:21 -070011144 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
Xiao Guangrong19efffa2015-06-15 16:55:31 +080011145 kvm_vcpu_mtrr_init(vcpu);
Christoffer Dallec7660c2017-12-04 21:35:23 +010011146 vcpu_load(vcpu);
Ilias Stamatis1ab92872021-06-07 11:54:38 +010011147 kvm_set_tsc_khz(vcpu, max_tsc_khz);
Nadav Amitd28bc9d2015-04-13 14:34:08 +030011148 kvm_vcpu_reset(vcpu, false);
Sean Christophersonc9060662021-06-09 16:42:33 -070011149 kvm_init_mmu(vcpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011150 vcpu_put(vcpu);
Christoffer Dallec7660c2017-12-04 21:35:23 +010011151 return 0;
Sean Christopherson95a0d012019-12-18 13:55:23 -080011152
11153free_guest_fpu:
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011154 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
Sean Christophersonc9b8b072020-02-18 15:29:48 -080011155free_emulate_ctxt:
11156 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011157free_wbinvd_dirty_mask:
11158 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
11159fail_free_mce_banks:
11160 kfree(vcpu->arch.mce_banks);
11161fail_free_pio_data:
11162 free_page((unsigned long)vcpu->arch.pio_data);
11163fail_free_lapic:
11164 kvm_free_lapic(vcpu);
11165fail_mmu_destroy:
11166 kvm_mmu_destroy(vcpu);
11167 return r;
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011168}
11169
Dominik Dingel31928aa2014-12-04 15:47:07 +010011170void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
Marcelo Tosatti42897d82012-11-27 23:29:02 -020011171{
Andrew Jones332967a2014-02-28 12:52:55 +010011172 struct kvm *kvm = vcpu->kvm;
Marcelo Tosatti42897d82012-11-27 23:29:02 -020011173
Christoffer Dallec7660c2017-12-04 21:35:23 +010011174 if (mutex_lock_killable(&vcpu->mutex))
Dominik Dingel31928aa2014-12-04 15:47:07 +010011175 return;
Christoffer Dallec7660c2017-12-04 21:35:23 +010011176 vcpu_load(vcpu);
Paolo Bonzini0c899c22020-09-24 14:45:27 +020011177 kvm_synchronize_tsc(vcpu, 0);
Marcelo Tosatti42897d82012-11-27 23:29:02 -020011178 vcpu_put(vcpu);
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -030011179
11180 /* poll control enabled by default */
11181 vcpu->arch.msr_kvm_poll_control = 1;
11182
Christoffer Dallec7660c2017-12-04 21:35:23 +010011183 mutex_unlock(&vcpu->mutex);
Marcelo Tosatti42897d82012-11-27 23:29:02 -020011184
Wanpeng Lib34de572020-02-28 11:18:41 +080011185 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
11186 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
11187 KVMCLOCK_SYNC_PERIOD);
Marcelo Tosatti42897d82012-11-27 23:29:02 -020011188}
11189
Hollis Blanchardd40ccc62007-11-19 14:04:43 -060011190void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011191{
Sean Christopherson95a0d012019-12-18 13:55:23 -080011192 int idx;
Gleb Natapov344d9582010-10-14 11:22:50 +020011193
Sean Christopherson50b143e2019-12-18 13:55:07 -080011194 kvmclock_reset(vcpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011195
Jason Baronb36464772021-01-14 22:27:56 -050011196 static_call(kvm_x86_vcpu_free)(vcpu);
Sean Christopherson50b143e2019-12-18 13:55:07 -080011197
Sean Christophersonc9b8b072020-02-18 15:29:48 -080011198 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
Sean Christopherson50b143e2019-12-18 13:55:07 -080011199 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011200 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011201
11202 kvm_hv_vcpu_uninit(vcpu);
11203 kvm_pmu_destroy(vcpu);
11204 kfree(vcpu->arch.mce_banks);
11205 kvm_free_lapic(vcpu);
11206 idx = srcu_read_lock(&vcpu->kvm->srcu);
11207 kvm_mmu_destroy(vcpu);
11208 srcu_read_unlock(&vcpu->kvm->srcu, idx);
11209 free_page((unsigned long)vcpu->arch.pio_data);
Vitaly Kuznetsov255cbec2020-10-01 15:05:40 +020011210 kvfree(vcpu->arch.cpuid_entries);
Sean Christopherson95a0d012019-12-18 13:55:23 -080011211 if (!lapic_in_kernel(vcpu))
Cun Li6e4e3b42021-01-11 23:24:35 +080011212 static_branch_dec(&kvm_has_noapic_vcpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011213}
11214
Nadav Amitd28bc9d2015-04-13 14:34:08 +030011215void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011216{
Sean Christopherson25b97842021-09-29 15:24:26 -070011217 struct kvm_cpuid_entry2 *cpuid_0x1;
Sean Christopherson0aa18372021-06-22 10:56:48 -070011218 unsigned long old_cr0 = kvm_read_cr0(vcpu);
Sean Christopherson4c72ab52021-07-13 09:33:24 -070011219 unsigned long new_cr0;
Sean Christopherson0aa18372021-06-22 10:56:48 -070011220
Sean Christopherson62dd57d2021-09-20 17:03:03 -070011221 /*
11222 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
11223 * to handle side effects. RESET emulation hits those flows and relies
11224 * on emulated/virtualized registers, including those that are loaded
11225 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
11226 * to detect improper or missing initialization.
11227 */
11228 WARN_ON_ONCE(!init_event &&
11229 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011230
Radim Krčmářb7e31be2018-03-01 15:24:25 +010011231 kvm_lapic_reset(vcpu, init_event);
11232
Paolo Bonzinie69fab52015-06-04 10:44:44 +020011233 vcpu->arch.hflags = 0;
11234
Paolo Bonzinic43203c2016-06-01 22:26:00 +020011235 vcpu->arch.smi_pending = 0;
Liran Alon52797bf2017-11-15 13:43:14 +020011236 vcpu->arch.smi_count = 0;
Avi Kivity7460fb4a2011-09-20 13:43:14 +030011237 atomic_set(&vcpu->arch.nmi_queued, 0);
11238 vcpu->arch.nmi_pending = 0;
Jan Kiszka448fa4a2008-09-26 09:30:48 +020011239 vcpu->arch.nmi_injected = false;
Nadav Amit5f7552d2014-06-30 12:03:02 +030011240 kvm_clear_interrupt_queue(vcpu);
11241 kvm_clear_exception_queue(vcpu);
Jan Kiszka448fa4a2008-09-26 09:30:48 +020011242
Jan Kiszka42dbaa52008-12-15 13:52:10 +010011243 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
Nadav Amitae561ed2015-04-02 03:10:37 +030011244 kvm_update_dr0123(vcpu);
Chenyi Qiang9a3ecd52021-02-02 17:04:31 +080011245 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
Jan Kiszka42dbaa52008-12-15 13:52:10 +010011246 vcpu->arch.dr7 = DR7_FIXED_1;
Jan Kiszkac8639012012-09-21 05:42:55 +020011247 kvm_update_dr7(vcpu);
Jan Kiszka42dbaa52008-12-15 13:52:10 +010011248
Nadav Amit11190222015-04-02 03:10:38 +030011249 vcpu->arch.cr2 = 0;
11250
Avi Kivity3842d132010-07-27 12:30:24 +030011251 kvm_make_request(KVM_REQ_EVENT, vcpu);
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020011252 vcpu->arch.apf.msr_en_val = 0;
11253 vcpu->arch.apf.msr_int_val = 0;
Glauber Costac9aaa892011-07-11 15:28:14 -040011254 vcpu->arch.st.msr_val = 0;
Avi Kivity3842d132010-07-27 12:30:24 +030011255
Glauber Costa12f9a482011-02-01 14:16:40 -050011256 kvmclock_reset(vcpu);
11257
Gleb Natapovaf585b92010-10-14 11:22:46 +020011258 kvm_clear_async_pf_completion_queue(vcpu);
11259 kvm_async_pf_hash_reset(vcpu);
11260 vcpu->arch.apf.halted = false;
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011261
Thomas Gleixnerd69c1382021-10-22 20:55:53 +020011262 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
11263 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
Wanpeng Lia554d202017-10-11 05:10:19 -070011264
11265 /*
11266 * To avoid have the INIT path from kvm_apic_has_events() that be
11267 * called with loaded FPU and does not let userspace fix the state.
11268 */
Rik van Rielf775b132017-11-14 16:54:23 -050011269 if (init_event)
11270 kvm_put_guest_fpu(vcpu);
Thomas Gleixner087df482021-10-13 16:55:31 +020011271
11272 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
11273 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
11274
Rik van Rielf775b132017-11-14 16:54:23 -050011275 if (init_event)
11276 kvm_load_guest_fpu(vcpu);
Wanpeng Lia554d202017-10-11 05:10:19 -070011277 }
11278
Paolo Bonzini64d60672015-05-07 11:36:11 +020011279 if (!init_event) {
Nadav Amitd28bc9d2015-04-13 14:34:08 +030011280 kvm_pmu_reset(vcpu);
Paolo Bonzini64d60672015-05-07 11:36:11 +020011281 vcpu->arch.smbase = 0x30000;
Kyle Hueydb2336a2017-03-20 01:16:28 -070011282
Kyle Hueydb2336a2017-03-20 01:16:28 -070011283 vcpu->arch.msr_misc_features_enables = 0;
Wanpeng Lia554d202017-10-11 05:10:19 -070011284
Like Xu05a9e062022-01-26 17:22:26 +000011285 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
11286 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
Paolo Bonzini64d60672015-05-07 11:36:11 +020011287 }
Gleb Natapovf5132b02011-11-10 14:57:22 +020011288
Sean Christophersonff8828c2021-09-20 17:02:56 -070011289 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
Julian Stecklina66f7b722012-12-05 15:26:19 +010011290 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
Sean Christophersonff8828c2021-09-20 17:02:56 -070011291 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
Julian Stecklina66f7b722012-12-05 15:26:19 +010011292
Sean Christopherson49d86652021-07-13 09:32:57 -070011293 /*
11294 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
11295 * if no CPUID match is found. Note, it's impossible to get a match at
11296 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
Sean Christopherson25b97842021-09-29 15:24:26 -070011297 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
11298 * on RESET. But, go through the motions in case that's ever remedied.
Sean Christopherson49d86652021-07-13 09:32:57 -070011299 */
Sean Christopherson25b97842021-09-29 15:24:26 -070011300 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1, 0);
11301 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
Sean Christopherson49d86652021-07-13 09:32:57 -070011302
Jason Baronb36464772021-01-14 22:27:56 -050011303 static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
Sean Christopherson0aa18372021-06-22 10:56:48 -070011304
Sean Christophersonf39e8052021-07-13 09:33:14 -070011305 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
11306 kvm_rip_write(vcpu, 0xfff0);
11307
Sean Christopherson03a6e842021-09-20 17:02:55 -070011308 vcpu->arch.cr3 = 0;
11309 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11310
Sean Christopherson4c72ab52021-07-13 09:33:24 -070011311 /*
11312 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
11313 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
11314 * (or qualify) that with a footnote stating that CD/NW are preserved.
11315 */
11316 new_cr0 = X86_CR0_ET;
11317 if (init_event)
11318 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
11319 else
11320 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
11321
11322 static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
Sean Christophersonf39e8052021-07-13 09:33:14 -070011323 static_call(kvm_x86_set_cr4)(vcpu, 0);
11324 static_call(kvm_x86_set_efer)(vcpu, 0);
11325 static_call(kvm_x86_update_exception_bitmap)(vcpu);
11326
Sean Christopherson0aa18372021-06-22 10:56:48 -070011327 /*
11328 * Reset the MMU context if paging was enabled prior to INIT (which is
11329 * implied if CR0.PG=1 as CR0 will be '0' prior to RESET). Unlike the
11330 * standard CR0/CR4/EFER modification paths, only CR0.PG needs to be
11331 * checked because it is unconditionally cleared on INIT and all other
11332 * paging related bits are ignored if paging is disabled, i.e. CR0.WP,
11333 * CR4, and EFER changes are all irrelevant if CR0.PG was '0'.
11334 */
11335 if (old_cr0 & X86_CR0_PG)
11336 kvm_mmu_reset_context(vcpu);
Sean Christophersondf37ed32021-07-13 09:32:39 -070011337
11338 /*
11339 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
11340 * APM states the TLBs are untouched by INIT, but it also states that
11341 * the TLBs are flushed on "External initialization of the processor."
11342 * Flush the guest TLB regardless of vendor, there is no meaningful
11343 * benefit in relying on the guest to flush the TLB immediately after
11344 * INIT. A spurious TLB flush is benign and likely negligible from a
11345 * performance perspective.
11346 */
11347 if (init_event)
11348 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011349}
Sean Christopherson265e4352021-07-13 09:33:22 -070011350EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011351
Paolo Bonzini2b4a2732014-11-24 14:35:24 +010011352void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
Jan Kiszka66450a22013-03-13 12:42:34 +010011353{
11354 struct kvm_segment cs;
11355
11356 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
11357 cs.selector = vector << 8;
11358 cs.base = vector << 12;
11359 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
11360 kvm_rip_write(vcpu, 0);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011361}
Tom Lendacky647daca2021-01-04 14:20:01 -060011362EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011363
Radim Krčmář13a34e02014-08-28 15:13:03 +020011364int kvm_arch_hardware_enable(void)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011365{
Zachary Amsdenca84d1a2010-08-19 22:07:28 -100011366 struct kvm *kvm;
11367 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +000011368 unsigned long i;
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011369 int ret;
11370 u64 local_tsc;
11371 u64 max_tsc = 0;
11372 bool stable, backwards_tsc = false;
Avi Kivity18863bd2009-09-07 11:12:18 +030011373
Sean Christopherson7e34fbd2020-09-23 11:03:55 -070011374 kvm_user_return_msr_cpu_online();
Jason Baronb36464772021-01-14 22:27:56 -050011375 ret = static_call(kvm_x86_hardware_enable)();
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011376 if (ret != 0)
11377 return ret;
11378
Andy Lutomirski4ea16362015-06-25 18:44:07 +020011379 local_tsc = rdtsc();
Vitaly Kuznetsovb0c39dc2018-01-24 14:23:36 +010011380 stable = !kvm_check_tsc_unstable();
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011381 list_for_each_entry(kvm, &vm_list, vm_list) {
11382 kvm_for_each_vcpu(i, vcpu, kvm) {
11383 if (!stable && vcpu->cpu == smp_processor_id())
Guo Hui Liu105b21b2014-09-12 13:43:19 +080011384 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011385 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
11386 backwards_tsc = true;
11387 if (vcpu->arch.last_host_tsc > max_tsc)
11388 max_tsc = vcpu->arch.last_host_tsc;
11389 }
11390 }
11391 }
11392
11393 /*
11394 * Sometimes, even reliable TSCs go backwards. This happens on
11395 * platforms that reset TSC during suspend or hibernate actions, but
11396 * maintain synchronization. We must compensate. Fortunately, we can
11397 * detect that condition here, which happens early in CPU bringup,
11398 * before any KVM threads can be running. Unfortunately, we can't
11399 * bring the TSCs fully up to date with real time, as we aren't yet far
11400 * enough into CPU bringup that we know how much real time has actually
Jason A. Donenfeld9285ec42019-06-21 22:32:48 +020011401 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011402 * variables that haven't been updated yet.
11403 *
11404 * So we simply find the maximum observed TSC above, then record the
11405 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
11406 * the adjustment will be applied. Note that we accumulate
11407 * adjustments, in case multiple suspend cycles happen before some VCPU
11408 * gets a chance to run again. In the event that no KVM threads get a
11409 * chance to run, we will miss the entire elapsed period, as we'll have
11410 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
11411 * loose cycle time. This isn't too big a deal, since the loss will be
11412 * uniform across all VCPUs (not to mention the scenario is extremely
11413 * unlikely). It is possible that a second hibernate recovery happens
11414 * much faster than a first, causing the observed TSC here to be
11415 * smaller; this would require additional padding adjustment, which is
11416 * why we set last_host_tsc to the local tsc observed here.
11417 *
11418 * N.B. - this code below runs only on platforms with reliable TSC,
11419 * as that is the only way backwards_tsc is set above. Also note
11420 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
11421 * have the same delta_cyc adjustment applied if backwards_tsc
11422 * is detected. Note further, this adjustment is only done once,
11423 * as we reset last_host_tsc on all VCPUs to stop this from being
11424 * called multiple times (one for each physical CPU bringup).
11425 *
Guo Chao4a969982012-06-28 15:17:27 +080011426 * Platforms with unreliable TSCs don't have to deal with this, they
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011427 * will be compensated by the logic in vcpu_load, which sets the TSC to
11428 * catchup mode. This will catchup all VCPUs to real time, but cannot
11429 * guarantee that they stay in perfect synchronization.
11430 */
11431 if (backwards_tsc) {
11432 u64 delta_cyc = max_tsc - local_tsc;
11433 list_for_each_entry(kvm, &vm_list, vm_list) {
Ladi Proseka826faf2017-06-26 09:56:43 +020011434 kvm->arch.backwards_tsc_observed = true;
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011435 kvm_for_each_vcpu(i, vcpu, kvm) {
11436 vcpu->arch.tsc_offset_adjustment += delta_cyc;
11437 vcpu->arch.last_host_tsc = local_tsc;
Guo Hui Liu105b21b2014-09-12 13:43:19 +080011438 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
Zachary Amsden0dd6a6e2012-02-03 15:43:56 -020011439 }
11440
11441 /*
11442 * We have to disable TSC offset matching.. if you were
11443 * booting a VM while issuing an S4 host suspend....
11444 * you may have some problem. Solving this issue is
11445 * left as an exercise to the reader.
11446 */
11447 kvm->arch.last_tsc_nsec = 0;
11448 kvm->arch.last_tsc_write = 0;
11449 }
11450
11451 }
11452 return 0;
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011453}
11454
Radim Krčmář13a34e02014-08-28 15:13:03 +020011455void kvm_arch_hardware_disable(void)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011456{
Jason Baronb36464772021-01-14 22:27:56 -050011457 static_call(kvm_x86_hardware_disable)();
Radim Krčmář13a34e02014-08-28 15:13:03 +020011458 drop_user_return_notifiers();
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011459}
11460
Sean Christophersonb9904082020-03-21 13:25:55 -070011461int kvm_arch_hardware_setup(void *opaque)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011462{
Sean Christophersond008dfd2020-03-21 13:25:56 -070011463 struct kvm_x86_init_ops *ops = opaque;
Nadav Amit9e9c3fe2015-04-12 21:47:15 +030011464 int r;
11465
Sean Christopherson91661982020-03-02 15:57:06 -080011466 rdmsrl_safe(MSR_EFER, &host_efer);
11467
Paolo Bonzini408e9a32020-03-05 16:11:56 +010011468 if (boot_cpu_has(X86_FEATURE_XSAVES))
11469 rdmsrl(MSR_IA32_XSS, host_xss);
11470
Sean Christophersond008dfd2020-03-21 13:25:56 -070011471 r = ops->hardware_setup();
Nadav Amit9e9c3fe2015-04-12 21:47:15 +030011472 if (r != 0)
11473 return r;
11474
Sean Christophersonafaf0b22020-03-21 13:26:00 -070011475 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
Jason Baronb36464772021-01-14 22:27:56 -050011476 kvm_ops_static_call_update();
Sean Christopherson69c6f692020-03-21 13:25:59 -070011477
Sean Christopherson33271a92021-11-11 02:07:34 +000011478 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
Sean Christopherson5c7df802021-11-11 02:07:23 +000011479
Paolo Bonzini408e9a32020-03-05 16:11:56 +010011480 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
11481 supported_xss = 0;
11482
Paolo Bonzini139f7422020-05-05 09:40:46 -040011483#define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
11484 cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
11485#undef __kvm_cpu_cap_has
Sean Christophersonb11306b2019-12-10 14:44:13 -080011486
Haozhong Zhang35181e82015-10-20 15:39:03 +080011487 if (kvm_has_tsc_control) {
11488 /*
11489 * Make sure the user can only configure tsc_khz values that
11490 * fit into a signed integer.
Marcelo Tosatti273ba452018-06-11 14:12:10 -030011491 * A min value is not calculated because it will always
Haozhong Zhang35181e82015-10-20 15:39:03 +080011492 * be 1 on all machines.
11493 */
11494 u64 max = min(0x7fffffffULL,
11495 __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
11496 kvm_max_guest_tsc_khz = max;
11497
Haozhong Zhangad7218832015-10-20 15:39:02 +080011498 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
Haozhong Zhang35181e82015-10-20 15:39:03 +080011499 }
Haozhong Zhangad7218832015-10-20 15:39:02 +080011500
Nadav Amit9e9c3fe2015-04-12 21:47:15 +030011501 kvm_init_msr_list();
11502 return 0;
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011503}
11504
11505void kvm_arch_hardware_unsetup(void)
11506{
Sean Christophersone1bfc242021-11-11 02:07:33 +000011507 kvm_unregister_perf_callbacks();
Sean Christopherson5c7df802021-11-11 02:07:23 +000011508
Jason Baronb36464772021-01-14 22:27:56 -050011509 static_call(kvm_x86_hardware_unsetup)();
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011510}
11511
Sean Christophersonb9904082020-03-21 13:25:55 -070011512int kvm_arch_check_processor_compat(void *opaque)
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011513{
Sean Christophersonf1cdecf2019-12-10 14:44:14 -080011514 struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
Sean Christophersond008dfd2020-03-21 13:25:56 -070011515 struct kvm_x86_init_ops *ops = opaque;
Sean Christophersonf1cdecf2019-12-10 14:44:14 -080011516
11517 WARN_ON(!irqs_disabled());
11518
Paolo Bonzini139f7422020-05-05 09:40:46 -040011519 if (__cr4_reserved_bits(cpu_has, c) !=
11520 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
Sean Christophersonf1cdecf2019-12-10 14:44:14 -080011521 return -EIO;
11522
Sean Christophersond008dfd2020-03-21 13:25:56 -070011523 return ops->check_processor_compatibility();
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +080011524}
11525
Paolo Bonzinid71ba782015-07-29 11:56:48 +020011526bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
11527{
11528 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
11529}
11530EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
11531
11532bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
11533{
11534 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
11535}
11536
Cun Li6e4e3b42021-01-11 23:24:35 +080011537__read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
11538EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
Gleb Natapov54e98182012-08-05 15:58:32 +030011539
Radim Krčmáře790d9e2014-08-21 18:08:05 +020011540void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
11541{
Like Xub35e5542019-10-27 18:52:43 +080011542 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
11543
Paolo Bonzinic595cee2018-07-02 13:07:14 +020011544 vcpu->arch.l1tf_flush_l1d = true;
Like Xub35e5542019-10-27 18:52:43 +080011545 if (pmu->version && unlikely(pmu->event_count)) {
11546 pmu->need_cleanup = true;
11547 kvm_make_request(KVM_REQ_PMU, vcpu);
11548 }
Jason Baronb36464772021-01-14 22:27:56 -050011549 static_call(kvm_x86_sched_in)(vcpu, cpu);
Radim Krčmáře790d9e2014-08-21 18:08:05 +020011550}
11551
Sean Christopherson562b6b02020-01-26 16:41:13 -080011552void kvm_arch_free_vm(struct kvm *kvm)
11553{
Vitaly Kuznetsov05f04ae2021-01-26 14:48:09 +010011554 kfree(to_kvm_hv(kvm)->hv_pa_pg);
Juergen Gross78b497f2021-09-03 15:08:05 +020011555 __kvm_arch_free_vm(kvm);
Sean Christopherson562b6b02020-01-26 16:41:13 -080011556}
11557
11558
Carsten Ottee08b9632012-01-04 10:25:20 +010011559int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011560{
Haimin Zhangeb7511b2021-09-03 10:37:06 +080011561 int ret;
Paolo Bonzini869b4422021-09-16 18:15:36 +000011562 unsigned long flags;
Haimin Zhangeb7511b2021-09-03 10:37:06 +080011563
Carsten Ottee08b9632012-01-04 10:25:20 +010011564 if (type)
11565 return -EINVAL;
11566
Haimin Zhangeb7511b2021-09-03 10:37:06 +080011567 ret = kvm_page_track_init(kvm);
11568 if (ret)
11569 return ret;
11570
Paolo Bonzini6ef768f2014-11-20 13:45:31 +010011571 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
Zhang Xiantaof05e70a2007-12-14 10:01:48 +080011572 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
Sean Christopherson10605202019-09-12 19:46:10 -070011573 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
Junaid Shahid1aa9b952019-11-04 20:26:00 +010011574 INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
Ben-Ami Yassour4d5c5d02008-07-28 19:26:26 +030011575 INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
Alex Williamsone0f0bbc2013-10-30 11:02:30 -060011576 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011577
Sheng Yang5550af42008-10-15 20:15:06 +080011578 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
11579 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
Alex Williamson7a844282012-09-21 11:58:03 -060011580 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
11581 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
11582 &kvm->arch.irq_sources_bitmap);
Sheng Yang5550af42008-10-15 20:15:06 +080011583
Jan Kiszka038f8c12011-02-04 10:49:11 +010011584 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
Gleb Natapov1e08ec42012-09-13 17:19:24 +030011585 mutex_init(&kvm->arch.apic_map_lock);
Paolo Bonzini869b4422021-09-16 18:15:36 +000011586 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
Paolo Bonzini8171cd62020-01-22 14:36:09 +010011587 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
Paolo Bonzini869b4422021-09-16 18:15:36 +000011588
11589 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
Marcelo Tosattid8281992012-11-27 23:29:01 -020011590 pvclock_update_vm_gtod_copy(kvm);
Paolo Bonzini869b4422021-09-16 18:15:36 +000011591 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
Marcelo Tosatti53f658b32008-12-11 20:45:05 +010011592
Drew Schmitt6fbbde92018-08-20 10:32:15 -070011593 kvm->arch.guest_can_read_msr_platform_info = true;
11594
Vineeth Pillai3c86c0d2021-06-03 15:14:36 +000011595#if IS_ENABLED(CONFIG_HYPERV)
11596 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
11597 kvm->arch.hv_root_tdp = INVALID_PAGE;
11598#endif
11599
Andrew Jones7e44e442014-02-28 12:52:54 +010011600 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
Andrew Jones332967a2014-02-28 12:52:55 +010011601 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
Andrew Jones7e44e442014-02-28 12:52:54 +010011602
Vitaly Kuznetsov4651fc52021-06-09 17:09:09 +020011603 kvm_apicv_init(kvm);
Roman Kagancbc02362018-02-01 16:48:31 +030011604 kvm_hv_init_vm(kvm);
Xiao Guangrong13d268c2016-02-24 17:51:16 +080011605 kvm_mmu_init_vm(kvm);
Paolo Bonzini319afe62021-08-04 12:48:41 -040011606 kvm_xen_init_vm(kvm);
Xiao Guangrong0eb05bf2016-02-24 17:51:13 +080011607
Jason Baronb36464772021-01-14 22:27:56 -050011608 return static_call(kvm_x86_vm_init)(kvm);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011609}
11610
Junaid Shahid1aa9b952019-11-04 20:26:00 +010011611int kvm_arch_post_init_vm(struct kvm *kvm)
11612{
11613 return kvm_mmu_post_init_vm(kvm);
11614}
11615
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011616static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
11617{
Christoffer Dallec7660c2017-12-04 21:35:23 +010011618 vcpu_load(vcpu);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011619 kvm_mmu_unload(vcpu);
11620 vcpu_put(vcpu);
11621}
11622
11623static void kvm_free_vcpus(struct kvm *kvm)
11624{
Marc Zyngier46808a42021-11-16 16:04:02 +000011625 unsigned long i;
Gleb Natapov988a2ca2009-06-09 15:56:29 +030011626 struct kvm_vcpu *vcpu;
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011627
11628 /*
11629 * Unpin any mmu pages first.
11630 */
Gleb Natapovaf585b92010-10-14 11:22:46 +020011631 kvm_for_each_vcpu(i, vcpu, kvm) {
11632 kvm_clear_async_pf_completion_queue(vcpu);
Gleb Natapov988a2ca2009-06-09 15:56:29 +030011633 kvm_unload_vcpu_mmu(vcpu);
Gleb Natapovaf585b92010-10-14 11:22:46 +020011634 }
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011635
Marc Zyngier27592ae2021-11-16 16:03:57 +000011636 kvm_destroy_vcpus(kvm);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011637}
11638
Sheng Yangad8ba2c2009-01-06 10:03:02 +080011639void kvm_arch_sync_events(struct kvm *kvm)
11640{
Andrew Jones332967a2014-02-28 12:52:55 +010011641 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
Andrew Jones7e44e442014-02-28 12:52:54 +010011642 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
Xiao Guangrongaea924f2010-07-10 17:37:56 +080011643 kvm_free_pit(kvm);
Sheng Yangad8ba2c2009-01-06 10:03:02 +080011644}
11645
Peter Xuff5a9832020-09-30 21:20:33 -040011646/**
11647 * __x86_set_memory_region: Setup KVM internal memory slot
11648 *
11649 * @kvm: the kvm pointer to the VM.
11650 * @id: the slot ID to setup.
11651 * @gpa: the GPA to install the slot (unused when @size == 0).
11652 * @size: the size of the slot. Set to zero to uninstall a slot.
11653 *
11654 * This function helps to setup a KVM internal memory slot. Specify
11655 * @size > 0 to install a new slot, while @size == 0 to uninstall a
11656 * slot. The return code can be one of the following:
11657 *
11658 * HVA: on success (uninstall will return a bogus HVA)
11659 * -errno: on error
11660 *
11661 * The caller should always use IS_ERR() to check the return value
11662 * before use. Note, the KVM internal memory slots are guaranteed to
11663 * remain valid and unchanged until the VM is destroyed, i.e., the
11664 * GPA->HVA translation will not change. However, the HVA is a user
11665 * address, i.e. its accessibility is not guaranteed, and must be
11666 * accessed via __copy_{to,from}_user().
11667 */
11668void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
11669 u32 size)
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011670{
11671 int i, r;
Kees Cook3f649ab2020-06-03 13:09:38 -070011672 unsigned long hva, old_npages;
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011673 struct kvm_memslots *slots = kvm_memslots(kvm);
Sean Christopherson0577d1a2020-02-18 13:07:31 -080011674 struct kvm_memory_slot *slot;
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011675
11676 /* Called with kvm->slots_lock held. */
Paolo Bonzini1d8007b2015-10-12 13:38:32 +020011677 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
Peter Xuff5a9832020-09-30 21:20:33 -040011678 return ERR_PTR_USR(-EINVAL);
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011679
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011680 slot = id_to_memslot(slots, id);
11681 if (size) {
Sean Christopherson0577d1a2020-02-18 13:07:31 -080011682 if (slot && slot->npages)
Peter Xuff5a9832020-09-30 21:20:33 -040011683 return ERR_PTR_USR(-EEXIST);
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011684
11685 /*
11686 * MAP_SHARED to prevent internal slot pages from being moved
11687 * by fork()/COW.
11688 */
11689 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
11690 MAP_SHARED | MAP_ANONYMOUS, 0);
11691 if (IS_ERR((void *)hva))
Peter Xuff5a9832020-09-30 21:20:33 -040011692 return (void __user *)hva;
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011693 } else {
Sean Christopherson0577d1a2020-02-18 13:07:31 -080011694 if (!slot || !slot->npages)
Muhammad Usama Anjum46914532021-03-05 23:08:16 +050011695 return NULL;
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011696
Sean Christopherson0577d1a2020-02-18 13:07:31 -080011697 old_npages = slot->npages;
Zheng Zhan Liangb66f9ba2021-02-01 13:53:10 +080011698 hva = slot->userspace_addr;
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011699 }
11700
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011701 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
Paolo Bonzini1d8007b2015-10-12 13:38:32 +020011702 struct kvm_userspace_memory_region m;
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011703
Paolo Bonzini1d8007b2015-10-12 13:38:32 +020011704 m.slot = id | (i << 16);
11705 m.flags = 0;
11706 m.guest_phys_addr = gpa;
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011707 m.userspace_addr = hva;
Paolo Bonzini1d8007b2015-10-12 13:38:32 +020011708 m.memory_size = size;
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011709 r = __kvm_set_memory_region(kvm, &m);
11710 if (r < 0)
Peter Xuff5a9832020-09-30 21:20:33 -040011711 return ERR_PTR_USR(r);
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011712 }
11713
Eric Biggers103c7632018-01-31 17:30:21 -080011714 if (!size)
Sean Christopherson0577d1a2020-02-18 13:07:31 -080011715 vm_munmap(hva, old_npages * PAGE_SIZE);
Paolo Bonzinif0d648b2015-10-12 13:56:27 +020011716
Peter Xuff5a9832020-09-30 21:20:33 -040011717 return (void __user *)hva;
Paolo Bonzini9da0e4d2015-05-18 13:33:16 +020011718}
11719EXPORT_SYMBOL_GPL(__x86_set_memory_region);
11720
Junaid Shahid1aa9b952019-11-04 20:26:00 +010011721void kvm_arch_pre_destroy_vm(struct kvm *kvm)
11722{
11723 kvm_mmu_pre_destroy_vm(kvm);
11724}
11725
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011726void kvm_arch_destroy_vm(struct kvm *kvm)
11727{
Andrew Honig27469d22013-04-18 09:38:14 -070011728 if (current->mm == kvm->mm) {
11729 /*
11730 * Free memory regions allocated on behalf of userspace,
11731 * unless the the memory map has changed due to process exit
11732 * or fd copying.
11733 */
Peter Xu6a3c6232020-01-09 09:57:16 -050011734 mutex_lock(&kvm->slots_lock);
11735 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
11736 0, 0);
11737 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
11738 0, 0);
11739 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
11740 mutex_unlock(&kvm->slots_lock);
Andrew Honig27469d22013-04-18 09:38:14 -070011741 }
Jason Baronb36464772021-01-14 22:27:56 -050011742 static_call_cond(kvm_x86_vm_destroy)(kvm);
Sean Christophersonb318e8d2021-03-16 11:44:33 -070011743 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
Peter Xuc7611592017-03-15 16:01:19 +080011744 kvm_pic_destroy(kvm);
11745 kvm_ioapic_destroy(kvm);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011746 kvm_free_vcpus(kvm);
Radim Krčmářaf1bae52016-07-12 22:09:30 +020011747 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
Eric Hankland66bb8a02019-07-10 18:25:15 -070011748 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
Xiao Guangrong13d268c2016-02-24 17:51:16 +080011749 kvm_mmu_uninit_vm(kvm);
Paolo Bonzini2beb6dad2017-03-27 17:53:50 +020011750 kvm_page_track_cleanup(kvm);
David Woodhouse7d6bbeb2021-02-02 15:48:05 +000011751 kvm_xen_destroy_vm(kvm);
Roman Kagancbc02362018-02-01 16:48:31 +030011752 kvm_hv_destroy_vm(kvm);
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +080011753}
Zhang Xiantao0de10342007-11-20 16:25:04 +080011754
Ben Gardonc9b929b2021-05-18 10:34:08 -070011755static void memslot_rmap_free(struct kvm_memory_slot *slot)
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011756{
11757 int i;
11758
Takuya Yoshikawad89cc612012-08-01 18:03:28 +090011759 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
Sean Christophersone96c81e2020-02-18 13:07:27 -080011760 kvfree(slot->arch.rmap[i]);
11761 slot->arch.rmap[i] = NULL;
Ben Gardonc9b929b2021-05-18 10:34:08 -070011762 }
11763}
Sean Christophersone96c81e2020-02-18 13:07:27 -080011764
Ben Gardonc9b929b2021-05-18 10:34:08 -070011765void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
11766{
11767 int i;
Takuya Yoshikawad89cc612012-08-01 18:03:28 +090011768
Ben Gardonc9b929b2021-05-18 10:34:08 -070011769 memslot_rmap_free(slot);
11770
11771 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
Sean Christophersone96c81e2020-02-18 13:07:27 -080011772 kvfree(slot->arch.lpage_info[i - 1]);
11773 slot->arch.lpage_info[i - 1] = NULL;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011774 }
Xiao Guangrong21ebbed2016-02-24 17:51:09 +080011775
Sean Christophersone96c81e2020-02-18 13:07:27 -080011776 kvm_page_track_free_memslot(slot);
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011777}
11778
David Stevens1e76a3c2021-10-15 12:30:21 -040011779int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
Ben Gardon56dd1012021-05-18 10:34:09 -070011780{
11781 const int sz = sizeof(*slot->arch.rmap[0]);
11782 int i;
11783
11784 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
11785 int level = i + 1;
Peter Xu4139b192021-07-30 18:04:51 -040011786 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
Ben Gardon56dd1012021-05-18 10:34:09 -070011787
Paolo Bonzinifa138432021-10-15 13:05:00 -040011788 if (slot->arch.rmap[i])
11789 continue;
Ben Gardond501f742021-05-18 10:34:14 -070011790
Ben Gardon56dd1012021-05-18 10:34:09 -070011791 slot->arch.rmap[i] = kvcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
11792 if (!slot->arch.rmap[i]) {
11793 memslot_rmap_free(slot);
11794 return -ENOMEM;
11795 }
11796 }
11797
11798 return 0;
11799}
11800
Ben Gardona2557402021-05-18 10:34:12 -070011801static int kvm_alloc_memslot_metadata(struct kvm *kvm,
Sean Christopherson9d7d18e2021-12-06 20:54:16 +010011802 struct kvm_memory_slot *slot)
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011803{
Sean Christopherson9d7d18e2021-12-06 20:54:16 +010011804 unsigned long npages = slot->npages;
Ben Gardon56dd1012021-05-18 10:34:09 -070011805 int i, r;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011806
Sean Christophersonedd4fa32020-02-18 13:07:15 -080011807 /*
11808 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
11809 * old arrays will be freed by __kvm_set_memory_region() if installing
11810 * the new memslot is successful.
11811 */
11812 memset(&slot->arch, 0, sizeof(slot->arch));
11813
Ben Gardone2209712021-05-18 10:34:13 -070011814 if (kvm_memslots_have_rmaps(kvm)) {
Ben Gardona2557402021-05-18 10:34:12 -070011815 r = memslot_rmap_alloc(slot, npages);
11816 if (r)
11817 return r;
11818 }
Ben Gardon56dd1012021-05-18 10:34:09 -070011819
11820 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011821 struct kvm_lpage_info *linfo;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011822 unsigned long ugfn;
11823 int lpages;
Takuya Yoshikawad89cc612012-08-01 18:03:28 +090011824 int level = i + 1;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011825
Peter Xu4139b192021-07-30 18:04:51 -040011826 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011827
Ben Gardon254272c2019-02-11 11:02:50 -080011828 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011829 if (!linfo)
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011830 goto out_free;
11831
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011832 slot->arch.lpage_info[i - 1] = linfo;
11833
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011834 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011835 linfo[0].disallow_lpage = 1;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011836 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011837 linfo[lpages - 1].disallow_lpage = 1;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011838 ugfn = slot->userspace_addr >> PAGE_SHIFT;
11839 /*
11840 * If the gfn and userspace address are not aligned wrt each
Sean Christopherson600087b2020-03-02 15:57:05 -080011841 * other, disable large page support for this slot.
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011842 */
Sean Christopherson600087b2020-03-02 15:57:05 -080011843 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011844 unsigned long j;
11845
11846 for (j = 0; j < lpages; ++j)
Xiao Guangrong92f94f12016-02-24 17:51:06 +080011847 linfo[j].disallow_lpage = 1;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011848 }
11849 }
11850
David Stevensdeae4a12021-09-22 13:58:59 +090011851 if (kvm_page_track_create_memslot(kvm, slot, npages))
Xiao Guangrong21ebbed2016-02-24 17:51:09 +080011852 goto out_free;
11853
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011854 return 0;
11855
11856out_free:
Ben Gardonc9b929b2021-05-18 10:34:08 -070011857 memslot_rmap_free(slot);
Takuya Yoshikawad89cc612012-08-01 18:03:28 +090011858
Ben Gardonc9b929b2021-05-18 10:34:08 -070011859 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
Thomas Huth548ef282015-02-24 21:29:25 +010011860 kvfree(slot->arch.lpage_info[i - 1]);
Takuya Yoshikawad89cc612012-08-01 18:03:28 +090011861 slot->arch.lpage_info[i - 1] = NULL;
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +090011862 }
11863 return -ENOMEM;
11864}
11865
Sean Christopherson15248252019-02-05 12:54:17 -080011866void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +090011867{
Boris Ostrovsky91724812019-12-05 01:30:51 +000011868 struct kvm_vcpu *vcpu;
Marc Zyngier46808a42021-11-16 16:04:02 +000011869 unsigned long i;
Boris Ostrovsky91724812019-12-05 01:30:51 +000011870
Takuya Yoshikawae6dff7d2013-07-04 13:41:26 +090011871 /*
11872 * memslots->generation has been incremented.
11873 * mmio generation may have reached its maximum value.
11874 */
Sean Christopherson15248252019-02-05 12:54:17 -080011875 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
Boris Ostrovsky91724812019-12-05 01:30:51 +000011876
11877 /* Force re-initialization of steal_time cache */
11878 kvm_for_each_vcpu(i, vcpu, kvm)
11879 kvm_vcpu_kick(vcpu);
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +090011880}
11881
Marcelo Tosattif7784b82009-12-23 14:35:18 -020011882int kvm_arch_prepare_memory_region(struct kvm *kvm,
Sean Christopherson537a17b2021-12-06 20:54:11 +010011883 const struct kvm_memory_slot *old,
11884 struct kvm_memory_slot *new,
11885 enum kvm_mr_change change)
Zhang Xiantao0de10342007-11-20 16:25:04 +080011886{
Sean Christopherson0dab98b2020-02-18 13:07:19 -080011887 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
Sean Christopherson9d7d18e2021-12-06 20:54:16 +010011888 return kvm_alloc_memslot_metadata(kvm, new);
Sean Christopherson537a17b2021-12-06 20:54:11 +010011889
11890 if (change == KVM_MR_FLAGS_ONLY)
11891 memcpy(&new->arch, &old->arch, sizeof(old->arch));
11892 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
11893 return -EIO;
11894
Marcelo Tosattif7784b82009-12-23 14:35:18 -020011895 return 0;
11896}
11897
Makarand Sonarea85863c2021-02-12 16:50:12 -080011898
11899static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
11900{
11901 struct kvm_arch *ka = &kvm->arch;
11902
11903 if (!kvm_x86_ops.cpu_dirty_log_size)
11904 return;
11905
11906 if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
11907 (!enable && --ka->cpu_dirty_logging_count == 0))
11908 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
11909
11910 WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
11911}
11912
Kai Huang88178fd2015-01-28 10:54:27 +080011913static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
Anthony Yznaga37416792020-06-02 13:07:30 -070011914 struct kvm_memory_slot *old,
Hamza Mahfooz269e9552021-07-12 22:33:38 -040011915 const struct kvm_memory_slot *new,
Anthony Yznaga37416792020-06-02 13:07:30 -070011916 enum kvm_mr_change change)
Kai Huang88178fd2015-01-28 10:54:27 +080011917{
Sean Christopherson77aedf22021-12-06 20:54:20 +010011918 u32 old_flags = old ? old->flags : 0;
11919 u32 new_flags = new ? new->flags : 0;
11920 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
Makarand Sonarea85863c2021-02-12 16:50:12 -080011921
Anthony Yznaga37416792020-06-02 13:07:30 -070011922 /*
Makarand Sonarea85863c2021-02-12 16:50:12 -080011923 * Update CPU dirty logging if dirty logging is being toggled. This
11924 * applies to all operations.
11925 */
Sean Christopherson77aedf22021-12-06 20:54:20 +010011926 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
Makarand Sonarea85863c2021-02-12 16:50:12 -080011927 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
11928
11929 /*
11930 * Nothing more to do for RO slots (which can't be dirtied and can't be
Sean Christophersonb6e16ae2021-02-12 16:50:13 -080011931 * made writable) or CREATE/MOVE/DELETE of a slot.
11932 *
11933 * For a memslot with dirty logging disabled:
11934 * CREATE: No dirty mappings will already exist.
11935 * MOVE/DELETE: The old mappings will already have been cleaned up by
11936 * kvm_arch_flush_shadow_memslot()
11937 *
11938 * For a memslot with dirty logging enabled:
11939 * CREATE: No shadow pages exist, thus nothing to write-protect
11940 * and no dirty bits to clear.
11941 * MOVE/DELETE: The old mappings will already have been cleaned up by
11942 * kvm_arch_flush_shadow_memslot().
Anthony Yznaga37416792020-06-02 13:07:30 -070011943 */
Sean Christopherson77aedf22021-12-06 20:54:20 +010011944 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
Kai Huang88178fd2015-01-28 10:54:27 +080011945 return;
Kai Huang88178fd2015-01-28 10:54:27 +080011946
11947 /*
Sean Christopherson52f460792021-02-12 16:50:11 -080011948 * READONLY and non-flags changes were filtered out above, and the only
11949 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
11950 * logging isn't being toggled on or off.
Anthony Yznaga37416792020-06-02 13:07:30 -070011951 */
Sean Christopherson77aedf22021-12-06 20:54:20 +010011952 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
Sean Christopherson52f460792021-02-12 16:50:11 -080011953 return;
11954
Sean Christophersonb6e16ae2021-02-12 16:50:13 -080011955 if (!log_dirty_pages) {
11956 /*
11957 * Dirty logging tracks sptes in 4k granularity, meaning that
11958 * large sptes have to be split. If live migration succeeds,
11959 * the guest in the source machine will be destroyed and large
11960 * sptes will be created in the destination. However, if the
11961 * guest continues to run in the source machine (for example if
11962 * live migration fails), small sptes will remain around and
11963 * cause bad performance.
11964 *
11965 * Scan sptes if dirty logging has been stopped, dropping those
11966 * which can be collapsed into a single large-page spte. Later
11967 * page faults will create the large-page sptes.
11968 */
Anthony Yznaga37416792020-06-02 13:07:30 -070011969 kvm_mmu_zap_collapsible_sptes(kvm, new);
Sean Christophersonb6e16ae2021-02-12 16:50:13 -080011970 } else {
Keqian Zhu89212912021-04-29 11:41:15 +080011971 /*
11972 * Initially-all-set does not require write protecting any page,
11973 * because they're all assumed to be dirty.
11974 */
11975 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
11976 return;
Anthony Yznaga37416792020-06-02 13:07:30 -070011977
Sean Christophersona018eba2021-02-12 16:50:10 -080011978 if (kvm_x86_ops.cpu_dirty_log_size) {
Keqian Zhu89212912021-04-29 11:41:15 +080011979 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
11980 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
11981 } else {
11982 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
Jay Zhou3c9bd402020-02-27 09:32:27 +080011983 }
Kai Huang88178fd2015-01-28 10:54:27 +080011984 }
11985}
11986
Marcelo Tosattif7784b82009-12-23 14:35:18 -020011987void kvm_arch_commit_memory_region(struct kvm *kvm,
Sean Christopherson9d4c1972020-02-18 13:07:24 -080011988 struct kvm_memory_slot *old,
Paolo Bonzinif36f3f22015-05-18 13:20:23 +020011989 const struct kvm_memory_slot *new,
Takuya Yoshikawa84826442013-02-27 19:45:25 +090011990 enum kvm_mr_change change)
Marcelo Tosattif7784b82009-12-23 14:35:18 -020011991{
Maciej S. Szmigieroe0c2b632021-12-06 20:54:23 +010011992 if (!kvm->arch.n_requested_mmu_pages &&
Maciej S. Szmigierof5756022021-12-06 20:54:24 +010011993 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
11994 unsigned long nr_mmu_pages;
11995
11996 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
11997 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
11998 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
11999 }
Kai Huang1c91cad42015-01-28 10:54:26 +080012000
Hamza Mahfooz269e9552021-07-12 22:33:38 -040012001 kvm_mmu_slot_apply_flags(kvm, old, new, change);
Sean Christopherson21198842020-02-18 13:07:25 -080012002
12003 /* Free the arrays associated with the old memslot. */
12004 if (change == KVM_MR_MOVE)
Sean Christophersone96c81e2020-02-18 13:07:27 -080012005 kvm_arch_free_memslot(kvm, old);
Zhang Xiantao0de10342007-11-20 16:25:04 +080012006}
Zhang Xiantao1d737c82007-12-14 09:35:10 +080012007
Marcelo Tosatti2df72e92012-08-24 15:54:57 -030012008void kvm_arch_flush_shadow_all(struct kvm *kvm)
Marcelo Tosatti34d4cb82008-07-10 20:49:31 -030012009{
Sean Christopherson7390de12019-02-05 13:01:31 -080012010 kvm_mmu_zap_all(kvm);
Marcelo Tosatti34d4cb82008-07-10 20:49:31 -030012011}
12012
Marcelo Tosatti2df72e92012-08-24 15:54:57 -030012013void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12014 struct kvm_memory_slot *slot)
12015{
Xiaoguang Chenae7cd872016-10-09 15:41:44 +080012016 kvm_page_track_flush_slot(kvm, slot);
Marcelo Tosatti2df72e92012-08-24 15:54:57 -030012017}
12018
Liran Alone6c67d82018-09-04 10:56:52 +030012019static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
12020{
12021 return (is_guest_mode(vcpu) &&
Sean Christophersonafaf0b22020-03-21 13:26:00 -070012022 kvm_x86_ops.guest_apic_has_interrupt &&
Jason Baronb36464772021-01-14 22:27:56 -050012023 static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
Liran Alone6c67d82018-09-04 10:56:52 +030012024}
12025
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012026static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
12027{
12028 if (!list_empty_careful(&vcpu->async_pf.done))
12029 return true;
12030
12031 if (kvm_apic_has_events(vcpu))
12032 return true;
12033
12034 if (vcpu->arch.pv.pv_unhalted)
12035 return true;
12036
Wanpeng Lia5f01f82017-09-13 04:04:01 -070012037 if (vcpu->arch.exception.pending)
12038 return true;
12039
ZhuangYanying47a66ee2017-05-26 13:16:48 +080012040 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12041 (vcpu->arch.nmi_pending &&
Jason Baronb36464772021-01-14 22:27:56 -050012042 static_call(kvm_x86_nmi_allowed)(vcpu, false)))
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012043 return true;
12044
ZhuangYanying47a66ee2017-05-26 13:16:48 +080012045 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
Paolo Bonzinia9fa7cb2020-04-23 11:02:36 -040012046 (vcpu->arch.smi_pending &&
Jason Baronb36464772021-01-14 22:27:56 -050012047 static_call(kvm_x86_smi_allowed)(vcpu, false)))
Paolo Bonzini73917732015-10-13 10:19:35 +020012048 return true;
12049
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012050 if (kvm_arch_interrupt_allowed(vcpu) &&
Liran Alone6c67d82018-09-04 10:56:52 +030012051 (kvm_cpu_has_interrupt(vcpu) ||
12052 kvm_guest_apic_has_interrupt(vcpu)))
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012053 return true;
12054
Andrey Smetanin1f4b34f2015-11-30 19:22:21 +030012055 if (kvm_hv_has_stimer_pending(vcpu))
12056 return true;
12057
Sean Christophersond2060bd2020-04-22 19:25:39 -070012058 if (is_guest_mode(vcpu) &&
12059 kvm_x86_ops.nested_ops->hv_timer_pending &&
12060 kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
12061 return true;
12062
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012063 return false;
12064}
12065
Zhang Xiantao1d737c82007-12-14 09:35:10 +080012066int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
12067{
Paolo Bonzini5d9bc642015-10-13 10:18:53 +020012068 return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
Zhang Xiantao1d737c82007-12-14 09:35:10 +080012069}
Zhang Xiantao57361992007-12-17 14:21:40 +080012070
Haiwei Li10dbdf92021-04-21 11:25:13 +080012071bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
12072{
12073 if (vcpu->arch.apicv_active && static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
12074 return true;
12075
12076 return false;
12077}
12078
Wanpeng Li17e433b2019-08-05 10:03:19 +080012079bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
12080{
12081 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
12082 return true;
12083
12084 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
12085 kvm_test_request(KVM_REQ_SMI, vcpu) ||
12086 kvm_test_request(KVM_REQ_EVENT, vcpu))
12087 return true;
12088
Haiwei Li10dbdf92021-04-21 11:25:13 +080012089 return kvm_arch_dy_has_pending_interrupt(vcpu);
Wanpeng Li17e433b2019-08-05 10:03:19 +080012090}
12091
Longpeng(Mike)199b5762017-08-08 12:05:32 +080012092bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
12093{
Wanpeng Lib86bb112021-04-22 16:34:19 +080012094 if (vcpu->arch.guest_state_protected)
12095 return true;
12096
Longpeng(Mike)de63ad42017-08-08 12:05:33 +080012097 return vcpu->arch.preempted_in_kernel;
Longpeng(Mike)199b5762017-08-08 12:05:32 +080012098}
12099
Sean Christophersone1bfc242021-11-11 02:07:33 +000012100unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
12101{
12102 return kvm_rip_read(vcpu);
12103}
12104
Christoffer Dallb6d33832012-03-08 16:44:24 -050012105int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
Zhang Xiantao57361992007-12-17 14:21:40 +080012106{
Christoffer Dallb6d33832012-03-08 16:44:24 -050012107 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
Zhang Xiantao57361992007-12-17 14:21:40 +080012108}
Gleb Natapov78646122009-03-23 12:12:11 +020012109
12110int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
12111{
Jason Baronb36464772021-01-14 22:27:56 -050012112 return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
Gleb Natapov78646122009-03-23 12:12:11 +020012113}
Marcelo Tosatti229456f2009-06-17 09:22:14 -030012114
Nadav Amit82b32772014-11-02 11:54:45 +020012115unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
12116{
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012117 /* Can't read the RIP when guest state is protected, just return 0 */
12118 if (vcpu->arch.guest_state_protected)
12119 return 0;
12120
Nadav Amit82b32772014-11-02 11:54:45 +020012121 if (is_64_bit_mode(vcpu))
12122 return kvm_rip_read(vcpu);
12123 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
12124 kvm_rip_read(vcpu));
12125}
12126EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
12127
Jan Kiszkaf92653e2010-02-23 17:47:55 +010012128bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
12129{
Nadav Amit82b32772014-11-02 11:54:45 +020012130 return kvm_get_linear_rip(vcpu) == linear_rip;
Jan Kiszkaf92653e2010-02-23 17:47:55 +010012131}
12132EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
12133
Jan Kiszka94fe45d2009-10-18 13:24:44 +020012134unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
12135{
12136 unsigned long rflags;
12137
Jason Baronb36464772021-01-14 22:27:56 -050012138 rflags = static_call(kvm_x86_get_rflags)(vcpu);
Jan Kiszka94fe45d2009-10-18 13:24:44 +020012139 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
Jan Kiszkac310bac2010-02-23 17:47:58 +010012140 rflags &= ~X86_EFLAGS_TF;
Jan Kiszka94fe45d2009-10-18 13:24:44 +020012141 return rflags;
12142}
12143EXPORT_SYMBOL_GPL(kvm_get_rflags);
12144
Paolo Bonzini6addfc42014-03-27 11:29:28 +010012145static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
Jan Kiszka94fe45d2009-10-18 13:24:44 +020012146{
12147 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
Jan Kiszkaf92653e2010-02-23 17:47:55 +010012148 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
Jan Kiszkac310bac2010-02-23 17:47:58 +010012149 rflags |= X86_EFLAGS_TF;
Jason Baronb36464772021-01-14 22:27:56 -050012150 static_call(kvm_x86_set_rflags)(vcpu, rflags);
Paolo Bonzini6addfc42014-03-27 11:29:28 +010012151}
12152
12153void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
12154{
12155 __kvm_set_rflags(vcpu, rflags);
Avi Kivity3842d132010-07-27 12:30:24 +030012156 kvm_make_request(KVM_REQ_EVENT, vcpu);
Jan Kiszka94fe45d2009-10-18 13:24:44 +020012157}
12158EXPORT_SYMBOL_GPL(kvm_set_rflags);
12159
Gleb Natapov56028d02010-10-17 18:13:42 +020012160void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
12161{
12162 int r;
12163
Vitaly Kuznetsov44dd3ff2018-10-08 21:28:05 +020012164 if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
chai wenf2e10662013-10-14 22:22:33 +080012165 work->wakeup_all)
Gleb Natapov56028d02010-10-17 18:13:42 +020012166 return;
12167
12168 r = kvm_mmu_reload(vcpu);
12169 if (unlikely(r))
12170 return;
12171
Vitaly Kuznetsov44dd3ff2018-10-08 21:28:05 +020012172 if (!vcpu->arch.mmu->direct_map &&
Sean Christophersond8dd54e2020-03-02 18:02:39 -080012173 work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
Xiao Guangrongfb67e142010-12-07 10:35:25 +080012174 return;
12175
Sean Christopherson7a026742020-02-06 14:14:34 -080012176 kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
Gleb Natapov56028d02010-10-17 18:13:42 +020012177}
12178
Gleb Natapovaf585b92010-10-14 11:22:46 +020012179static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
12180{
Peter Xudd03bca2020-04-16 11:58:59 -040012181 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
12182
Gleb Natapovaf585b92010-10-14 11:22:46 +020012183 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
12184}
12185
12186static inline u32 kvm_async_pf_next_probe(u32 key)
12187{
Peter Xudd03bca2020-04-16 11:58:59 -040012188 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
Gleb Natapovaf585b92010-10-14 11:22:46 +020012189}
12190
12191static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12192{
12193 u32 key = kvm_async_pf_hash_fn(gfn);
12194
12195 while (vcpu->arch.apf.gfns[key] != ~0)
12196 key = kvm_async_pf_next_probe(key);
12197
12198 vcpu->arch.apf.gfns[key] = gfn;
12199}
12200
12201static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
12202{
12203 int i;
12204 u32 key = kvm_async_pf_hash_fn(gfn);
12205
Peter Xudd03bca2020-04-16 11:58:59 -040012206 for (i = 0; i < ASYNC_PF_PER_VCPU &&
Xiao Guangrongc7d28c22010-11-01 17:00:30 +080012207 (vcpu->arch.apf.gfns[key] != gfn &&
12208 vcpu->arch.apf.gfns[key] != ~0); i++)
Gleb Natapovaf585b92010-10-14 11:22:46 +020012209 key = kvm_async_pf_next_probe(key);
12210
12211 return key;
12212}
12213
12214bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12215{
12216 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
12217}
12218
12219static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
12220{
12221 u32 i, j, k;
12222
12223 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
Peter Xu0fd46042020-04-16 11:59:10 -040012224
12225 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
12226 return;
12227
Gleb Natapovaf585b92010-10-14 11:22:46 +020012228 while (true) {
12229 vcpu->arch.apf.gfns[i] = ~0;
12230 do {
12231 j = kvm_async_pf_next_probe(j);
12232 if (vcpu->arch.apf.gfns[j] == ~0)
12233 return;
12234 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
12235 /*
12236 * k lies cyclically in ]i,j]
12237 * | i.k.j |
12238 * |....j i.k.| or |.k..j i...|
12239 */
12240 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
12241 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
12242 i = j;
12243 }
12244}
12245
Vitaly Kuznetsov68fd66f2020-05-25 16:41:17 +020012246static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
Gleb Natapov7c907052010-10-14 11:22:53 +020012247{
Vitaly Kuznetsov68fd66f2020-05-25 16:41:17 +020012248 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
12249
12250 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
12251 sizeof(reason));
12252}
12253
12254static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
12255{
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012256 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
Paolo Bonzini4e335d92017-05-02 16:20:18 +020012257
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012258 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12259 &token, offset, sizeof(token));
12260}
12261
12262static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
12263{
12264 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
12265 u32 val;
12266
12267 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
12268 &val, offset, sizeof(val)))
12269 return false;
12270
12271 return !val;
Gleb Natapov7c907052010-10-14 11:22:53 +020012272}
12273
Paolo Bonzini1dfdb452019-06-05 16:46:44 +020012274static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
12275{
12276 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
12277 return false;
12278
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012279 if (!kvm_pv_async_pf_enabled(vcpu) ||
Jason Baronb36464772021-01-14 22:27:56 -050012280 (vcpu->arch.apf.send_user_only && static_call(kvm_x86_get_cpl)(vcpu) == 0))
Paolo Bonzini1dfdb452019-06-05 16:46:44 +020012281 return false;
12282
12283 return true;
12284}
12285
12286bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
12287{
12288 if (unlikely(!lapic_in_kernel(vcpu) ||
12289 kvm_event_needs_reinjection(vcpu) ||
12290 vcpu->arch.exception.pending))
12291 return false;
12292
12293 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
12294 return false;
12295
12296 /*
12297 * If interrupts are off we cannot even use an artificial
12298 * halt state.
12299 */
Paolo Bonzinic300ab92020-04-23 14:08:58 -040012300 return kvm_arch_interrupt_allowed(vcpu);
Paolo Bonzini1dfdb452019-06-05 16:46:44 +020012301}
12302
Vitaly Kuznetsov2a18b7e2020-06-10 19:55:32 +020012303bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
Gleb Natapovaf585b92010-10-14 11:22:46 +020012304 struct kvm_async_pf *work)
12305{
Avi Kivity6389ee92010-11-29 16:12:30 +020012306 struct x86_exception fault;
12307
Sean Christopherson736c2912019-12-06 15:57:14 -080012308 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
Gleb Natapovaf585b92010-10-14 11:22:46 +020012309 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
Gleb Natapov7c907052010-10-14 11:22:53 +020012310
Paolo Bonzini1dfdb452019-06-05 16:46:44 +020012311 if (kvm_can_deliver_async_pf(vcpu) &&
Vitaly Kuznetsov68fd66f2020-05-25 16:41:17 +020012312 !apf_put_user_notpresent(vcpu)) {
Avi Kivity6389ee92010-11-29 16:12:30 +020012313 fault.vector = PF_VECTOR;
12314 fault.error_code_valid = true;
12315 fault.error_code = 0;
12316 fault.nested_page_fault = false;
12317 fault.address = work->arch.token;
Wanpeng Liadfe20f2017-07-13 18:30:41 -070012318 fault.async_page_fault = true;
Avi Kivity6389ee92010-11-29 16:12:30 +020012319 kvm_inject_page_fault(vcpu, &fault);
Vitaly Kuznetsov2a18b7e2020-06-10 19:55:32 +020012320 return true;
Paolo Bonzini1dfdb452019-06-05 16:46:44 +020012321 } else {
12322 /*
12323 * It is not possible to deliver a paravirtualized asynchronous
12324 * page fault, but putting the guest in an artificial halt state
12325 * can be beneficial nevertheless: if an interrupt arrives, we
12326 * can deliver it timely and perhaps the guest will schedule
12327 * another process. When the instruction that triggered a page
12328 * fault is retried, hopefully the page will be ready in the host.
12329 */
12330 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
Vitaly Kuznetsov2a18b7e2020-06-10 19:55:32 +020012331 return false;
Gleb Natapov7c907052010-10-14 11:22:53 +020012332 }
Gleb Natapovaf585b92010-10-14 11:22:46 +020012333}
12334
12335void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
12336 struct kvm_async_pf *work)
12337{
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012338 struct kvm_lapic_irq irq = {
12339 .delivery_mode = APIC_DM_FIXED,
12340 .vector = vcpu->arch.apf.vec
12341 };
Avi Kivity6389ee92010-11-29 16:12:30 +020012342
chai wenf2e10662013-10-14 22:22:33 +080012343 if (work->wakeup_all)
Gleb Natapov7c907052010-10-14 11:22:53 +020012344 work->arch.token = ~0; /* broadcast wakeup */
12345 else
12346 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
Sean Christopherson736c2912019-12-06 15:57:14 -080012347 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
Gleb Natapov7c907052010-10-14 11:22:53 +020012348
Vitaly Kuznetsov2a18b7e2020-06-10 19:55:32 +020012349 if ((work->wakeup_all || work->notpresent_injected) &&
12350 kvm_pv_async_pf_enabled(vcpu) &&
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +020012351 !apf_put_user_ready(vcpu, work->arch.token)) {
12352 vcpu->arch.apf.pageready_pending = true;
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012353 kvm_apic_set_irq(vcpu, &irq, NULL);
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +020012354 }
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012355
Xiao Guangronge6d53e32010-11-01 17:01:28 +080012356 vcpu->arch.apf.halted = false;
Gleb Natapova4fa1632012-05-03 11:36:39 +030012357 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
Gleb Natapov7c907052010-10-14 11:22:53 +020012358}
12359
Vitaly Kuznetsov557a9612020-05-25 16:41:21 +020012360void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
12361{
12362 kvm_make_request(KVM_REQ_APF_READY, vcpu);
12363 if (!vcpu->arch.apf.pageready_pending)
12364 kvm_vcpu_kick(vcpu);
12365}
12366
Vitaly Kuznetsov7c0ade62020-05-25 16:41:18 +020012367bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
Gleb Natapov7c907052010-10-14 11:22:53 +020012368{
Vitaly Kuznetsov2635b5c2020-05-25 16:41:20 +020012369 if (!kvm_pv_async_pf_enabled(vcpu))
Gleb Natapov7c907052010-10-14 11:22:53 +020012370 return true;
12371 else
Vitaly Kuznetsov2f15d022021-04-22 11:29:48 +020012372 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
Gleb Natapovaf585b92010-10-14 11:22:46 +020012373}
12374
Paolo Bonzini5544eb92015-07-07 15:41:58 +020012375void kvm_arch_start_assignment(struct kvm *kvm)
12376{
Marcelo Tosatti57ab8792021-05-25 10:41:16 -030012377 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
12378 static_call_cond(kvm_x86_start_assignment)(kvm);
Paolo Bonzini5544eb92015-07-07 15:41:58 +020012379}
12380EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
12381
12382void kvm_arch_end_assignment(struct kvm *kvm)
12383{
12384 atomic_dec(&kvm->arch.assigned_device_count);
12385}
12386EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
12387
12388bool kvm_arch_has_assigned_device(struct kvm *kvm)
12389{
12390 return atomic_read(&kvm->arch.assigned_device_count);
12391}
12392EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
12393
Alex Williamsone0f0bbc2013-10-30 11:02:30 -060012394void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
12395{
12396 atomic_inc(&kvm->arch.noncoherent_dma_count);
12397}
12398EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
12399
12400void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
12401{
12402 atomic_dec(&kvm->arch.noncoherent_dma_count);
12403}
12404EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
12405
12406bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
12407{
12408 return atomic_read(&kvm->arch.noncoherent_dma_count);
12409}
12410EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
12411
Alex Williamson14717e22016-05-05 11:58:35 -060012412bool kvm_arch_has_irq_bypass(void)
12413{
Sean Christopherson92735b12019-08-02 15:06:17 -070012414 return true;
Alex Williamson14717e22016-05-05 11:58:35 -060012415}
12416
Feng Wu87276882015-09-18 22:29:40 +080012417int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
12418 struct irq_bypass_producer *prod)
12419{
12420 struct kvm_kernel_irqfd *irqfd =
12421 container_of(cons, struct kvm_kernel_irqfd, consumer);
Zhu Lingshan2edd9cb2020-07-31 14:55:29 +080012422 int ret;
Feng Wu87276882015-09-18 22:29:40 +080012423
Alex Williamson14717e22016-05-05 11:58:35 -060012424 irqfd->producer = prod;
Zhu Lingshan2edd9cb2020-07-31 14:55:29 +080012425 kvm_arch_start_assignment(irqfd->kvm);
Jason Baronb36464772021-01-14 22:27:56 -050012426 ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm,
Zhu Lingshan2edd9cb2020-07-31 14:55:29 +080012427 prod->irq, irqfd->gsi, 1);
Feng Wu87276882015-09-18 22:29:40 +080012428
Zhu Lingshan2edd9cb2020-07-31 14:55:29 +080012429 if (ret)
12430 kvm_arch_end_assignment(irqfd->kvm);
12431
12432 return ret;
Feng Wu87276882015-09-18 22:29:40 +080012433}
12434
12435void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
12436 struct irq_bypass_producer *prod)
12437{
12438 int ret;
12439 struct kvm_kernel_irqfd *irqfd =
12440 container_of(cons, struct kvm_kernel_irqfd, consumer);
12441
Feng Wu87276882015-09-18 22:29:40 +080012442 WARN_ON(irqfd->producer != prod);
12443 irqfd->producer = NULL;
12444
12445 /*
12446 * When producer of consumer is unregistered, we change back to
12447 * remapped mode, so we can re-use the current implementation
Andrea Gelminibb3541f2016-05-21 14:14:44 +020012448 * when the irq is masked/disabled or the consumer side (KVM
Feng Wu87276882015-09-18 22:29:40 +080012449 * int this case doesn't want to receive the interrupts.
12450 */
Jason Baronb36464772021-01-14 22:27:56 -050012451 ret = static_call(kvm_x86_update_pi_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
Feng Wu87276882015-09-18 22:29:40 +080012452 if (ret)
12453 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
12454 " fails: %d\n", irqfd->consumer.token, ret);
Zhu Lingshan2edd9cb2020-07-31 14:55:29 +080012455
12456 kvm_arch_end_assignment(irqfd->kvm);
Feng Wu87276882015-09-18 22:29:40 +080012457}
12458
12459int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
12460 uint32_t guest_irq, bool set)
12461{
Jason Baronb36464772021-01-14 22:27:56 -050012462 return static_call(kvm_x86_update_pi_irte)(kvm, host_irq, guest_irq, set);
Feng Wu87276882015-09-18 22:29:40 +080012463}
12464
Longpeng(Mike)515a0c72021-08-27 16:00:03 +080012465bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
12466 struct kvm_kernel_irq_routing_entry *new)
12467{
12468 if (new->type != KVM_IRQ_ROUTING_MSI)
12469 return true;
12470
12471 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
12472}
12473
Feng Wu520040142016-01-25 16:53:33 +080012474bool kvm_vector_hashing_enabled(void)
12475{
12476 return vector_hashing;
12477}
Feng Wu520040142016-01-25 16:53:33 +080012478
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -030012479bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
12480{
12481 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
12482}
12483EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
12484
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012485
12486int kvm_spec_ctrl_test_value(u64 value)
Paolo Bonzini6441fa62020-01-20 16:33:06 +010012487{
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012488 /*
12489 * test that setting IA32_SPEC_CTRL to given value
12490 * is allowed by the host processor
12491 */
Paolo Bonzini6441fa62020-01-20 16:33:06 +010012492
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012493 u64 saved_value;
12494 unsigned long flags;
12495 int ret = 0;
Paolo Bonzini6441fa62020-01-20 16:33:06 +010012496
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012497 local_irq_save(flags);
Paolo Bonzini6441fa62020-01-20 16:33:06 +010012498
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012499 if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
12500 ret = 1;
12501 else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
12502 ret = 1;
12503 else
12504 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
12505
12506 local_irq_restore(flags);
12507
12508 return ret;
Paolo Bonzini6441fa62020-01-20 16:33:06 +010012509}
Maxim Levitsky841c2be2020-07-08 14:57:31 +030012510EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
Marcelo Tosatti2d5ba192019-06-03 19:52:44 -030012511
Mohammed Gamal89786142020-07-10 17:48:03 +020012512void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
12513{
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +080012514 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
Mohammed Gamal89786142020-07-10 17:48:03 +020012515 struct x86_exception fault;
Paolo Bonzini19cf4b72020-08-17 13:53:04 -040012516 u32 access = error_code &
12517 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
Mohammed Gamal89786142020-07-10 17:48:03 +020012518
12519 if (!(error_code & PFERR_PRESENT_MASK) ||
Lai Jiangshan1f5a21e2021-11-24 20:20:44 +080012520 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != UNMAPPED_GVA) {
Mohammed Gamal89786142020-07-10 17:48:03 +020012521 /*
12522 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
12523 * tables probably do not match the TLB. Just proceed
12524 * with the error code that the processor gave.
12525 */
12526 fault.vector = PF_VECTOR;
12527 fault.error_code_valid = true;
12528 fault.error_code = error_code;
12529 fault.nested_page_fault = false;
12530 fault.address = gva;
12531 }
12532 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
12533}
12534EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
Carsten Otte043405e2007-10-10 17:16:19 +020012535
Babu Moger3f3393b2020-09-11 14:29:05 -050012536/*
12537 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
12538 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
12539 * indicates whether exit to userspace is needed.
12540 */
12541int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
12542 struct x86_exception *e)
12543{
12544 if (r == X86EMUL_PROPAGATE_FAULT) {
12545 kvm_inject_emulated_page_fault(vcpu, e);
12546 return 1;
12547 }
12548
12549 /*
12550 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
12551 * while handling a VMX instruction KVM could've handled the request
12552 * correctly by exiting to userspace and performing I/O but there
12553 * doesn't seem to be a real use-case behind such requests, just return
12554 * KVM_EXIT_INTERNAL_ERROR for now.
12555 */
David Edmondsone615e352021-09-20 11:37:36 +010012556 kvm_prepare_emulation_failure_exit(vcpu);
Babu Moger3f3393b2020-09-11 14:29:05 -050012557
12558 return 0;
12559}
12560EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
12561
Babu Moger97150922020-09-11 14:29:12 -050012562int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
12563{
12564 bool pcid_enabled;
12565 struct x86_exception e;
Babu Moger97150922020-09-11 14:29:12 -050012566 struct {
12567 u64 pcid;
12568 u64 gla;
12569 } operand;
12570 int r;
12571
12572 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
12573 if (r != X86EMUL_CONTINUE)
12574 return kvm_handle_memory_failure(vcpu, r, &e);
12575
12576 if (operand.pcid >> 12 != 0) {
12577 kvm_inject_gp(vcpu, 0);
12578 return 1;
12579 }
12580
12581 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
12582
12583 switch (type) {
12584 case INVPCID_TYPE_INDIV_ADDR:
12585 if ((!pcid_enabled && (operand.pcid != 0)) ||
12586 is_noncanonical_address(operand.gla, vcpu)) {
12587 kvm_inject_gp(vcpu, 0);
12588 return 1;
12589 }
12590 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
12591 return kvm_skip_emulated_instruction(vcpu);
12592
12593 case INVPCID_TYPE_SINGLE_CTXT:
12594 if (!pcid_enabled && (operand.pcid != 0)) {
12595 kvm_inject_gp(vcpu, 0);
12596 return 1;
12597 }
12598
Sean Christopherson21823fb2021-06-09 16:42:24 -070012599 kvm_invalidate_pcid(vcpu, operand.pcid);
Babu Moger97150922020-09-11 14:29:12 -050012600 return kvm_skip_emulated_instruction(vcpu);
12601
12602 case INVPCID_TYPE_ALL_NON_GLOBAL:
12603 /*
12604 * Currently, KVM doesn't mark global entries in the shadow
12605 * page tables, so a non-global flush just degenerates to a
12606 * global flush. If needed, we could optimize this later by
12607 * keeping track of global entries in shadow page tables.
12608 */
12609
12610 fallthrough;
12611 case INVPCID_TYPE_ALL_INCL_GLOBAL:
Sean Christopherson28f28d42021-06-09 16:42:30 -070012612 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
Babu Moger97150922020-09-11 14:29:12 -050012613 return kvm_skip_emulated_instruction(vcpu);
12614
12615 default:
Vipin Sharma796c83c2021-11-09 17:44:26 +000012616 kvm_inject_gp(vcpu, 0);
12617 return 1;
Babu Moger97150922020-09-11 14:29:12 -050012618 }
12619}
12620EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
12621
Tom Lendacky8f423a82020-12-10 11:09:53 -060012622static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
12623{
12624 struct kvm_run *run = vcpu->run;
12625 struct kvm_mmio_fragment *frag;
12626 unsigned int len;
12627
12628 BUG_ON(!vcpu->mmio_needed);
12629
12630 /* Complete previous fragment */
12631 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
12632 len = min(8u, frag->len);
12633 if (!vcpu->mmio_is_write)
12634 memcpy(frag->data, run->mmio.data, len);
12635
12636 if (frag->len <= 8) {
12637 /* Switch to the next fragment. */
12638 frag++;
12639 vcpu->mmio_cur_fragment++;
12640 } else {
12641 /* Go forward to the next mmio piece. */
12642 frag->data += len;
12643 frag->gpa += len;
12644 frag->len -= len;
12645 }
12646
12647 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
12648 vcpu->mmio_needed = 0;
12649
12650 // VMG change, at this point, we're always done
12651 // RIP has already been advanced
12652 return 1;
12653 }
12654
12655 // More MMIO is needed
12656 run->mmio.phys_addr = frag->gpa;
12657 run->mmio.len = min(8u, frag->len);
12658 run->mmio.is_write = vcpu->mmio_is_write;
12659 if (run->mmio.is_write)
12660 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
12661 run->exit_reason = KVM_EXIT_MMIO;
12662
12663 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
12664
12665 return 0;
12666}
12667
12668int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
12669 void *data)
12670{
12671 int handled;
12672 struct kvm_mmio_fragment *frag;
12673
12674 if (!data)
12675 return -EINVAL;
12676
12677 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
12678 if (handled == bytes)
12679 return 1;
12680
12681 bytes -= handled;
12682 gpa += handled;
12683 data += handled;
12684
12685 /*TODO: Check if need to increment number of frags */
12686 frag = vcpu->mmio_fragments;
12687 vcpu->mmio_nr_fragments = 1;
12688 frag->len = bytes;
12689 frag->gpa = gpa;
12690 frag->data = data;
12691
12692 vcpu->mmio_needed = 1;
12693 vcpu->mmio_cur_fragment = 0;
12694
12695 vcpu->run->mmio.phys_addr = gpa;
12696 vcpu->run->mmio.len = min(8u, frag->len);
12697 vcpu->run->mmio.is_write = 1;
12698 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
12699 vcpu->run->exit_reason = KVM_EXIT_MMIO;
12700
12701 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
12702
12703 return 0;
12704}
12705EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
12706
12707int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
12708 void *data)
12709{
12710 int handled;
12711 struct kvm_mmio_fragment *frag;
12712
12713 if (!data)
12714 return -EINVAL;
12715
12716 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
12717 if (handled == bytes)
12718 return 1;
12719
12720 bytes -= handled;
12721 gpa += handled;
12722 data += handled;
12723
12724 /*TODO: Check if need to increment number of frags */
12725 frag = vcpu->mmio_fragments;
12726 vcpu->mmio_nr_fragments = 1;
12727 frag->len = bytes;
12728 frag->gpa = gpa;
12729 frag->data = data;
12730
12731 vcpu->mmio_needed = 1;
12732 vcpu->mmio_cur_fragment = 0;
12733
12734 vcpu->run->mmio.phys_addr = gpa;
12735 vcpu->run->mmio.len = min(8u, frag->len);
12736 vcpu->run->mmio.is_write = 0;
12737 vcpu->run->exit_reason = KVM_EXIT_MMIO;
12738
12739 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
12740
12741 return 0;
12742}
12743EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
12744
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012745static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012746 unsigned int port);
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012747
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012748static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
12749{
12750 int size = vcpu->arch.pio.size;
12751 int port = vcpu->arch.pio.port;
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012752
12753 vcpu->arch.pio.count = 0;
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012754 if (vcpu->arch.sev_pio_count)
12755 return kvm_sev_es_outs(vcpu, size, port);
12756 return 1;
12757}
12758
12759static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
12760 unsigned int port)
12761{
12762 for (;;) {
12763 unsigned int count =
12764 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
12765 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
12766
12767 /* memcpy done already by emulator_pio_out. */
12768 vcpu->arch.sev_pio_count -= count;
12769 vcpu->arch.sev_pio_data += count * vcpu->arch.pio.size;
12770 if (!ret)
12771 break;
12772
12773 /* Emulation done by the kernel. */
12774 if (!vcpu->arch.sev_pio_count)
12775 return 1;
12776 }
12777
12778 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012779 return 0;
12780}
12781
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012782static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
12783 unsigned int port);
12784
12785static void advance_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
12786{
12787 unsigned count = vcpu->arch.pio.count;
12788 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
12789 vcpu->arch.sev_pio_count -= count;
12790 vcpu->arch.sev_pio_data += count * vcpu->arch.pio.size;
12791}
12792
Paolo Bonzini4fa4b382021-10-12 11:25:45 -040012793static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
12794{
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012795 int size = vcpu->arch.pio.size;
12796 int port = vcpu->arch.pio.port;
Paolo Bonzini4fa4b382021-10-12 11:25:45 -040012797
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012798 advance_sev_es_emulated_ins(vcpu);
12799 if (vcpu->arch.sev_pio_count)
12800 return kvm_sev_es_ins(vcpu, size, port);
Paolo Bonzini4fa4b382021-10-12 11:25:45 -040012801 return 1;
12802}
12803
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012804static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012805 unsigned int port)
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012806{
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012807 for (;;) {
12808 unsigned int count =
12809 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
12810 if (!__emulator_pio_in(vcpu, size, port, count))
12811 break;
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012812
Paolo Bonziniea724ea2021-10-12 10:51:55 -040012813 /* Emulation done by the kernel. */
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012814 advance_sev_es_emulated_ins(vcpu);
12815 if (!vcpu->arch.sev_pio_count)
12816 return 1;
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012817 }
12818
Paolo Bonziniea724ea2021-10-12 10:51:55 -040012819 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012820 return 0;
12821}
12822
12823int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
12824 unsigned int port, void *data, unsigned int count,
12825 int in)
12826{
Paolo Bonziniea724ea2021-10-12 10:51:55 -040012827 vcpu->arch.sev_pio_data = data;
Paolo Bonzini95e16b42021-10-12 11:33:03 -040012828 vcpu->arch.sev_pio_count = count;
12829 return in ? kvm_sev_es_ins(vcpu, size, port)
12830 : kvm_sev_es_outs(vcpu, size, port);
Tom Lendacky7ed9abf2020-12-10 11:09:54 -060012831}
12832EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
12833
Lorenzo Bresciad95df952020-12-23 14:45:07 +000012834EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
Carsten Otte043405e2007-10-10 17:16:19 +020012835EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
12836EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
12837EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
12838EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
12839EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
12840EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
12841EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
12842EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
12843EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
12844EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
Sean Christopherson5497b952019-07-11 08:58:29 -070012845EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
Carsten Otte043405e2007-10-10 17:16:19 +020012846EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
12847EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
12848EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
12849EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
Peter Xu4f75bcc2019-09-06 10:17:22 +080012850EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
Carsten Otte043405e2007-10-10 17:16:19 +020012851EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
12852EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
12853EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
12854EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
Suravee Suthikulpanitab56f8e2020-03-12 05:39:28 -050012855EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
Suravee Suthikulpanit24bbf742019-11-14 14:15:07 -060012856EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);
Maxim Levitsky8e819d72021-12-09 13:54:36 +020012857EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
Tom Lendackyd523ab6b2020-12-10 11:09:48 -060012858EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
12859EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
Tom Lendacky59e38b52020-12-10 11:09:52 -060012860EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
12861EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);