1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * KVM paravirt_ops implementation 4 * 5 * Copyright (C) 2007, Red Hat, Inc., Ingo Molnar <mingo@redhat.com> 6 * Copyright IBM Corporation, 2007 7 * Authors: Anthony Liguori <aliguori@us.ibm.com> 8 */ 9 10 #define pr_fmt(fmt) "kvm-guest: " fmt 11 12 #include <linux/context_tracking.h> 13 #include <linux/init.h> 14 #include <linux/irq.h> 15 #include <linux/kernel.h> 16 #include <linux/kvm_para.h> 17 #include <linux/cpu.h> 18 #include <linux/mm.h> 19 #include <linux/highmem.h> 20 #include <linux/hardirq.h> 21 #include <linux/notifier.h> 22 #include <linux/reboot.h> 23 #include <linux/hash.h> 24 #include <linux/sched.h> 25 #include <linux/slab.h> 26 #include <linux/kprobes.h> 27 #include <linux/nmi.h> 28 #include <linux/swait.h> 29 #include <linux/syscore_ops.h> 30 #include <linux/cc_platform.h> 31 #include <linux/efi.h> 32 #include <asm/timer.h> 33 #include <asm/cpu.h> 34 #include <asm/traps.h> 35 #include <asm/desc.h> 36 #include <asm/tlbflush.h> 37 #include <asm/apic.h> 38 #include <asm/apicdef.h> 39 #include <asm/hypervisor.h> 40 #include <asm/tlb.h> 41 #include <asm/cpuidle_haltpoll.h> 42 #include <asm/ptrace.h> 43 #include <asm/reboot.h> 44 #include <asm/svm.h> 45 #include <asm/e820/api.h> 46 47 DEFINE_STATIC_KEY_FALSE(kvm_async_pf_enabled); 48 49 static int kvmapf = 1; 50 51 static int __init parse_no_kvmapf(char *arg) 52 { 53 kvmapf = 0; 54 return 0; 55 } 56 57 early_param("no-kvmapf", parse_no_kvmapf); 58 59 static int steal_acc = 1; 60 static int __init parse_no_stealacc(char *arg) 61 { 62 steal_acc = 0; 63 return 0; 64 } 65 66 early_param("no-steal-acc", parse_no_stealacc); 67 68 static DEFINE_PER_CPU_DECRYPTED(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64); 69 DEFINE_PER_CPU_DECRYPTED(struct kvm_steal_time, steal_time) __aligned(64) __visible; 70 static int has_steal_clock = 0; 71 72 static int has_guest_poll = 0; 73 /* 74 * No need for any "IO delay" on KVM 75 */ 76 static void kvm_io_delay(void) 77 { 78 } 79 80 #define KVM_TASK_SLEEP_HASHBITS 8 81 #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS) 82 83 struct kvm_task_sleep_node { 84 struct hlist_node link; 85 struct swait_queue_head wq; 86 u32 token; 87 int cpu; 88 }; 89 90 static struct kvm_task_sleep_head { 91 raw_spinlock_t lock; 92 struct hlist_head list; 93 } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE]; 94 95 static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b, 96 u32 token) 97 { 98 struct hlist_node *p; 99 100 hlist_for_each(p, &b->list) { 101 struct kvm_task_sleep_node *n = 102 hlist_entry(p, typeof(*n), link); 103 if (n->token == token) 104 return n; 105 } 106 107 return NULL; 108 } 109 110 static bool kvm_async_pf_queue_task(u32 token, struct kvm_task_sleep_node *n) 111 { 112 u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); 113 struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; 114 struct kvm_task_sleep_node *e; 115 116 raw_spin_lock(&b->lock); 117 e = _find_apf_task(b, token); 118 if (e) { 119 /* dummy entry exist -> wake up was delivered ahead of PF */ 120 hlist_del(&e->link); 121 raw_spin_unlock(&b->lock); 122 kfree(e); 123 return false; 124 } 125 126 n->token = token; 127 n->cpu = smp_processor_id(); 128 init_swait_queue_head(&n->wq); 129 hlist_add_head(&n->link, &b->list); 130 raw_spin_unlock(&b->lock); 131 return true; 132 } 133 134 /* 135 * kvm_async_pf_task_wait_schedule - Wait for pagefault to be handled 136 * @token: Token to identify the sleep node entry 137 * 138 * Invoked from the async pagefault handling code or from the VM exit page 139 * fault handler. In both cases RCU is watching. 140 */ 141 void kvm_async_pf_task_wait_schedule(u32 token) 142 { 143 struct kvm_task_sleep_node n; 144 DECLARE_SWAITQUEUE(wait); 145 146 lockdep_assert_irqs_disabled(); 147 148 if (!kvm_async_pf_queue_task(token, &n)) 149 return; 150 151 for (;;) { 152 prepare_to_swait_exclusive(&n.wq, &wait, TASK_UNINTERRUPTIBLE); 153 if (hlist_unhashed(&n.link)) 154 break; 155 156 local_irq_enable(); 157 schedule(); 158 local_irq_disable(); 159 } 160 finish_swait(&n.wq, &wait); 161 } 162 EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait_schedule); 163 164 static void apf_task_wake_one(struct kvm_task_sleep_node *n) 165 { 166 hlist_del_init(&n->link); 167 if (swq_has_sleeper(&n->wq)) 168 swake_up_one(&n->wq); 169 } 170 171 static void apf_task_wake_all(void) 172 { 173 int i; 174 175 for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) { 176 struct kvm_task_sleep_head *b = &async_pf_sleepers[i]; 177 struct kvm_task_sleep_node *n; 178 struct hlist_node *p, *next; 179 180 raw_spin_lock(&b->lock); 181 hlist_for_each_safe(p, next, &b->list) { 182 n = hlist_entry(p, typeof(*n), link); 183 if (n->cpu == smp_processor_id()) 184 apf_task_wake_one(n); 185 } 186 raw_spin_unlock(&b->lock); 187 } 188 } 189 190 void kvm_async_pf_task_wake(u32 token) 191 { 192 u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); 193 struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; 194 struct kvm_task_sleep_node *n; 195 196 if (token == ~0) { 197 apf_task_wake_all(); 198 return; 199 } 200 201 again: 202 raw_spin_lock(&b->lock); 203 n = _find_apf_task(b, token); 204 if (!n) { 205 /* 206 * async PF was not yet handled. 207 * Add dummy entry for the token. 208 */ 209 n = kzalloc(sizeof(*n), GFP_ATOMIC); 210 if (!n) { 211 /* 212 * Allocation failed! Busy wait while other cpu 213 * handles async PF. 214 */ 215 raw_spin_unlock(&b->lock); 216 cpu_relax(); 217 goto again; 218 } 219 n->token = token; 220 n->cpu = smp_processor_id(); 221 init_swait_queue_head(&n->wq); 222 hlist_add_head(&n->link, &b->list); 223 } else { 224 apf_task_wake_one(n); 225 } 226 raw_spin_unlock(&b->lock); 227 return; 228 } 229 EXPORT_SYMBOL_GPL(kvm_async_pf_task_wake); 230 231 noinstr u32 kvm_read_and_reset_apf_flags(void) 232 { 233 u32 flags = 0; 234 235 if (__this_cpu_read(apf_reason.enabled)) { 236 flags = __this_cpu_read(apf_reason.flags); 237 __this_cpu_write(apf_reason.flags, 0); 238 } 239 240 return flags; 241 } 242 EXPORT_SYMBOL_GPL(kvm_read_and_reset_apf_flags); 243 244 noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token) 245 { 246 u32 flags = kvm_read_and_reset_apf_flags(); 247 irqentry_state_t state; 248 249 if (!flags) 250 return false; 251 252 state = irqentry_enter(regs); 253 instrumentation_begin(); 254 255 /* 256 * If the host managed to inject an async #PF into an interrupt 257 * disabled region, then die hard as this is not going to end well 258 * and the host side is seriously broken. 259 */ 260 if (unlikely(!(regs->flags & X86_EFLAGS_IF))) 261 panic("Host injected async #PF in interrupt disabled region\n"); 262 263 if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) { 264 if (unlikely(!(user_mode(regs)))) 265 panic("Host injected async #PF in kernel mode\n"); 266 /* Page is swapped out by the host. */ 267 kvm_async_pf_task_wait_schedule(token); 268 } else { 269 WARN_ONCE(1, "Unexpected async PF flags: %x\n", flags); 270 } 271 272 instrumentation_end(); 273 irqentry_exit(regs, state); 274 return true; 275 } 276 277 DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_asyncpf_interrupt) 278 { 279 struct pt_regs *old_regs = set_irq_regs(regs); 280 u32 token; 281 282 ack_APIC_irq(); 283 284 inc_irq_stat(irq_hv_callback_count); 285 286 if (__this_cpu_read(apf_reason.enabled)) { 287 token = __this_cpu_read(apf_reason.token); 288 kvm_async_pf_task_wake(token); 289 __this_cpu_write(apf_reason.token, 0); 290 wrmsrl(MSR_KVM_ASYNC_PF_ACK, 1); 291 } 292 293 set_irq_regs(old_regs); 294 } 295 296 static void __init paravirt_ops_setup(void) 297 { 298 pv_info.name = "KVM"; 299 300 if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY)) 301 pv_ops.cpu.io_delay = kvm_io_delay; 302 303 #ifdef CONFIG_X86_IO_APIC 304 no_timer_check = 1; 305 #endif 306 } 307 308 static void kvm_register_steal_time(void) 309 { 310 int cpu = smp_processor_id(); 311 struct kvm_steal_time *st = &per_cpu(steal_time, cpu); 312 313 if (!has_steal_clock) 314 return; 315 316 wrmsrl(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED)); 317 pr_debug("stealtime: cpu %d, msr %llx\n", cpu, 318 (unsigned long long) slow_virt_to_phys(st)); 319 } 320 321 static DEFINE_PER_CPU_DECRYPTED(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED; 322 323 static notrace void kvm_guest_apic_eoi_write(u32 reg, u32 val) 324 { 325 /** 326 * This relies on __test_and_clear_bit to modify the memory 327 * in a way that is atomic with respect to the local CPU. 328 * The hypervisor only accesses this memory from the local CPU so 329 * there's no need for lock or memory barriers. 330 * An optimization barrier is implied in apic write. 331 */ 332 if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi))) 333 return; 334 apic->native_eoi_write(APIC_EOI, APIC_EOI_ACK); 335 } 336 337 static void kvm_guest_cpu_init(void) 338 { 339 if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) { 340 u64 pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason)); 341 342 WARN_ON_ONCE(!static_branch_likely(&kvm_async_pf_enabled)); 343 344 pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason)); 345 pa |= KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT; 346 347 if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_VMEXIT)) 348 pa |= KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT; 349 350 wrmsrl(MSR_KVM_ASYNC_PF_INT, HYPERVISOR_CALLBACK_VECTOR); 351 352 wrmsrl(MSR_KVM_ASYNC_PF_EN, pa); 353 __this_cpu_write(apf_reason.enabled, 1); 354 pr_debug("setup async PF for cpu %d\n", smp_processor_id()); 355 } 356 357 if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) { 358 unsigned long pa; 359 360 /* Size alignment is implied but just to make it explicit. */ 361 BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4); 362 __this_cpu_write(kvm_apic_eoi, 0); 363 pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi)) 364 | KVM_MSR_ENABLED; 365 wrmsrl(MSR_KVM_PV_EOI_EN, pa); 366 } 367 368 if (has_steal_clock) 369 kvm_register_steal_time(); 370 } 371 372 static void kvm_pv_disable_apf(void) 373 { 374 if (!__this_cpu_read(apf_reason.enabled)) 375 return; 376 377 wrmsrl(MSR_KVM_ASYNC_PF_EN, 0); 378 __this_cpu_write(apf_reason.enabled, 0); 379 380 pr_debug("disable async PF for cpu %d\n", smp_processor_id()); 381 } 382 383 static void kvm_disable_steal_time(void) 384 { 385 if (!has_steal_clock) 386 return; 387 388 wrmsr(MSR_KVM_STEAL_TIME, 0, 0); 389 } 390 391 static u64 kvm_steal_clock(int cpu) 392 { 393 u64 steal; 394 struct kvm_steal_time *src; 395 int version; 396 397 src = &per_cpu(steal_time, cpu); 398 do { 399 version = src->version; 400 virt_rmb(); 401 steal = src->steal; 402 virt_rmb(); 403 } while ((version & 1) || (version != src->version)); 404 405 return steal; 406 } 407 408 static inline void __set_percpu_decrypted(void *ptr, unsigned long size) 409 { 410 early_set_memory_decrypted((unsigned long) ptr, size); 411 } 412 413 /* 414 * Iterate through all possible CPUs and map the memory region pointed 415 * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once. 416 * 417 * Note: we iterate through all possible CPUs to ensure that CPUs 418 * hotplugged will have their per-cpu variable already mapped as 419 * decrypted. 420 */ 421 static void __init sev_map_percpu_data(void) 422 { 423 int cpu; 424 425 if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) 426 return; 427 428 for_each_possible_cpu(cpu) { 429 __set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason)); 430 __set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time)); 431 __set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi)); 432 } 433 } 434 435 static void kvm_guest_cpu_offline(bool shutdown) 436 { 437 kvm_disable_steal_time(); 438 if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) 439 wrmsrl(MSR_KVM_PV_EOI_EN, 0); 440 if (kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) 441 wrmsrl(MSR_KVM_MIGRATION_CONTROL, 0); 442 kvm_pv_disable_apf(); 443 if (!shutdown) 444 apf_task_wake_all(); 445 kvmclock_disable(); 446 } 447 448 static int kvm_cpu_online(unsigned int cpu) 449 { 450 unsigned long flags; 451 452 local_irq_save(flags); 453 kvm_guest_cpu_init(); 454 local_irq_restore(flags); 455 return 0; 456 } 457 458 #ifdef CONFIG_SMP 459 460 static DEFINE_PER_CPU(cpumask_var_t, __pv_cpu_mask); 461 462 static bool pv_tlb_flush_supported(void) 463 { 464 return (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) && 465 !kvm_para_has_hint(KVM_HINTS_REALTIME) && 466 kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) && 467 !boot_cpu_has(X86_FEATURE_MWAIT) && 468 (num_possible_cpus() != 1)); 469 } 470 471 static bool pv_ipi_supported(void) 472 { 473 return (kvm_para_has_feature(KVM_FEATURE_PV_SEND_IPI) && 474 (num_possible_cpus() != 1)); 475 } 476 477 static bool pv_sched_yield_supported(void) 478 { 479 return (kvm_para_has_feature(KVM_FEATURE_PV_SCHED_YIELD) && 480 !kvm_para_has_hint(KVM_HINTS_REALTIME) && 481 kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) && 482 !boot_cpu_has(X86_FEATURE_MWAIT) && 483 (num_possible_cpus() != 1)); 484 } 485 486 #define KVM_IPI_CLUSTER_SIZE (2 * BITS_PER_LONG) 487 488 static void __send_ipi_mask(const struct cpumask *mask, int vector) 489 { 490 unsigned long flags; 491 int cpu, apic_id, icr; 492 int min = 0, max = 0; 493 #ifdef CONFIG_X86_64 494 __uint128_t ipi_bitmap = 0; 495 #else 496 u64 ipi_bitmap = 0; 497 #endif 498 long ret; 499 500 if (cpumask_empty(mask)) 501 return; 502 503 local_irq_save(flags); 504 505 switch (vector) { 506 default: 507 icr = APIC_DM_FIXED | vector; 508 break; 509 case NMI_VECTOR: 510 icr = APIC_DM_NMI; 511 break; 512 } 513 514 for_each_cpu(cpu, mask) { 515 apic_id = per_cpu(x86_cpu_to_apicid, cpu); 516 if (!ipi_bitmap) { 517 min = max = apic_id; 518 } else if (apic_id < min && max - apic_id < KVM_IPI_CLUSTER_SIZE) { 519 ipi_bitmap <<= min - apic_id; 520 min = apic_id; 521 } else if (apic_id > min && apic_id < min + KVM_IPI_CLUSTER_SIZE) { 522 max = apic_id < max ? max : apic_id; 523 } else { 524 ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap, 525 (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr); 526 WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld", 527 ret); 528 min = max = apic_id; 529 ipi_bitmap = 0; 530 } 531 __set_bit(apic_id - min, (unsigned long *)&ipi_bitmap); 532 } 533 534 if (ipi_bitmap) { 535 ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap, 536 (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr); 537 WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld", 538 ret); 539 } 540 541 local_irq_restore(flags); 542 } 543 544 static void kvm_send_ipi_mask(const struct cpumask *mask, int vector) 545 { 546 __send_ipi_mask(mask, vector); 547 } 548 549 static void kvm_send_ipi_mask_allbutself(const struct cpumask *mask, int vector) 550 { 551 unsigned int this_cpu = smp_processor_id(); 552 struct cpumask *new_mask = this_cpu_cpumask_var_ptr(__pv_cpu_mask); 553 const struct cpumask *local_mask; 554 555 cpumask_copy(new_mask, mask); 556 cpumask_clear_cpu(this_cpu, new_mask); 557 local_mask = new_mask; 558 __send_ipi_mask(local_mask, vector); 559 } 560 561 static int __init setup_efi_kvm_sev_migration(void) 562 { 563 efi_char16_t efi_sev_live_migration_enabled[] = L"SevLiveMigrationEnabled"; 564 efi_guid_t efi_variable_guid = AMD_SEV_MEM_ENCRYPT_GUID; 565 efi_status_t status; 566 unsigned long size; 567 bool enabled; 568 569 if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) || 570 !kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) 571 return 0; 572 573 if (!efi_enabled(EFI_BOOT)) 574 return 0; 575 576 if (!efi_enabled(EFI_RUNTIME_SERVICES)) { 577 pr_info("%s : EFI runtime services are not enabled\n", __func__); 578 return 0; 579 } 580 581 size = sizeof(enabled); 582 583 /* Get variable contents into buffer */ 584 status = efi.get_variable(efi_sev_live_migration_enabled, 585 &efi_variable_guid, NULL, &size, &enabled); 586 587 if (status == EFI_NOT_FOUND) { 588 pr_info("%s : EFI live migration variable not found\n", __func__); 589 return 0; 590 } 591 592 if (status != EFI_SUCCESS) { 593 pr_info("%s : EFI variable retrieval failed\n", __func__); 594 return 0; 595 } 596 597 if (enabled == 0) { 598 pr_info("%s: live migration disabled in EFI\n", __func__); 599 return 0; 600 } 601 602 pr_info("%s : live migration enabled in EFI\n", __func__); 603 wrmsrl(MSR_KVM_MIGRATION_CONTROL, KVM_MIGRATION_READY); 604 605 return 1; 606 } 607 608 late_initcall(setup_efi_kvm_sev_migration); 609 610 /* 611 * Set the IPI entry points 612 */ 613 static void kvm_setup_pv_ipi(void) 614 { 615 apic->send_IPI_mask = kvm_send_ipi_mask; 616 apic->send_IPI_mask_allbutself = kvm_send_ipi_mask_allbutself; 617 pr_info("setup PV IPIs\n"); 618 } 619 620 static void kvm_smp_send_call_func_ipi(const struct cpumask *mask) 621 { 622 int cpu; 623 624 native_send_call_func_ipi(mask); 625 626 /* Make sure other vCPUs get a chance to run if they need to. */ 627 for_each_cpu(cpu, mask) { 628 if (!idle_cpu(cpu) && vcpu_is_preempted(cpu)) { 629 kvm_hypercall1(KVM_HC_SCHED_YIELD, per_cpu(x86_cpu_to_apicid, cpu)); 630 break; 631 } 632 } 633 } 634 635 static void kvm_flush_tlb_multi(const struct cpumask *cpumask, 636 const struct flush_tlb_info *info) 637 { 638 u8 state; 639 int cpu; 640 struct kvm_steal_time *src; 641 struct cpumask *flushmask = this_cpu_cpumask_var_ptr(__pv_cpu_mask); 642 643 cpumask_copy(flushmask, cpumask); 644 /* 645 * We have to call flush only on online vCPUs. And 646 * queue flush_on_enter for pre-empted vCPUs 647 */ 648 for_each_cpu(cpu, flushmask) { 649 /* 650 * The local vCPU is never preempted, so we do not explicitly 651 * skip check for local vCPU - it will never be cleared from 652 * flushmask. 653 */ 654 src = &per_cpu(steal_time, cpu); 655 state = READ_ONCE(src->preempted); 656 if ((state & KVM_VCPU_PREEMPTED)) { 657 if (try_cmpxchg(&src->preempted, &state, 658 state | KVM_VCPU_FLUSH_TLB)) 659 __cpumask_clear_cpu(cpu, flushmask); 660 } 661 } 662 663 native_flush_tlb_multi(flushmask, info); 664 } 665 666 static __init int kvm_alloc_cpumask(void) 667 { 668 int cpu; 669 670 if (!kvm_para_available() || nopv) 671 return 0; 672 673 if (pv_tlb_flush_supported() || pv_ipi_supported()) 674 for_each_possible_cpu(cpu) { 675 zalloc_cpumask_var_node(per_cpu_ptr(&__pv_cpu_mask, cpu), 676 GFP_KERNEL, cpu_to_node(cpu)); 677 } 678 679 return 0; 680 } 681 arch_initcall(kvm_alloc_cpumask); 682 683 static void __init kvm_smp_prepare_boot_cpu(void) 684 { 685 /* 686 * Map the per-cpu variables as decrypted before kvm_guest_cpu_init() 687 * shares the guest physical address with the hypervisor. 688 */ 689 sev_map_percpu_data(); 690 691 kvm_guest_cpu_init(); 692 native_smp_prepare_boot_cpu(); 693 kvm_spinlock_init(); 694 } 695 696 static int kvm_cpu_down_prepare(unsigned int cpu) 697 { 698 unsigned long flags; 699 700 local_irq_save(flags); 701 kvm_guest_cpu_offline(false); 702 local_irq_restore(flags); 703 return 0; 704 } 705 706 #endif 707 708 static int kvm_suspend(void) 709 { 710 u64 val = 0; 711 712 kvm_guest_cpu_offline(false); 713 714 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL 715 if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) 716 rdmsrl(MSR_KVM_POLL_CONTROL, val); 717 has_guest_poll = !(val & 1); 718 #endif 719 return 0; 720 } 721 722 static void kvm_resume(void) 723 { 724 kvm_cpu_online(raw_smp_processor_id()); 725 726 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL 727 if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL) && has_guest_poll) 728 wrmsrl(MSR_KVM_POLL_CONTROL, 0); 729 #endif 730 } 731 732 static struct syscore_ops kvm_syscore_ops = { 733 .suspend = kvm_suspend, 734 .resume = kvm_resume, 735 }; 736 737 static void kvm_pv_guest_cpu_reboot(void *unused) 738 { 739 kvm_guest_cpu_offline(true); 740 } 741 742 static int kvm_pv_reboot_notify(struct notifier_block *nb, 743 unsigned long code, void *unused) 744 { 745 if (code == SYS_RESTART) 746 on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1); 747 return NOTIFY_DONE; 748 } 749 750 static struct notifier_block kvm_pv_reboot_nb = { 751 .notifier_call = kvm_pv_reboot_notify, 752 }; 753 754 /* 755 * After a PV feature is registered, the host will keep writing to the 756 * registered memory location. If the guest happens to shutdown, this memory 757 * won't be valid. In cases like kexec, in which you install a new kernel, this 758 * means a random memory location will be kept being written. 759 */ 760 #ifdef CONFIG_KEXEC_CORE 761 static void kvm_crash_shutdown(struct pt_regs *regs) 762 { 763 kvm_guest_cpu_offline(true); 764 native_machine_crash_shutdown(regs); 765 } 766 #endif 767 768 static void __init kvm_guest_init(void) 769 { 770 int i; 771 772 paravirt_ops_setup(); 773 register_reboot_notifier(&kvm_pv_reboot_nb); 774 for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) 775 raw_spin_lock_init(&async_pf_sleepers[i].lock); 776 777 if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) { 778 has_steal_clock = 1; 779 static_call_update(pv_steal_clock, kvm_steal_clock); 780 } 781 782 if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) 783 apic_set_eoi_write(kvm_guest_apic_eoi_write); 784 785 if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) { 786 static_branch_enable(&kvm_async_pf_enabled); 787 alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_kvm_asyncpf_interrupt); 788 } 789 790 #ifdef CONFIG_SMP 791 if (pv_tlb_flush_supported()) { 792 pv_ops.mmu.flush_tlb_multi = kvm_flush_tlb_multi; 793 pv_ops.mmu.tlb_remove_table = tlb_remove_table; 794 pr_info("KVM setup pv remote TLB flush\n"); 795 } 796 797 smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu; 798 if (pv_sched_yield_supported()) { 799 smp_ops.send_call_func_ipi = kvm_smp_send_call_func_ipi; 800 pr_info("setup PV sched yield\n"); 801 } 802 if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online", 803 kvm_cpu_online, kvm_cpu_down_prepare) < 0) 804 pr_err("failed to install cpu hotplug callbacks\n"); 805 #else 806 sev_map_percpu_data(); 807 kvm_guest_cpu_init(); 808 #endif 809 810 #ifdef CONFIG_KEXEC_CORE 811 machine_ops.crash_shutdown = kvm_crash_shutdown; 812 #endif 813 814 register_syscore_ops(&kvm_syscore_ops); 815 816 /* 817 * Hard lockup detection is enabled by default. Disable it, as guests 818 * can get false positives too easily, for example if the host is 819 * overcommitted. 820 */ 821 hardlockup_detector_disable(); 822 } 823 824 static noinline uint32_t __kvm_cpuid_base(void) 825 { 826 if (boot_cpu_data.cpuid_level < 0) 827 return 0; /* So we don't blow up on old processors */ 828 829 if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) 830 return hypervisor_cpuid_base(KVM_SIGNATURE, 0); 831 832 return 0; 833 } 834 835 static inline uint32_t kvm_cpuid_base(void) 836 { 837 static int kvm_cpuid_base = -1; 838 839 if (kvm_cpuid_base == -1) 840 kvm_cpuid_base = __kvm_cpuid_base(); 841 842 return kvm_cpuid_base; 843 } 844 845 bool kvm_para_available(void) 846 { 847 return kvm_cpuid_base() != 0; 848 } 849 EXPORT_SYMBOL_GPL(kvm_para_available); 850 851 unsigned int kvm_arch_para_features(void) 852 { 853 return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES); 854 } 855 856 unsigned int kvm_arch_para_hints(void) 857 { 858 return cpuid_edx(kvm_cpuid_base() | KVM_CPUID_FEATURES); 859 } 860 EXPORT_SYMBOL_GPL(kvm_arch_para_hints); 861 862 static uint32_t __init kvm_detect(void) 863 { 864 return kvm_cpuid_base(); 865 } 866 867 static void __init kvm_apic_init(void) 868 { 869 #ifdef CONFIG_SMP 870 if (pv_ipi_supported()) 871 kvm_setup_pv_ipi(); 872 #endif 873 } 874 875 static bool __init kvm_msi_ext_dest_id(void) 876 { 877 return kvm_para_has_feature(KVM_FEATURE_MSI_EXT_DEST_ID); 878 } 879 880 static void kvm_sev_hc_page_enc_status(unsigned long pfn, int npages, bool enc) 881 { 882 kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, pfn << PAGE_SHIFT, npages, 883 KVM_MAP_GPA_RANGE_ENC_STAT(enc) | KVM_MAP_GPA_RANGE_PAGE_SZ_4K); 884 } 885 886 static void __init kvm_init_platform(void) 887 { 888 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) && 889 kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) { 890 unsigned long nr_pages; 891 int i; 892 893 pv_ops.mmu.notify_page_enc_status_changed = 894 kvm_sev_hc_page_enc_status; 895 896 /* 897 * Reset the host's shared pages list related to kernel 898 * specific page encryption status settings before we load a 899 * new kernel by kexec. Reset the page encryption status 900 * during early boot intead of just before kexec to avoid SMP 901 * races during kvm_pv_guest_cpu_reboot(). 902 * NOTE: We cannot reset the complete shared pages list 903 * here as we need to retain the UEFI/OVMF firmware 904 * specific settings. 905 */ 906 907 for (i = 0; i < e820_table->nr_entries; i++) { 908 struct e820_entry *entry = &e820_table->entries[i]; 909 910 if (entry->type != E820_TYPE_RAM) 911 continue; 912 913 nr_pages = DIV_ROUND_UP(entry->size, PAGE_SIZE); 914 915 kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, entry->addr, 916 nr_pages, 917 KVM_MAP_GPA_RANGE_ENCRYPTED | KVM_MAP_GPA_RANGE_PAGE_SZ_4K); 918 } 919 920 /* 921 * Ensure that _bss_decrypted section is marked as decrypted in the 922 * shared pages list. 923 */ 924 nr_pages = DIV_ROUND_UP(__end_bss_decrypted - __start_bss_decrypted, 925 PAGE_SIZE); 926 early_set_mem_enc_dec_hypercall((unsigned long)__start_bss_decrypted, 927 nr_pages, 0); 928 929 /* 930 * If not booted using EFI, enable Live migration support. 931 */ 932 if (!efi_enabled(EFI_BOOT)) 933 wrmsrl(MSR_KVM_MIGRATION_CONTROL, 934 KVM_MIGRATION_READY); 935 } 936 kvmclock_init(); 937 x86_platform.apic_post_init = kvm_apic_init; 938 } 939 940 #if defined(CONFIG_AMD_MEM_ENCRYPT) 941 static void kvm_sev_es_hcall_prepare(struct ghcb *ghcb, struct pt_regs *regs) 942 { 943 /* RAX and CPL are already in the GHCB */ 944 ghcb_set_rbx(ghcb, regs->bx); 945 ghcb_set_rcx(ghcb, regs->cx); 946 ghcb_set_rdx(ghcb, regs->dx); 947 ghcb_set_rsi(ghcb, regs->si); 948 } 949 950 static bool kvm_sev_es_hcall_finish(struct ghcb *ghcb, struct pt_regs *regs) 951 { 952 /* No checking of the return state needed */ 953 return true; 954 } 955 #endif 956 957 const __initconst struct hypervisor_x86 x86_hyper_kvm = { 958 .name = "KVM", 959 .detect = kvm_detect, 960 .type = X86_HYPER_KVM, 961 .init.guest_late_init = kvm_guest_init, 962 .init.x2apic_available = kvm_para_available, 963 .init.msi_ext_dest_id = kvm_msi_ext_dest_id, 964 .init.init_platform = kvm_init_platform, 965 #if defined(CONFIG_AMD_MEM_ENCRYPT) 966 .runtime.sev_es_hcall_prepare = kvm_sev_es_hcall_prepare, 967 .runtime.sev_es_hcall_finish = kvm_sev_es_hcall_finish, 968 #endif 969 }; 970 971 static __init int activate_jump_labels(void) 972 { 973 if (has_steal_clock) { 974 static_key_slow_inc(¶virt_steal_enabled); 975 if (steal_acc) 976 static_key_slow_inc(¶virt_steal_rq_enabled); 977 } 978 979 return 0; 980 } 981 arch_initcall(activate_jump_labels); 982 983 #ifdef CONFIG_PARAVIRT_SPINLOCKS 984 985 /* Kick a cpu by its apicid. Used to wake up a halted vcpu */ 986 static void kvm_kick_cpu(int cpu) 987 { 988 int apicid; 989 unsigned long flags = 0; 990 991 apicid = per_cpu(x86_cpu_to_apicid, cpu); 992 kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid); 993 } 994 995 #include <asm/qspinlock.h> 996 997 static void kvm_wait(u8 *ptr, u8 val) 998 { 999 if (in_nmi()) 1000 return; 1001 1002 /* 1003 * halt until it's our turn and kicked. Note that we do safe halt 1004 * for irq enabled case to avoid hang when lock info is overwritten 1005 * in irq spinlock slowpath and no spurious interrupt occur to save us. 1006 */ 1007 if (irqs_disabled()) { 1008 if (READ_ONCE(*ptr) == val) 1009 halt(); 1010 } else { 1011 local_irq_disable(); 1012 1013 /* safe_halt() will enable IRQ */ 1014 if (READ_ONCE(*ptr) == val) 1015 safe_halt(); 1016 else 1017 local_irq_enable(); 1018 } 1019 } 1020 1021 #ifdef CONFIG_X86_32 1022 __visible bool __kvm_vcpu_is_preempted(long cpu) 1023 { 1024 struct kvm_steal_time *src = &per_cpu(steal_time, cpu); 1025 1026 return !!(src->preempted & KVM_VCPU_PREEMPTED); 1027 } 1028 PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted); 1029 1030 #else 1031 1032 #include <asm/asm-offsets.h> 1033 1034 extern bool __raw_callee_save___kvm_vcpu_is_preempted(long); 1035 1036 /* 1037 * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and 1038 * restoring to/from the stack. 1039 */ 1040 asm( 1041 ".pushsection .text;" 1042 ".global __raw_callee_save___kvm_vcpu_is_preempted;" 1043 ".type __raw_callee_save___kvm_vcpu_is_preempted, @function;" 1044 "__raw_callee_save___kvm_vcpu_is_preempted:" 1045 ASM_ENDBR 1046 "movq __per_cpu_offset(,%rdi,8), %rax;" 1047 "cmpb $0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax);" 1048 "setne %al;" 1049 ASM_RET 1050 ".size __raw_callee_save___kvm_vcpu_is_preempted, .-__raw_callee_save___kvm_vcpu_is_preempted;" 1051 ".popsection"); 1052 1053 #endif 1054 1055 /* 1056 * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present. 1057 */ 1058 void __init kvm_spinlock_init(void) 1059 { 1060 /* 1061 * In case host doesn't support KVM_FEATURE_PV_UNHALT there is still an 1062 * advantage of keeping virt_spin_lock_key enabled: virt_spin_lock() is 1063 * preferred over native qspinlock when vCPU is preempted. 1064 */ 1065 if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) { 1066 pr_info("PV spinlocks disabled, no host support\n"); 1067 return; 1068 } 1069 1070 /* 1071 * Disable PV spinlocks and use native qspinlock when dedicated pCPUs 1072 * are available. 1073 */ 1074 if (kvm_para_has_hint(KVM_HINTS_REALTIME)) { 1075 pr_info("PV spinlocks disabled with KVM_HINTS_REALTIME hints\n"); 1076 goto out; 1077 } 1078 1079 if (num_possible_cpus() == 1) { 1080 pr_info("PV spinlocks disabled, single CPU\n"); 1081 goto out; 1082 } 1083 1084 if (nopvspin) { 1085 pr_info("PV spinlocks disabled, forced by \"nopvspin\" parameter\n"); 1086 goto out; 1087 } 1088 1089 pr_info("PV spinlocks enabled\n"); 1090 1091 __pv_init_lock_hash(); 1092 pv_ops.lock.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath; 1093 pv_ops.lock.queued_spin_unlock = 1094 PV_CALLEE_SAVE(__pv_queued_spin_unlock); 1095 pv_ops.lock.wait = kvm_wait; 1096 pv_ops.lock.kick = kvm_kick_cpu; 1097 1098 if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) { 1099 pv_ops.lock.vcpu_is_preempted = 1100 PV_CALLEE_SAVE(__kvm_vcpu_is_preempted); 1101 } 1102 /* 1103 * When PV spinlock is enabled which is preferred over 1104 * virt_spin_lock(), virt_spin_lock_key's value is meaningless. 1105 * Just disable it anyway. 1106 */ 1107 out: 1108 static_branch_disable(&virt_spin_lock_key); 1109 } 1110 1111 #endif /* CONFIG_PARAVIRT_SPINLOCKS */ 1112 1113 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL 1114 1115 static void kvm_disable_host_haltpoll(void *i) 1116 { 1117 wrmsrl(MSR_KVM_POLL_CONTROL, 0); 1118 } 1119 1120 static void kvm_enable_host_haltpoll(void *i) 1121 { 1122 wrmsrl(MSR_KVM_POLL_CONTROL, 1); 1123 } 1124 1125 void arch_haltpoll_enable(unsigned int cpu) 1126 { 1127 if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) { 1128 pr_err_once("host does not support poll control\n"); 1129 pr_err_once("host upgrade recommended\n"); 1130 return; 1131 } 1132 1133 /* Enable guest halt poll disables host halt poll */ 1134 smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1); 1135 } 1136 EXPORT_SYMBOL_GPL(arch_haltpoll_enable); 1137 1138 void arch_haltpoll_disable(unsigned int cpu) 1139 { 1140 if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) 1141 return; 1142 1143 /* Disable guest halt poll enables host halt poll */ 1144 smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1); 1145 } 1146 EXPORT_SYMBOL_GPL(arch_haltpoll_disable); 1147 #endif 1148