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