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