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