File Index
Files and directories
Sign in
FILE

x86.c

File preview with syntax highlighting.

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