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