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