1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Kernel-based Virtual Machine driver for Linux 4 * 5 * AMD SVM-SEV support 6 * 7 * Copyright 2010 Red Hat, Inc. and/or its affiliates. 8 */ 9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 10 11 #include <linux/kvm_types.h> 12 #include <linux/kvm_host.h> 13 #include <linux/kernel.h> 14 #include <linux/highmem.h> 15 #include <linux/psp.h> 16 #include <linux/psp-sev.h> 17 #include <linux/pagemap.h> 18 #include <linux/swap.h> 19 #include <linux/misc_cgroup.h> 20 #include <linux/processor.h> 21 #include <linux/trace_events.h> 22 #include <uapi/linux/sev-guest.h> 23 24 #include <asm/pkru.h> 25 #include <asm/trapnr.h> 26 #include <asm/fpu/xcr.h> 27 #include <asm/fpu/xstate.h> 28 #include <asm/debugreg.h> 29 #include <asm/msr.h> 30 #include <asm/sev.h> 31 32 #include "mmu.h" 33 #include "x86.h" 34 #include "svm.h" 35 #include "svm_ops.h" 36 #include "cpuid.h" 37 #include "trace.h" 38 39 #define GHCB_VERSION_MAX 2ULL 40 #define GHCB_VERSION_DEFAULT 2ULL 41 #define GHCB_VERSION_MIN 1ULL 42 43 #define GHCB_HV_FT_SUPPORTED (GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION) 44 45 /* enable/disable SEV support */ 46 static bool sev_enabled = true; 47 module_param_named(sev, sev_enabled, bool, 0444); 48 49 /* enable/disable SEV-ES support */ 50 static bool sev_es_enabled = true; 51 module_param_named(sev_es, sev_es_enabled, bool, 0444); 52 53 /* enable/disable SEV-SNP support */ 54 static bool sev_snp_enabled = true; 55 module_param_named(sev_snp, sev_snp_enabled, bool, 0444); 56 57 /* enable/disable SEV-ES DebugSwap support */ 58 static bool sev_es_debug_swap_enabled = true; 59 module_param_named(debug_swap, sev_es_debug_swap_enabled, bool, 0444); 60 static u64 sev_supported_vmsa_features; 61 62 #define AP_RESET_HOLD_NONE 0 63 #define AP_RESET_HOLD_NAE_EVENT 1 64 #define AP_RESET_HOLD_MSR_PROTO 2 65 66 /* As defined by SEV-SNP Firmware ABI, under "Guest Policy". */ 67 #define SNP_POLICY_MASK_API_MINOR GENMASK_ULL(7, 0) 68 #define SNP_POLICY_MASK_API_MAJOR GENMASK_ULL(15, 8) 69 #define SNP_POLICY_MASK_SMT BIT_ULL(16) 70 #define SNP_POLICY_MASK_RSVD_MBO BIT_ULL(17) 71 #define SNP_POLICY_MASK_DEBUG BIT_ULL(19) 72 #define SNP_POLICY_MASK_SINGLE_SOCKET BIT_ULL(20) 73 74 #define SNP_POLICY_MASK_VALID (SNP_POLICY_MASK_API_MINOR | \ 75 SNP_POLICY_MASK_API_MAJOR | \ 76 SNP_POLICY_MASK_SMT | \ 77 SNP_POLICY_MASK_RSVD_MBO | \ 78 SNP_POLICY_MASK_DEBUG | \ 79 SNP_POLICY_MASK_SINGLE_SOCKET) 80 81 #define INITIAL_VMSA_GPA 0xFFFFFFFFF000 82 83 static u8 sev_enc_bit; 84 static DECLARE_RWSEM(sev_deactivate_lock); 85 static DEFINE_MUTEX(sev_bitmap_lock); 86 unsigned int max_sev_asid; 87 static unsigned int min_sev_asid; 88 static unsigned long sev_me_mask; 89 static unsigned int nr_asids; 90 static unsigned long *sev_asid_bitmap; 91 static unsigned long *sev_reclaim_asid_bitmap; 92 93 static int snp_decommission_context(struct kvm *kvm); 94 95 struct enc_region { 96 struct list_head list; 97 unsigned long npages; 98 struct page **pages; 99 unsigned long uaddr; 100 unsigned long size; 101 }; 102 103 /* Called with the sev_bitmap_lock held, or on shutdown */ 104 static int sev_flush_asids(unsigned int min_asid, unsigned int max_asid) 105 { 106 int ret, error = 0; 107 unsigned int asid; 108 109 /* Check if there are any ASIDs to reclaim before performing a flush */ 110 asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid); 111 if (asid > max_asid) 112 return -EBUSY; 113 114 /* 115 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail, 116 * so it must be guarded. 117 */ 118 down_write(&sev_deactivate_lock); 119 120 wbinvd_on_all_cpus(); 121 122 if (sev_snp_enabled) 123 ret = sev_do_cmd(SEV_CMD_SNP_DF_FLUSH, NULL, &error); 124 else 125 ret = sev_guest_df_flush(&error); 126 127 up_write(&sev_deactivate_lock); 128 129 if (ret) 130 pr_err("SEV%s: DF_FLUSH failed, ret=%d, error=%#x\n", 131 sev_snp_enabled ? "-SNP" : "", ret, error); 132 133 return ret; 134 } 135 136 static inline bool is_mirroring_enc_context(struct kvm *kvm) 137 { 138 return !!to_kvm_sev_info(kvm)->enc_context_owner; 139 } 140 141 static bool sev_vcpu_has_debug_swap(struct vcpu_svm *svm) 142 { 143 struct kvm_vcpu *vcpu = &svm->vcpu; 144 struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm); 145 146 return sev->vmsa_features & SVM_SEV_FEAT_DEBUG_SWAP; 147 } 148 149 /* Must be called with the sev_bitmap_lock held */ 150 static bool __sev_recycle_asids(unsigned int min_asid, unsigned int max_asid) 151 { 152 if (sev_flush_asids(min_asid, max_asid)) 153 return false; 154 155 /* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */ 156 bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap, 157 nr_asids); 158 bitmap_zero(sev_reclaim_asid_bitmap, nr_asids); 159 160 return true; 161 } 162 163 static int sev_misc_cg_try_charge(struct kvm_sev_info *sev) 164 { 165 enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV; 166 return misc_cg_try_charge(type, sev->misc_cg, 1); 167 } 168 169 static void sev_misc_cg_uncharge(struct kvm_sev_info *sev) 170 { 171 enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV; 172 misc_cg_uncharge(type, sev->misc_cg, 1); 173 } 174 175 static int sev_asid_new(struct kvm_sev_info *sev) 176 { 177 /* 178 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid. 179 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1. 180 * Note: min ASID can end up larger than the max if basic SEV support is 181 * effectively disabled by disallowing use of ASIDs for SEV guests. 182 */ 183 unsigned int min_asid = sev->es_active ? 1 : min_sev_asid; 184 unsigned int max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid; 185 unsigned int asid; 186 bool retry = true; 187 int ret; 188 189 if (min_asid > max_asid) 190 return -ENOTTY; 191 192 WARN_ON(sev->misc_cg); 193 sev->misc_cg = get_current_misc_cg(); 194 ret = sev_misc_cg_try_charge(sev); 195 if (ret) { 196 put_misc_cg(sev->misc_cg); 197 sev->misc_cg = NULL; 198 return ret; 199 } 200 201 mutex_lock(&sev_bitmap_lock); 202 203 again: 204 asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid); 205 if (asid > max_asid) { 206 if (retry && __sev_recycle_asids(min_asid, max_asid)) { 207 retry = false; 208 goto again; 209 } 210 mutex_unlock(&sev_bitmap_lock); 211 ret = -EBUSY; 212 goto e_uncharge; 213 } 214 215 __set_bit(asid, sev_asid_bitmap); 216 217 mutex_unlock(&sev_bitmap_lock); 218 219 sev->asid = asid; 220 return 0; 221 e_uncharge: 222 sev_misc_cg_uncharge(sev); 223 put_misc_cg(sev->misc_cg); 224 sev->misc_cg = NULL; 225 return ret; 226 } 227 228 static unsigned int sev_get_asid(struct kvm *kvm) 229 { 230 return to_kvm_sev_info(kvm)->asid; 231 } 232 233 static void sev_asid_free(struct kvm_sev_info *sev) 234 { 235 struct svm_cpu_data *sd; 236 int cpu; 237 238 mutex_lock(&sev_bitmap_lock); 239 240 __set_bit(sev->asid, sev_reclaim_asid_bitmap); 241 242 for_each_possible_cpu(cpu) { 243 sd = per_cpu_ptr(&svm_data, cpu); 244 sd->sev_vmcbs[sev->asid] = NULL; 245 } 246 247 mutex_unlock(&sev_bitmap_lock); 248 249 sev_misc_cg_uncharge(sev); 250 put_misc_cg(sev->misc_cg); 251 sev->misc_cg = NULL; 252 } 253 254 static void sev_decommission(unsigned int handle) 255 { 256 struct sev_data_decommission decommission; 257 258 if (!handle) 259 return; 260 261 decommission.handle = handle; 262 sev_guest_decommission(&decommission, NULL); 263 } 264 265 /* 266 * Transition a page to hypervisor-owned/shared state in the RMP table. This 267 * should not fail under normal conditions, but leak the page should that 268 * happen since it will no longer be usable by the host due to RMP protections. 269 */ 270 static int kvm_rmp_make_shared(struct kvm *kvm, u64 pfn, enum pg_level level) 271 { 272 if (KVM_BUG_ON(rmp_make_shared(pfn, level), kvm)) { 273 snp_leak_pages(pfn, page_level_size(level) >> PAGE_SHIFT); 274 return -EIO; 275 } 276 277 return 0; 278 } 279 280 /* 281 * Certain page-states, such as Pre-Guest and Firmware pages (as documented 282 * in Chapter 5 of the SEV-SNP Firmware ABI under "Page States") cannot be 283 * directly transitioned back to normal/hypervisor-owned state via RMPUPDATE 284 * unless they are reclaimed first. 285 * 286 * Until they are reclaimed and subsequently transitioned via RMPUPDATE, they 287 * might not be usable by the host due to being set as immutable or still 288 * being associated with a guest ASID. 289 * 290 * Bug the VM and leak the page if reclaim fails, or if the RMP entry can't be 291 * converted back to shared, as the page is no longer usable due to RMP 292 * protections, and it's infeasible for the guest to continue on. 293 */ 294 static int snp_page_reclaim(struct kvm *kvm, u64 pfn) 295 { 296 struct sev_data_snp_page_reclaim data = {0}; 297 int fw_err, rc; 298 299 data.paddr = __sme_set(pfn << PAGE_SHIFT); 300 rc = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &fw_err); 301 if (KVM_BUG(rc, kvm, "Failed to reclaim PFN %llx, rc %d fw_err %d", pfn, rc, fw_err)) { 302 snp_leak_pages(pfn, 1); 303 return -EIO; 304 } 305 306 if (kvm_rmp_make_shared(kvm, pfn, PG_LEVEL_4K)) 307 return -EIO; 308 309 return rc; 310 } 311 312 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle) 313 { 314 struct sev_data_deactivate deactivate; 315 316 if (!handle) 317 return; 318 319 deactivate.handle = handle; 320 321 /* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */ 322 down_read(&sev_deactivate_lock); 323 sev_guest_deactivate(&deactivate, NULL); 324 up_read(&sev_deactivate_lock); 325 326 sev_decommission(handle); 327 } 328 329 /* 330 * This sets up bounce buffers/firmware pages to handle SNP Guest Request 331 * messages (e.g. attestation requests). See "SNP Guest Request" in the GHCB 332 * 2.0 specification for more details. 333 * 334 * Technically, when an SNP Guest Request is issued, the guest will provide its 335 * own request/response pages, which could in theory be passed along directly 336 * to firmware rather than using bounce pages. However, these pages would need 337 * special care: 338 * 339 * - Both pages are from shared guest memory, so they need to be protected 340 * from migration/etc. occurring while firmware reads/writes to them. At a 341 * minimum, this requires elevating the ref counts and potentially needing 342 * an explicit pinning of the memory. This places additional restrictions 343 * on what type of memory backends userspace can use for shared guest 344 * memory since there is some reliance on using refcounted pages. 345 * 346 * - The response page needs to be switched to Firmware-owned[1] state 347 * before the firmware can write to it, which can lead to potential 348 * host RMP #PFs if the guest is misbehaved and hands the host a 349 * guest page that KVM might write to for other reasons (e.g. virtio 350 * buffers/etc.). 351 * 352 * Both of these issues can be avoided completely by using separately-allocated 353 * bounce pages for both the request/response pages and passing those to 354 * firmware instead. So that's what is being set up here. 355 * 356 * Guest requests rely on message sequence numbers to ensure requests are 357 * issued to firmware in the order the guest issues them, so concurrent guest 358 * requests generally shouldn't happen. But a misbehaved guest could issue 359 * concurrent guest requests in theory, so a mutex is used to serialize 360 * access to the bounce buffers. 361 * 362 * [1] See the "Page States" section of the SEV-SNP Firmware ABI for more 363 * details on Firmware-owned pages, along with "RMP and VMPL Access Checks" 364 * in the APM for details on the related RMP restrictions. 365 */ 366 static int snp_guest_req_init(struct kvm *kvm) 367 { 368 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 369 struct page *req_page; 370 371 req_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 372 if (!req_page) 373 return -ENOMEM; 374 375 sev->guest_resp_buf = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 376 if (!sev->guest_resp_buf) { 377 __free_page(req_page); 378 return -EIO; 379 } 380 381 sev->guest_req_buf = page_address(req_page); 382 mutex_init(&sev->guest_req_mutex); 383 384 return 0; 385 } 386 387 static void snp_guest_req_cleanup(struct kvm *kvm) 388 { 389 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 390 391 if (sev->guest_resp_buf) 392 snp_free_firmware_page(sev->guest_resp_buf); 393 394 if (sev->guest_req_buf) 395 __free_page(virt_to_page(sev->guest_req_buf)); 396 397 sev->guest_req_buf = NULL; 398 sev->guest_resp_buf = NULL; 399 } 400 401 static int __sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp, 402 struct kvm_sev_init *data, 403 unsigned long vm_type) 404 { 405 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 406 struct sev_platform_init_args init_args = {0}; 407 bool es_active = vm_type != KVM_X86_SEV_VM; 408 u64 valid_vmsa_features = es_active ? sev_supported_vmsa_features : 0; 409 int ret; 410 411 if (kvm->created_vcpus) 412 return -EINVAL; 413 414 if (data->flags) 415 return -EINVAL; 416 417 if (data->vmsa_features & ~valid_vmsa_features) 418 return -EINVAL; 419 420 if (data->ghcb_version > GHCB_VERSION_MAX || (!es_active && data->ghcb_version)) 421 return -EINVAL; 422 423 if (unlikely(sev->active)) 424 return -EINVAL; 425 426 sev->active = true; 427 sev->es_active = es_active; 428 sev->vmsa_features = data->vmsa_features; 429 sev->ghcb_version = data->ghcb_version; 430 431 /* 432 * Currently KVM supports the full range of mandatory features defined 433 * by version 2 of the GHCB protocol, so default to that for SEV-ES 434 * guests created via KVM_SEV_INIT2. 435 */ 436 if (sev->es_active && !sev->ghcb_version) 437 sev->ghcb_version = GHCB_VERSION_DEFAULT; 438 439 if (vm_type == KVM_X86_SNP_VM) 440 sev->vmsa_features |= SVM_SEV_FEAT_SNP_ACTIVE; 441 442 ret = sev_asid_new(sev); 443 if (ret) 444 goto e_no_asid; 445 446 init_args.probe = false; 447 ret = sev_platform_init(&init_args); 448 if (ret) 449 goto e_free; 450 451 /* This needs to happen after SEV/SNP firmware initialization. */ 452 if (vm_type == KVM_X86_SNP_VM) { 453 ret = snp_guest_req_init(kvm); 454 if (ret) 455 goto e_free; 456 } 457 458 INIT_LIST_HEAD(&sev->regions_list); 459 INIT_LIST_HEAD(&sev->mirror_vms); 460 sev->need_init = false; 461 462 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_SEV); 463 464 return 0; 465 466 e_free: 467 argp->error = init_args.error; 468 sev_asid_free(sev); 469 sev->asid = 0; 470 e_no_asid: 471 sev->vmsa_features = 0; 472 sev->es_active = false; 473 sev->active = false; 474 return ret; 475 } 476 477 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp) 478 { 479 struct kvm_sev_init data = { 480 .vmsa_features = 0, 481 .ghcb_version = 0, 482 }; 483 unsigned long vm_type; 484 485 if (kvm->arch.vm_type != KVM_X86_DEFAULT_VM) 486 return -EINVAL; 487 488 vm_type = (argp->id == KVM_SEV_INIT ? KVM_X86_SEV_VM : KVM_X86_SEV_ES_VM); 489 490 /* 491 * KVM_SEV_ES_INIT has been deprecated by KVM_SEV_INIT2, so it will 492 * continue to only ever support the minimal GHCB protocol version. 493 */ 494 if (vm_type == KVM_X86_SEV_ES_VM) 495 data.ghcb_version = GHCB_VERSION_MIN; 496 497 return __sev_guest_init(kvm, argp, &data, vm_type); 498 } 499 500 static int sev_guest_init2(struct kvm *kvm, struct kvm_sev_cmd *argp) 501 { 502 struct kvm_sev_init data; 503 504 if (!to_kvm_sev_info(kvm)->need_init) 505 return -EINVAL; 506 507 if (kvm->arch.vm_type != KVM_X86_SEV_VM && 508 kvm->arch.vm_type != KVM_X86_SEV_ES_VM && 509 kvm->arch.vm_type != KVM_X86_SNP_VM) 510 return -EINVAL; 511 512 if (copy_from_user(&data, u64_to_user_ptr(argp->data), sizeof(data))) 513 return -EFAULT; 514 515 return __sev_guest_init(kvm, argp, &data, kvm->arch.vm_type); 516 } 517 518 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error) 519 { 520 unsigned int asid = sev_get_asid(kvm); 521 struct sev_data_activate activate; 522 int ret; 523 524 /* activate ASID on the given handle */ 525 activate.handle = handle; 526 activate.asid = asid; 527 ret = sev_guest_activate(&activate, error); 528 529 return ret; 530 } 531 532 static int __sev_issue_cmd(int fd, int id, void *data, int *error) 533 { 534 CLASS(fd, f)(fd); 535 536 if (fd_empty(f)) 537 return -EBADF; 538 539 return sev_issue_cmd_external_user(fd_file(f), id, data, error); 540 } 541 542 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error) 543 { 544 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 545 546 return __sev_issue_cmd(sev->fd, id, data, error); 547 } 548 549 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) 550 { 551 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 552 struct sev_data_launch_start start; 553 struct kvm_sev_launch_start params; 554 void *dh_blob, *session_blob; 555 int *error = &argp->error; 556 int ret; 557 558 if (!sev_guest(kvm)) 559 return -ENOTTY; 560 561 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 562 return -EFAULT; 563 564 memset(&start, 0, sizeof(start)); 565 566 dh_blob = NULL; 567 if (params.dh_uaddr) { 568 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len); 569 if (IS_ERR(dh_blob)) 570 return PTR_ERR(dh_blob); 571 572 start.dh_cert_address = __sme_set(__pa(dh_blob)); 573 start.dh_cert_len = params.dh_len; 574 } 575 576 session_blob = NULL; 577 if (params.session_uaddr) { 578 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len); 579 if (IS_ERR(session_blob)) { 580 ret = PTR_ERR(session_blob); 581 goto e_free_dh; 582 } 583 584 start.session_address = __sme_set(__pa(session_blob)); 585 start.session_len = params.session_len; 586 } 587 588 start.handle = params.handle; 589 start.policy = params.policy; 590 591 /* create memory encryption context */ 592 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, &start, error); 593 if (ret) 594 goto e_free_session; 595 596 /* Bind ASID to this guest */ 597 ret = sev_bind_asid(kvm, start.handle, error); 598 if (ret) { 599 sev_decommission(start.handle); 600 goto e_free_session; 601 } 602 603 /* return handle to userspace */ 604 params.handle = start.handle; 605 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params))) { 606 sev_unbind_asid(kvm, start.handle); 607 ret = -EFAULT; 608 goto e_free_session; 609 } 610 611 sev->handle = start.handle; 612 sev->fd = argp->sev_fd; 613 614 e_free_session: 615 kfree(session_blob); 616 e_free_dh: 617 kfree(dh_blob); 618 return ret; 619 } 620 621 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr, 622 unsigned long ulen, unsigned long *n, 623 unsigned int flags) 624 { 625 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 626 unsigned long npages, size; 627 int npinned; 628 unsigned long locked, lock_limit; 629 struct page **pages; 630 unsigned long first, last; 631 int ret; 632 633 lockdep_assert_held(&kvm->lock); 634 635 if (ulen == 0 || uaddr + ulen < uaddr) 636 return ERR_PTR(-EINVAL); 637 638 /* Calculate number of pages. */ 639 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT; 640 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT; 641 npages = (last - first + 1); 642 643 locked = sev->pages_locked + npages; 644 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; 645 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) { 646 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit); 647 return ERR_PTR(-ENOMEM); 648 } 649 650 if (WARN_ON_ONCE(npages > INT_MAX)) 651 return ERR_PTR(-EINVAL); 652 653 /* Avoid using vmalloc for smaller buffers. */ 654 size = npages * sizeof(struct page *); 655 if (size > PAGE_SIZE) 656 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT); 657 else 658 pages = kmalloc(size, GFP_KERNEL_ACCOUNT); 659 660 if (!pages) 661 return ERR_PTR(-ENOMEM); 662 663 /* Pin the user virtual address. */ 664 npinned = pin_user_pages_fast(uaddr, npages, flags, pages); 665 if (npinned != npages) { 666 pr_err("SEV: Failure locking %lu pages.\n", npages); 667 ret = -ENOMEM; 668 goto err; 669 } 670 671 *n = npages; 672 sev->pages_locked = locked; 673 674 return pages; 675 676 err: 677 if (npinned > 0) 678 unpin_user_pages(pages, npinned); 679 680 kvfree(pages); 681 return ERR_PTR(ret); 682 } 683 684 static void sev_unpin_memory(struct kvm *kvm, struct page **pages, 685 unsigned long npages) 686 { 687 unpin_user_pages(pages, npages); 688 kvfree(pages); 689 to_kvm_sev_info(kvm)->pages_locked -= npages; 690 } 691 692 static void sev_clflush_pages(struct page *pages[], unsigned long npages) 693 { 694 uint8_t *page_virtual; 695 unsigned long i; 696 697 if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 || 698 pages == NULL) 699 return; 700 701 for (i = 0; i < npages; i++) { 702 page_virtual = kmap_local_page(pages[i]); 703 clflush_cache_range(page_virtual, PAGE_SIZE); 704 kunmap_local(page_virtual); 705 cond_resched(); 706 } 707 } 708 709 static unsigned long get_num_contig_pages(unsigned long idx, 710 struct page **inpages, unsigned long npages) 711 { 712 unsigned long paddr, next_paddr; 713 unsigned long i = idx + 1, pages = 1; 714 715 /* find the number of contiguous pages starting from idx */ 716 paddr = __sme_page_pa(inpages[idx]); 717 while (i < npages) { 718 next_paddr = __sme_page_pa(inpages[i++]); 719 if ((paddr + PAGE_SIZE) == next_paddr) { 720 pages++; 721 paddr = next_paddr; 722 continue; 723 } 724 break; 725 } 726 727 return pages; 728 } 729 730 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp) 731 { 732 unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i; 733 struct kvm_sev_launch_update_data params; 734 struct sev_data_launch_update_data data; 735 struct page **inpages; 736 int ret; 737 738 if (!sev_guest(kvm)) 739 return -ENOTTY; 740 741 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 742 return -EFAULT; 743 744 vaddr = params.uaddr; 745 size = params.len; 746 vaddr_end = vaddr + size; 747 748 /* Lock the user memory. */ 749 inpages = sev_pin_memory(kvm, vaddr, size, &npages, FOLL_WRITE); 750 if (IS_ERR(inpages)) 751 return PTR_ERR(inpages); 752 753 /* 754 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in 755 * place; the cache may contain the data that was written unencrypted. 756 */ 757 sev_clflush_pages(inpages, npages); 758 759 data.reserved = 0; 760 data.handle = to_kvm_sev_info(kvm)->handle; 761 762 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) { 763 int offset, len; 764 765 /* 766 * If the user buffer is not page-aligned, calculate the offset 767 * within the page. 768 */ 769 offset = vaddr & (PAGE_SIZE - 1); 770 771 /* Calculate the number of pages that can be encrypted in one go. */ 772 pages = get_num_contig_pages(i, inpages, npages); 773 774 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size); 775 776 data.len = len; 777 data.address = __sme_page_pa(inpages[i]) + offset; 778 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, &data, &argp->error); 779 if (ret) 780 goto e_unpin; 781 782 size -= len; 783 next_vaddr = vaddr + len; 784 } 785 786 e_unpin: 787 /* content of memory is updated, mark pages dirty */ 788 for (i = 0; i < npages; i++) { 789 set_page_dirty_lock(inpages[i]); 790 mark_page_accessed(inpages[i]); 791 } 792 /* unlock the user pages */ 793 sev_unpin_memory(kvm, inpages, npages); 794 return ret; 795 } 796 797 static int sev_es_sync_vmsa(struct vcpu_svm *svm) 798 { 799 struct kvm_vcpu *vcpu = &svm->vcpu; 800 struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm); 801 struct sev_es_save_area *save = svm->sev_es.vmsa; 802 struct xregs_state *xsave; 803 const u8 *s; 804 u8 *d; 805 int i; 806 807 /* Check some debug related fields before encrypting the VMSA */ 808 if (svm->vcpu.guest_debug || (svm->vmcb->save.dr7 & ~DR7_FIXED_1)) 809 return -EINVAL; 810 811 /* 812 * SEV-ES will use a VMSA that is pointed to by the VMCB, not 813 * the traditional VMSA that is part of the VMCB. Copy the 814 * traditional VMSA as it has been built so far (in prep 815 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state. 816 */ 817 memcpy(save, &svm->vmcb->save, sizeof(svm->vmcb->save)); 818 819 /* Sync registgers */ 820 save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX]; 821 save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX]; 822 save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX]; 823 save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX]; 824 save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP]; 825 save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP]; 826 save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI]; 827 save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI]; 828 #ifdef CONFIG_X86_64 829 save->r8 = svm->vcpu.arch.regs[VCPU_REGS_R8]; 830 save->r9 = svm->vcpu.arch.regs[VCPU_REGS_R9]; 831 save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10]; 832 save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11]; 833 save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12]; 834 save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13]; 835 save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14]; 836 save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15]; 837 #endif 838 save->rip = svm->vcpu.arch.regs[VCPU_REGS_RIP]; 839 840 /* Sync some non-GPR registers before encrypting */ 841 save->xcr0 = svm->vcpu.arch.xcr0; 842 save->pkru = svm->vcpu.arch.pkru; 843 save->xss = svm->vcpu.arch.ia32_xss; 844 save->dr6 = svm->vcpu.arch.dr6; 845 846 save->sev_features = sev->vmsa_features; 847 848 /* 849 * Skip FPU and AVX setup with KVM_SEV_ES_INIT to avoid 850 * breaking older measurements. 851 */ 852 if (vcpu->kvm->arch.vm_type != KVM_X86_DEFAULT_VM) { 853 xsave = &vcpu->arch.guest_fpu.fpstate->regs.xsave; 854 save->x87_dp = xsave->i387.rdp; 855 save->mxcsr = xsave->i387.mxcsr; 856 save->x87_ftw = xsave->i387.twd; 857 save->x87_fsw = xsave->i387.swd; 858 save->x87_fcw = xsave->i387.cwd; 859 save->x87_fop = xsave->i387.fop; 860 save->x87_ds = 0; 861 save->x87_cs = 0; 862 save->x87_rip = xsave->i387.rip; 863 864 for (i = 0; i < 8; i++) { 865 /* 866 * The format of the x87 save area is undocumented and 867 * definitely not what you would expect. It consists of 868 * an 8*8 bytes area with bytes 0-7, and an 8*2 bytes 869 * area with bytes 8-9 of each register. 870 */ 871 d = save->fpreg_x87 + i * 8; 872 s = ((u8 *)xsave->i387.st_space) + i * 16; 873 memcpy(d, s, 8); 874 save->fpreg_x87[64 + i * 2] = s[8]; 875 save->fpreg_x87[64 + i * 2 + 1] = s[9]; 876 } 877 memcpy(save->fpreg_xmm, xsave->i387.xmm_space, 256); 878 879 s = get_xsave_addr(xsave, XFEATURE_YMM); 880 if (s) 881 memcpy(save->fpreg_ymm, s, 256); 882 else 883 memset(save->fpreg_ymm, 0, 256); 884 } 885 886 pr_debug("Virtual Machine Save Area (VMSA):\n"); 887 print_hex_dump_debug("", DUMP_PREFIX_NONE, 16, 1, save, sizeof(*save), false); 888 889 return 0; 890 } 891 892 static int __sev_launch_update_vmsa(struct kvm *kvm, struct kvm_vcpu *vcpu, 893 int *error) 894 { 895 struct sev_data_launch_update_vmsa vmsa; 896 struct vcpu_svm *svm = to_svm(vcpu); 897 int ret; 898 899 if (vcpu->guest_debug) { 900 pr_warn_once("KVM_SET_GUEST_DEBUG for SEV-ES guest is not supported"); 901 return -EINVAL; 902 } 903 904 /* Perform some pre-encryption checks against the VMSA */ 905 ret = sev_es_sync_vmsa(svm); 906 if (ret) 907 return ret; 908 909 /* 910 * The LAUNCH_UPDATE_VMSA command will perform in-place encryption of 911 * the VMSA memory content (i.e it will write the same memory region 912 * with the guest's key), so invalidate it first. 913 */ 914 clflush_cache_range(svm->sev_es.vmsa, PAGE_SIZE); 915 916 vmsa.reserved = 0; 917 vmsa.handle = to_kvm_sev_info(kvm)->handle; 918 vmsa.address = __sme_pa(svm->sev_es.vmsa); 919 vmsa.len = PAGE_SIZE; 920 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, &vmsa, error); 921 if (ret) 922 return ret; 923 924 /* 925 * SEV-ES guests maintain an encrypted version of their FPU 926 * state which is restored and saved on VMRUN and VMEXIT. 927 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't 928 * do xsave/xrstor on it. 929 */ 930 fpstate_set_confidential(&vcpu->arch.guest_fpu); 931 vcpu->arch.guest_state_protected = true; 932 933 /* 934 * SEV-ES guest mandates LBR Virtualization to be _always_ ON. Enable it 935 * only after setting guest_state_protected because KVM_SET_MSRS allows 936 * dynamic toggling of LBRV (for performance reason) on write access to 937 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set. 938 */ 939 svm_enable_lbrv(vcpu); 940 return 0; 941 } 942 943 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp) 944 { 945 struct kvm_vcpu *vcpu; 946 unsigned long i; 947 int ret; 948 949 if (!sev_es_guest(kvm)) 950 return -ENOTTY; 951 952 kvm_for_each_vcpu(i, vcpu, kvm) { 953 ret = mutex_lock_killable(&vcpu->mutex); 954 if (ret) 955 return ret; 956 957 ret = __sev_launch_update_vmsa(kvm, vcpu, &argp->error); 958 959 mutex_unlock(&vcpu->mutex); 960 if (ret) 961 return ret; 962 } 963 964 return 0; 965 } 966 967 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp) 968 { 969 void __user *measure = u64_to_user_ptr(argp->data); 970 struct sev_data_launch_measure data; 971 struct kvm_sev_launch_measure params; 972 void __user *p = NULL; 973 void *blob = NULL; 974 int ret; 975 976 if (!sev_guest(kvm)) 977 return -ENOTTY; 978 979 if (copy_from_user(¶ms, measure, sizeof(params))) 980 return -EFAULT; 981 982 memset(&data, 0, sizeof(data)); 983 984 /* User wants to query the blob length */ 985 if (!params.len) 986 goto cmd; 987 988 p = u64_to_user_ptr(params.uaddr); 989 if (p) { 990 if (params.len > SEV_FW_BLOB_MAX_SIZE) 991 return -EINVAL; 992 993 blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT); 994 if (!blob) 995 return -ENOMEM; 996 997 data.address = __psp_pa(blob); 998 data.len = params.len; 999 } 1000 1001 cmd: 1002 data.handle = to_kvm_sev_info(kvm)->handle; 1003 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error); 1004 1005 /* 1006 * If we query the session length, FW responded with expected data. 1007 */ 1008 if (!params.len) 1009 goto done; 1010 1011 if (ret) 1012 goto e_free_blob; 1013 1014 if (blob) { 1015 if (copy_to_user(p, blob, params.len)) 1016 ret = -EFAULT; 1017 } 1018 1019 done: 1020 params.len = data.len; 1021 if (copy_to_user(measure, ¶ms, sizeof(params))) 1022 ret = -EFAULT; 1023 e_free_blob: 1024 kfree(blob); 1025 return ret; 1026 } 1027 1028 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) 1029 { 1030 struct sev_data_launch_finish data; 1031 1032 if (!sev_guest(kvm)) 1033 return -ENOTTY; 1034 1035 data.handle = to_kvm_sev_info(kvm)->handle; 1036 return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error); 1037 } 1038 1039 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp) 1040 { 1041 struct kvm_sev_guest_status params; 1042 struct sev_data_guest_status data; 1043 int ret; 1044 1045 if (!sev_guest(kvm)) 1046 return -ENOTTY; 1047 1048 memset(&data, 0, sizeof(data)); 1049 1050 data.handle = to_kvm_sev_info(kvm)->handle; 1051 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error); 1052 if (ret) 1053 return ret; 1054 1055 params.policy = data.policy; 1056 params.state = data.state; 1057 params.handle = data.handle; 1058 1059 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params))) 1060 ret = -EFAULT; 1061 1062 return ret; 1063 } 1064 1065 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src, 1066 unsigned long dst, int size, 1067 int *error, bool enc) 1068 { 1069 struct sev_data_dbg data; 1070 1071 data.reserved = 0; 1072 data.handle = to_kvm_sev_info(kvm)->handle; 1073 data.dst_addr = dst; 1074 data.src_addr = src; 1075 data.len = size; 1076 1077 return sev_issue_cmd(kvm, 1078 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT, 1079 &data, error); 1080 } 1081 1082 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr, 1083 unsigned long dst_paddr, int sz, int *err) 1084 { 1085 int offset; 1086 1087 /* 1088 * Its safe to read more than we are asked, caller should ensure that 1089 * destination has enough space. 1090 */ 1091 offset = src_paddr & 15; 1092 src_paddr = round_down(src_paddr, 16); 1093 sz = round_up(sz + offset, 16); 1094 1095 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false); 1096 } 1097 1098 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr, 1099 void __user *dst_uaddr, 1100 unsigned long dst_paddr, 1101 int size, int *err) 1102 { 1103 struct page *tpage = NULL; 1104 int ret, offset; 1105 1106 /* if inputs are not 16-byte then use intermediate buffer */ 1107 if (!IS_ALIGNED(dst_paddr, 16) || 1108 !IS_ALIGNED(paddr, 16) || 1109 !IS_ALIGNED(size, 16)) { 1110 tpage = (void *)alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 1111 if (!tpage) 1112 return -ENOMEM; 1113 1114 dst_paddr = __sme_page_pa(tpage); 1115 } 1116 1117 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err); 1118 if (ret) 1119 goto e_free; 1120 1121 if (tpage) { 1122 offset = paddr & 15; 1123 if (copy_to_user(dst_uaddr, page_address(tpage) + offset, size)) 1124 ret = -EFAULT; 1125 } 1126 1127 e_free: 1128 if (tpage) 1129 __free_page(tpage); 1130 1131 return ret; 1132 } 1133 1134 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr, 1135 void __user *vaddr, 1136 unsigned long dst_paddr, 1137 void __user *dst_vaddr, 1138 int size, int *error) 1139 { 1140 struct page *src_tpage = NULL; 1141 struct page *dst_tpage = NULL; 1142 int ret, len = size; 1143 1144 /* If source buffer is not aligned then use an intermediate buffer */ 1145 if (!IS_ALIGNED((unsigned long)vaddr, 16)) { 1146 src_tpage = alloc_page(GFP_KERNEL_ACCOUNT); 1147 if (!src_tpage) 1148 return -ENOMEM; 1149 1150 if (copy_from_user(page_address(src_tpage), vaddr, size)) { 1151 __free_page(src_tpage); 1152 return -EFAULT; 1153 } 1154 1155 paddr = __sme_page_pa(src_tpage); 1156 } 1157 1158 /* 1159 * If destination buffer or length is not aligned then do read-modify-write: 1160 * - decrypt destination in an intermediate buffer 1161 * - copy the source buffer in an intermediate buffer 1162 * - use the intermediate buffer as source buffer 1163 */ 1164 if (!IS_ALIGNED((unsigned long)dst_vaddr, 16) || !IS_ALIGNED(size, 16)) { 1165 int dst_offset; 1166 1167 dst_tpage = alloc_page(GFP_KERNEL_ACCOUNT); 1168 if (!dst_tpage) { 1169 ret = -ENOMEM; 1170 goto e_free; 1171 } 1172 1173 ret = __sev_dbg_decrypt(kvm, dst_paddr, 1174 __sme_page_pa(dst_tpage), size, error); 1175 if (ret) 1176 goto e_free; 1177 1178 /* 1179 * If source is kernel buffer then use memcpy() otherwise 1180 * copy_from_user(). 1181 */ 1182 dst_offset = dst_paddr & 15; 1183 1184 if (src_tpage) 1185 memcpy(page_address(dst_tpage) + dst_offset, 1186 page_address(src_tpage), size); 1187 else { 1188 if (copy_from_user(page_address(dst_tpage) + dst_offset, 1189 vaddr, size)) { 1190 ret = -EFAULT; 1191 goto e_free; 1192 } 1193 } 1194 1195 paddr = __sme_page_pa(dst_tpage); 1196 dst_paddr = round_down(dst_paddr, 16); 1197 len = round_up(size, 16); 1198 } 1199 1200 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true); 1201 1202 e_free: 1203 if (src_tpage) 1204 __free_page(src_tpage); 1205 if (dst_tpage) 1206 __free_page(dst_tpage); 1207 return ret; 1208 } 1209 1210 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec) 1211 { 1212 unsigned long vaddr, vaddr_end, next_vaddr; 1213 unsigned long dst_vaddr; 1214 struct page **src_p, **dst_p; 1215 struct kvm_sev_dbg debug; 1216 unsigned long n; 1217 unsigned int size; 1218 int ret; 1219 1220 if (!sev_guest(kvm)) 1221 return -ENOTTY; 1222 1223 if (copy_from_user(&debug, u64_to_user_ptr(argp->data), sizeof(debug))) 1224 return -EFAULT; 1225 1226 if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr) 1227 return -EINVAL; 1228 if (!debug.dst_uaddr) 1229 return -EINVAL; 1230 1231 vaddr = debug.src_uaddr; 1232 size = debug.len; 1233 vaddr_end = vaddr + size; 1234 dst_vaddr = debug.dst_uaddr; 1235 1236 for (; vaddr < vaddr_end; vaddr = next_vaddr) { 1237 int len, s_off, d_off; 1238 1239 /* lock userspace source and destination page */ 1240 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0); 1241 if (IS_ERR(src_p)) 1242 return PTR_ERR(src_p); 1243 1244 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, FOLL_WRITE); 1245 if (IS_ERR(dst_p)) { 1246 sev_unpin_memory(kvm, src_p, n); 1247 return PTR_ERR(dst_p); 1248 } 1249 1250 /* 1251 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify 1252 * the pages; flush the destination too so that future accesses do not 1253 * see stale data. 1254 */ 1255 sev_clflush_pages(src_p, 1); 1256 sev_clflush_pages(dst_p, 1); 1257 1258 /* 1259 * Since user buffer may not be page aligned, calculate the 1260 * offset within the page. 1261 */ 1262 s_off = vaddr & ~PAGE_MASK; 1263 d_off = dst_vaddr & ~PAGE_MASK; 1264 len = min_t(size_t, (PAGE_SIZE - s_off), size); 1265 1266 if (dec) 1267 ret = __sev_dbg_decrypt_user(kvm, 1268 __sme_page_pa(src_p[0]) + s_off, 1269 (void __user *)dst_vaddr, 1270 __sme_page_pa(dst_p[0]) + d_off, 1271 len, &argp->error); 1272 else 1273 ret = __sev_dbg_encrypt_user(kvm, 1274 __sme_page_pa(src_p[0]) + s_off, 1275 (void __user *)vaddr, 1276 __sme_page_pa(dst_p[0]) + d_off, 1277 (void __user *)dst_vaddr, 1278 len, &argp->error); 1279 1280 sev_unpin_memory(kvm, src_p, n); 1281 sev_unpin_memory(kvm, dst_p, n); 1282 1283 if (ret) 1284 goto err; 1285 1286 next_vaddr = vaddr + len; 1287 dst_vaddr = dst_vaddr + len; 1288 size -= len; 1289 } 1290 err: 1291 return ret; 1292 } 1293 1294 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp) 1295 { 1296 struct sev_data_launch_secret data; 1297 struct kvm_sev_launch_secret params; 1298 struct page **pages; 1299 void *blob, *hdr; 1300 unsigned long n, i; 1301 int ret, offset; 1302 1303 if (!sev_guest(kvm)) 1304 return -ENOTTY; 1305 1306 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 1307 return -EFAULT; 1308 1309 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, FOLL_WRITE); 1310 if (IS_ERR(pages)) 1311 return PTR_ERR(pages); 1312 1313 /* 1314 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in 1315 * place; the cache may contain the data that was written unencrypted. 1316 */ 1317 sev_clflush_pages(pages, n); 1318 1319 /* 1320 * The secret must be copied into contiguous memory region, lets verify 1321 * that userspace memory pages are contiguous before we issue command. 1322 */ 1323 if (get_num_contig_pages(0, pages, n) != n) { 1324 ret = -EINVAL; 1325 goto e_unpin_memory; 1326 } 1327 1328 memset(&data, 0, sizeof(data)); 1329 1330 offset = params.guest_uaddr & (PAGE_SIZE - 1); 1331 data.guest_address = __sme_page_pa(pages[0]) + offset; 1332 data.guest_len = params.guest_len; 1333 1334 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len); 1335 if (IS_ERR(blob)) { 1336 ret = PTR_ERR(blob); 1337 goto e_unpin_memory; 1338 } 1339 1340 data.trans_address = __psp_pa(blob); 1341 data.trans_len = params.trans_len; 1342 1343 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len); 1344 if (IS_ERR(hdr)) { 1345 ret = PTR_ERR(hdr); 1346 goto e_free_blob; 1347 } 1348 data.hdr_address = __psp_pa(hdr); 1349 data.hdr_len = params.hdr_len; 1350 1351 data.handle = to_kvm_sev_info(kvm)->handle; 1352 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error); 1353 1354 kfree(hdr); 1355 1356 e_free_blob: 1357 kfree(blob); 1358 e_unpin_memory: 1359 /* content of memory is updated, mark pages dirty */ 1360 for (i = 0; i < n; i++) { 1361 set_page_dirty_lock(pages[i]); 1362 mark_page_accessed(pages[i]); 1363 } 1364 sev_unpin_memory(kvm, pages, n); 1365 return ret; 1366 } 1367 1368 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp) 1369 { 1370 void __user *report = u64_to_user_ptr(argp->data); 1371 struct sev_data_attestation_report data; 1372 struct kvm_sev_attestation_report params; 1373 void __user *p; 1374 void *blob = NULL; 1375 int ret; 1376 1377 if (!sev_guest(kvm)) 1378 return -ENOTTY; 1379 1380 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 1381 return -EFAULT; 1382 1383 memset(&data, 0, sizeof(data)); 1384 1385 /* User wants to query the blob length */ 1386 if (!params.len) 1387 goto cmd; 1388 1389 p = u64_to_user_ptr(params.uaddr); 1390 if (p) { 1391 if (params.len > SEV_FW_BLOB_MAX_SIZE) 1392 return -EINVAL; 1393 1394 blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT); 1395 if (!blob) 1396 return -ENOMEM; 1397 1398 data.address = __psp_pa(blob); 1399 data.len = params.len; 1400 memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce)); 1401 } 1402 cmd: 1403 data.handle = to_kvm_sev_info(kvm)->handle; 1404 ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error); 1405 /* 1406 * If we query the session length, FW responded with expected data. 1407 */ 1408 if (!params.len) 1409 goto done; 1410 1411 if (ret) 1412 goto e_free_blob; 1413 1414 if (blob) { 1415 if (copy_to_user(p, blob, params.len)) 1416 ret = -EFAULT; 1417 } 1418 1419 done: 1420 params.len = data.len; 1421 if (copy_to_user(report, ¶ms, sizeof(params))) 1422 ret = -EFAULT; 1423 e_free_blob: 1424 kfree(blob); 1425 return ret; 1426 } 1427 1428 /* Userspace wants to query session length. */ 1429 static int 1430 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp, 1431 struct kvm_sev_send_start *params) 1432 { 1433 struct sev_data_send_start data; 1434 int ret; 1435 1436 memset(&data, 0, sizeof(data)); 1437 data.handle = to_kvm_sev_info(kvm)->handle; 1438 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error); 1439 1440 params->session_len = data.session_len; 1441 if (copy_to_user(u64_to_user_ptr(argp->data), params, 1442 sizeof(struct kvm_sev_send_start))) 1443 ret = -EFAULT; 1444 1445 return ret; 1446 } 1447 1448 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp) 1449 { 1450 struct sev_data_send_start data; 1451 struct kvm_sev_send_start params; 1452 void *amd_certs, *session_data; 1453 void *pdh_cert, *plat_certs; 1454 int ret; 1455 1456 if (!sev_guest(kvm)) 1457 return -ENOTTY; 1458 1459 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), 1460 sizeof(struct kvm_sev_send_start))) 1461 return -EFAULT; 1462 1463 /* if session_len is zero, userspace wants to query the session length */ 1464 if (!params.session_len) 1465 return __sev_send_start_query_session_length(kvm, argp, 1466 ¶ms); 1467 1468 /* some sanity checks */ 1469 if (!params.pdh_cert_uaddr || !params.pdh_cert_len || 1470 !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE) 1471 return -EINVAL; 1472 1473 /* allocate the memory to hold the session data blob */ 1474 session_data = kzalloc(params.session_len, GFP_KERNEL_ACCOUNT); 1475 if (!session_data) 1476 return -ENOMEM; 1477 1478 /* copy the certificate blobs from userspace */ 1479 pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr, 1480 params.pdh_cert_len); 1481 if (IS_ERR(pdh_cert)) { 1482 ret = PTR_ERR(pdh_cert); 1483 goto e_free_session; 1484 } 1485 1486 plat_certs = psp_copy_user_blob(params.plat_certs_uaddr, 1487 params.plat_certs_len); 1488 if (IS_ERR(plat_certs)) { 1489 ret = PTR_ERR(plat_certs); 1490 goto e_free_pdh; 1491 } 1492 1493 amd_certs = psp_copy_user_blob(params.amd_certs_uaddr, 1494 params.amd_certs_len); 1495 if (IS_ERR(amd_certs)) { 1496 ret = PTR_ERR(amd_certs); 1497 goto e_free_plat_cert; 1498 } 1499 1500 /* populate the FW SEND_START field with system physical address */ 1501 memset(&data, 0, sizeof(data)); 1502 data.pdh_cert_address = __psp_pa(pdh_cert); 1503 data.pdh_cert_len = params.pdh_cert_len; 1504 data.plat_certs_address = __psp_pa(plat_certs); 1505 data.plat_certs_len = params.plat_certs_len; 1506 data.amd_certs_address = __psp_pa(amd_certs); 1507 data.amd_certs_len = params.amd_certs_len; 1508 data.session_address = __psp_pa(session_data); 1509 data.session_len = params.session_len; 1510 data.handle = to_kvm_sev_info(kvm)->handle; 1511 1512 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error); 1513 1514 if (!ret && copy_to_user(u64_to_user_ptr(params.session_uaddr), 1515 session_data, params.session_len)) { 1516 ret = -EFAULT; 1517 goto e_free_amd_cert; 1518 } 1519 1520 params.policy = data.policy; 1521 params.session_len = data.session_len; 1522 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, 1523 sizeof(struct kvm_sev_send_start))) 1524 ret = -EFAULT; 1525 1526 e_free_amd_cert: 1527 kfree(amd_certs); 1528 e_free_plat_cert: 1529 kfree(plat_certs); 1530 e_free_pdh: 1531 kfree(pdh_cert); 1532 e_free_session: 1533 kfree(session_data); 1534 return ret; 1535 } 1536 1537 /* Userspace wants to query either header or trans length. */ 1538 static int 1539 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp, 1540 struct kvm_sev_send_update_data *params) 1541 { 1542 struct sev_data_send_update_data data; 1543 int ret; 1544 1545 memset(&data, 0, sizeof(data)); 1546 data.handle = to_kvm_sev_info(kvm)->handle; 1547 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error); 1548 1549 params->hdr_len = data.hdr_len; 1550 params->trans_len = data.trans_len; 1551 1552 if (copy_to_user(u64_to_user_ptr(argp->data), params, 1553 sizeof(struct kvm_sev_send_update_data))) 1554 ret = -EFAULT; 1555 1556 return ret; 1557 } 1558 1559 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp) 1560 { 1561 struct sev_data_send_update_data data; 1562 struct kvm_sev_send_update_data params; 1563 void *hdr, *trans_data; 1564 struct page **guest_page; 1565 unsigned long n; 1566 int ret, offset; 1567 1568 if (!sev_guest(kvm)) 1569 return -ENOTTY; 1570 1571 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), 1572 sizeof(struct kvm_sev_send_update_data))) 1573 return -EFAULT; 1574 1575 /* userspace wants to query either header or trans length */ 1576 if (!params.trans_len || !params.hdr_len) 1577 return __sev_send_update_data_query_lengths(kvm, argp, ¶ms); 1578 1579 if (!params.trans_uaddr || !params.guest_uaddr || 1580 !params.guest_len || !params.hdr_uaddr) 1581 return -EINVAL; 1582 1583 /* Check if we are crossing the page boundary */ 1584 offset = params.guest_uaddr & (PAGE_SIZE - 1); 1585 if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE) 1586 return -EINVAL; 1587 1588 /* Pin guest memory */ 1589 guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK, 1590 PAGE_SIZE, &n, 0); 1591 if (IS_ERR(guest_page)) 1592 return PTR_ERR(guest_page); 1593 1594 /* allocate memory for header and transport buffer */ 1595 ret = -ENOMEM; 1596 hdr = kzalloc(params.hdr_len, GFP_KERNEL_ACCOUNT); 1597 if (!hdr) 1598 goto e_unpin; 1599 1600 trans_data = kzalloc(params.trans_len, GFP_KERNEL_ACCOUNT); 1601 if (!trans_data) 1602 goto e_free_hdr; 1603 1604 memset(&data, 0, sizeof(data)); 1605 data.hdr_address = __psp_pa(hdr); 1606 data.hdr_len = params.hdr_len; 1607 data.trans_address = __psp_pa(trans_data); 1608 data.trans_len = params.trans_len; 1609 1610 /* The SEND_UPDATE_DATA command requires C-bit to be always set. */ 1611 data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset; 1612 data.guest_address |= sev_me_mask; 1613 data.guest_len = params.guest_len; 1614 data.handle = to_kvm_sev_info(kvm)->handle; 1615 1616 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error); 1617 1618 if (ret) 1619 goto e_free_trans_data; 1620 1621 /* copy transport buffer to user space */ 1622 if (copy_to_user(u64_to_user_ptr(params.trans_uaddr), 1623 trans_data, params.trans_len)) { 1624 ret = -EFAULT; 1625 goto e_free_trans_data; 1626 } 1627 1628 /* Copy packet header to userspace. */ 1629 if (copy_to_user(u64_to_user_ptr(params.hdr_uaddr), hdr, 1630 params.hdr_len)) 1631 ret = -EFAULT; 1632 1633 e_free_trans_data: 1634 kfree(trans_data); 1635 e_free_hdr: 1636 kfree(hdr); 1637 e_unpin: 1638 sev_unpin_memory(kvm, guest_page, n); 1639 1640 return ret; 1641 } 1642 1643 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) 1644 { 1645 struct sev_data_send_finish data; 1646 1647 if (!sev_guest(kvm)) 1648 return -ENOTTY; 1649 1650 data.handle = to_kvm_sev_info(kvm)->handle; 1651 return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error); 1652 } 1653 1654 static int sev_send_cancel(struct kvm *kvm, struct kvm_sev_cmd *argp) 1655 { 1656 struct sev_data_send_cancel data; 1657 1658 if (!sev_guest(kvm)) 1659 return -ENOTTY; 1660 1661 data.handle = to_kvm_sev_info(kvm)->handle; 1662 return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error); 1663 } 1664 1665 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp) 1666 { 1667 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 1668 struct sev_data_receive_start start; 1669 struct kvm_sev_receive_start params; 1670 int *error = &argp->error; 1671 void *session_data; 1672 void *pdh_data; 1673 int ret; 1674 1675 if (!sev_guest(kvm)) 1676 return -ENOTTY; 1677 1678 /* Get parameter from the userspace */ 1679 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), 1680 sizeof(struct kvm_sev_receive_start))) 1681 return -EFAULT; 1682 1683 /* some sanity checks */ 1684 if (!params.pdh_uaddr || !params.pdh_len || 1685 !params.session_uaddr || !params.session_len) 1686 return -EINVAL; 1687 1688 pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len); 1689 if (IS_ERR(pdh_data)) 1690 return PTR_ERR(pdh_data); 1691 1692 session_data = psp_copy_user_blob(params.session_uaddr, 1693 params.session_len); 1694 if (IS_ERR(session_data)) { 1695 ret = PTR_ERR(session_data); 1696 goto e_free_pdh; 1697 } 1698 1699 memset(&start, 0, sizeof(start)); 1700 start.handle = params.handle; 1701 start.policy = params.policy; 1702 start.pdh_cert_address = __psp_pa(pdh_data); 1703 start.pdh_cert_len = params.pdh_len; 1704 start.session_address = __psp_pa(session_data); 1705 start.session_len = params.session_len; 1706 1707 /* create memory encryption context */ 1708 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start, 1709 error); 1710 if (ret) 1711 goto e_free_session; 1712 1713 /* Bind ASID to this guest */ 1714 ret = sev_bind_asid(kvm, start.handle, error); 1715 if (ret) { 1716 sev_decommission(start.handle); 1717 goto e_free_session; 1718 } 1719 1720 params.handle = start.handle; 1721 if (copy_to_user(u64_to_user_ptr(argp->data), 1722 ¶ms, sizeof(struct kvm_sev_receive_start))) { 1723 ret = -EFAULT; 1724 sev_unbind_asid(kvm, start.handle); 1725 goto e_free_session; 1726 } 1727 1728 sev->handle = start.handle; 1729 sev->fd = argp->sev_fd; 1730 1731 e_free_session: 1732 kfree(session_data); 1733 e_free_pdh: 1734 kfree(pdh_data); 1735 1736 return ret; 1737 } 1738 1739 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp) 1740 { 1741 struct kvm_sev_receive_update_data params; 1742 struct sev_data_receive_update_data data; 1743 void *hdr = NULL, *trans = NULL; 1744 struct page **guest_page; 1745 unsigned long n; 1746 int ret, offset; 1747 1748 if (!sev_guest(kvm)) 1749 return -EINVAL; 1750 1751 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), 1752 sizeof(struct kvm_sev_receive_update_data))) 1753 return -EFAULT; 1754 1755 if (!params.hdr_uaddr || !params.hdr_len || 1756 !params.guest_uaddr || !params.guest_len || 1757 !params.trans_uaddr || !params.trans_len) 1758 return -EINVAL; 1759 1760 /* Check if we are crossing the page boundary */ 1761 offset = params.guest_uaddr & (PAGE_SIZE - 1); 1762 if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE) 1763 return -EINVAL; 1764 1765 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len); 1766 if (IS_ERR(hdr)) 1767 return PTR_ERR(hdr); 1768 1769 trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len); 1770 if (IS_ERR(trans)) { 1771 ret = PTR_ERR(trans); 1772 goto e_free_hdr; 1773 } 1774 1775 memset(&data, 0, sizeof(data)); 1776 data.hdr_address = __psp_pa(hdr); 1777 data.hdr_len = params.hdr_len; 1778 data.trans_address = __psp_pa(trans); 1779 data.trans_len = params.trans_len; 1780 1781 /* Pin guest memory */ 1782 guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK, 1783 PAGE_SIZE, &n, FOLL_WRITE); 1784 if (IS_ERR(guest_page)) { 1785 ret = PTR_ERR(guest_page); 1786 goto e_free_trans; 1787 } 1788 1789 /* 1790 * Flush (on non-coherent CPUs) before RECEIVE_UPDATE_DATA, the PSP 1791 * encrypts the written data with the guest's key, and the cache may 1792 * contain dirty, unencrypted data. 1793 */ 1794 sev_clflush_pages(guest_page, n); 1795 1796 /* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */ 1797 data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset; 1798 data.guest_address |= sev_me_mask; 1799 data.guest_len = params.guest_len; 1800 data.handle = to_kvm_sev_info(kvm)->handle; 1801 1802 ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data, 1803 &argp->error); 1804 1805 sev_unpin_memory(kvm, guest_page, n); 1806 1807 e_free_trans: 1808 kfree(trans); 1809 e_free_hdr: 1810 kfree(hdr); 1811 1812 return ret; 1813 } 1814 1815 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) 1816 { 1817 struct sev_data_receive_finish data; 1818 1819 if (!sev_guest(kvm)) 1820 return -ENOTTY; 1821 1822 data.handle = to_kvm_sev_info(kvm)->handle; 1823 return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error); 1824 } 1825 1826 static bool is_cmd_allowed_from_mirror(u32 cmd_id) 1827 { 1828 /* 1829 * Allow mirrors VM to call KVM_SEV_LAUNCH_UPDATE_VMSA to enable SEV-ES 1830 * active mirror VMs. Also allow the debugging and status commands. 1831 */ 1832 if (cmd_id == KVM_SEV_LAUNCH_UPDATE_VMSA || 1833 cmd_id == KVM_SEV_GUEST_STATUS || cmd_id == KVM_SEV_DBG_DECRYPT || 1834 cmd_id == KVM_SEV_DBG_ENCRYPT) 1835 return true; 1836 1837 return false; 1838 } 1839 1840 static int sev_lock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm) 1841 { 1842 struct kvm_sev_info *dst_sev = to_kvm_sev_info(dst_kvm); 1843 struct kvm_sev_info *src_sev = to_kvm_sev_info(src_kvm); 1844 int r = -EBUSY; 1845 1846 if (dst_kvm == src_kvm) 1847 return -EINVAL; 1848 1849 /* 1850 * Bail if these VMs are already involved in a migration to avoid 1851 * deadlock between two VMs trying to migrate to/from each other. 1852 */ 1853 if (atomic_cmpxchg_acquire(&dst_sev->migration_in_progress, 0, 1)) 1854 return -EBUSY; 1855 1856 if (atomic_cmpxchg_acquire(&src_sev->migration_in_progress, 0, 1)) 1857 goto release_dst; 1858 1859 r = -EINTR; 1860 if (mutex_lock_killable(&dst_kvm->lock)) 1861 goto release_src; 1862 if (mutex_lock_killable_nested(&src_kvm->lock, SINGLE_DEPTH_NESTING)) 1863 goto unlock_dst; 1864 return 0; 1865 1866 unlock_dst: 1867 mutex_unlock(&dst_kvm->lock); 1868 release_src: 1869 atomic_set_release(&src_sev->migration_in_progress, 0); 1870 release_dst: 1871 atomic_set_release(&dst_sev->migration_in_progress, 0); 1872 return r; 1873 } 1874 1875 static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm) 1876 { 1877 struct kvm_sev_info *dst_sev = to_kvm_sev_info(dst_kvm); 1878 struct kvm_sev_info *src_sev = to_kvm_sev_info(src_kvm); 1879 1880 mutex_unlock(&dst_kvm->lock); 1881 mutex_unlock(&src_kvm->lock); 1882 atomic_set_release(&dst_sev->migration_in_progress, 0); 1883 atomic_set_release(&src_sev->migration_in_progress, 0); 1884 } 1885 1886 /* vCPU mutex subclasses. */ 1887 enum sev_migration_role { 1888 SEV_MIGRATION_SOURCE = 0, 1889 SEV_MIGRATION_TARGET, 1890 SEV_NR_MIGRATION_ROLES, 1891 }; 1892 1893 static int sev_lock_vcpus_for_migration(struct kvm *kvm, 1894 enum sev_migration_role role) 1895 { 1896 struct kvm_vcpu *vcpu; 1897 unsigned long i, j; 1898 1899 kvm_for_each_vcpu(i, vcpu, kvm) { 1900 if (mutex_lock_killable_nested(&vcpu->mutex, role)) 1901 goto out_unlock; 1902 1903 #ifdef CONFIG_PROVE_LOCKING 1904 if (!i) 1905 /* 1906 * Reset the role to one that avoids colliding with 1907 * the role used for the first vcpu mutex. 1908 */ 1909 role = SEV_NR_MIGRATION_ROLES; 1910 else 1911 mutex_release(&vcpu->mutex.dep_map, _THIS_IP_); 1912 #endif 1913 } 1914 1915 return 0; 1916 1917 out_unlock: 1918 1919 kvm_for_each_vcpu(j, vcpu, kvm) { 1920 if (i == j) 1921 break; 1922 1923 #ifdef CONFIG_PROVE_LOCKING 1924 if (j) 1925 mutex_acquire(&vcpu->mutex.dep_map, role, 0, _THIS_IP_); 1926 #endif 1927 1928 mutex_unlock(&vcpu->mutex); 1929 } 1930 return -EINTR; 1931 } 1932 1933 static void sev_unlock_vcpus_for_migration(struct kvm *kvm) 1934 { 1935 struct kvm_vcpu *vcpu; 1936 unsigned long i; 1937 bool first = true; 1938 1939 kvm_for_each_vcpu(i, vcpu, kvm) { 1940 if (first) 1941 first = false; 1942 else 1943 mutex_acquire(&vcpu->mutex.dep_map, 1944 SEV_NR_MIGRATION_ROLES, 0, _THIS_IP_); 1945 1946 mutex_unlock(&vcpu->mutex); 1947 } 1948 } 1949 1950 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm) 1951 { 1952 struct kvm_sev_info *dst = to_kvm_sev_info(dst_kvm); 1953 struct kvm_sev_info *src = to_kvm_sev_info(src_kvm); 1954 struct kvm_vcpu *dst_vcpu, *src_vcpu; 1955 struct vcpu_svm *dst_svm, *src_svm; 1956 struct kvm_sev_info *mirror; 1957 unsigned long i; 1958 1959 dst->active = true; 1960 dst->asid = src->asid; 1961 dst->handle = src->handle; 1962 dst->pages_locked = src->pages_locked; 1963 dst->enc_context_owner = src->enc_context_owner; 1964 dst->es_active = src->es_active; 1965 dst->vmsa_features = src->vmsa_features; 1966 1967 src->asid = 0; 1968 src->active = false; 1969 src->handle = 0; 1970 src->pages_locked = 0; 1971 src->enc_context_owner = NULL; 1972 src->es_active = false; 1973 1974 list_cut_before(&dst->regions_list, &src->regions_list, &src->regions_list); 1975 1976 /* 1977 * If this VM has mirrors, "transfer" each mirror's refcount of the 1978 * source to the destination (this KVM). The caller holds a reference 1979 * to the source, so there's no danger of use-after-free. 1980 */ 1981 list_cut_before(&dst->mirror_vms, &src->mirror_vms, &src->mirror_vms); 1982 list_for_each_entry(mirror, &dst->mirror_vms, mirror_entry) { 1983 kvm_get_kvm(dst_kvm); 1984 kvm_put_kvm(src_kvm); 1985 mirror->enc_context_owner = dst_kvm; 1986 } 1987 1988 /* 1989 * If this VM is a mirror, remove the old mirror from the owners list 1990 * and add the new mirror to the list. 1991 */ 1992 if (is_mirroring_enc_context(dst_kvm)) { 1993 struct kvm_sev_info *owner_sev_info = to_kvm_sev_info(dst->enc_context_owner); 1994 1995 list_del(&src->mirror_entry); 1996 list_add_tail(&dst->mirror_entry, &owner_sev_info->mirror_vms); 1997 } 1998 1999 kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) { 2000 dst_svm = to_svm(dst_vcpu); 2001 2002 sev_init_vmcb(dst_svm); 2003 2004 if (!dst->es_active) 2005 continue; 2006 2007 /* 2008 * Note, the source is not required to have the same number of 2009 * vCPUs as the destination when migrating a vanilla SEV VM. 2010 */ 2011 src_vcpu = kvm_get_vcpu(src_kvm, i); 2012 src_svm = to_svm(src_vcpu); 2013 2014 /* 2015 * Transfer VMSA and GHCB state to the destination. Nullify and 2016 * clear source fields as appropriate, the state now belongs to 2017 * the destination. 2018 */ 2019 memcpy(&dst_svm->sev_es, &src_svm->sev_es, sizeof(src_svm->sev_es)); 2020 dst_svm->vmcb->control.ghcb_gpa = src_svm->vmcb->control.ghcb_gpa; 2021 dst_svm->vmcb->control.vmsa_pa = src_svm->vmcb->control.vmsa_pa; 2022 dst_vcpu->arch.guest_state_protected = true; 2023 2024 memset(&src_svm->sev_es, 0, sizeof(src_svm->sev_es)); 2025 src_svm->vmcb->control.ghcb_gpa = INVALID_PAGE; 2026 src_svm->vmcb->control.vmsa_pa = INVALID_PAGE; 2027 src_vcpu->arch.guest_state_protected = false; 2028 } 2029 } 2030 2031 static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src) 2032 { 2033 struct kvm_vcpu *src_vcpu; 2034 unsigned long i; 2035 2036 if (!sev_es_guest(src)) 2037 return 0; 2038 2039 if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus)) 2040 return -EINVAL; 2041 2042 kvm_for_each_vcpu(i, src_vcpu, src) { 2043 if (!src_vcpu->arch.guest_state_protected) 2044 return -EINVAL; 2045 } 2046 2047 return 0; 2048 } 2049 2050 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd) 2051 { 2052 struct kvm_sev_info *dst_sev = to_kvm_sev_info(kvm); 2053 struct kvm_sev_info *src_sev, *cg_cleanup_sev; 2054 CLASS(fd, f)(source_fd); 2055 struct kvm *source_kvm; 2056 bool charged = false; 2057 int ret; 2058 2059 if (fd_empty(f)) 2060 return -EBADF; 2061 2062 if (!file_is_kvm(fd_file(f))) 2063 return -EBADF; 2064 2065 source_kvm = fd_file(f)->private_data; 2066 ret = sev_lock_two_vms(kvm, source_kvm); 2067 if (ret) 2068 return ret; 2069 2070 if (kvm->arch.vm_type != source_kvm->arch.vm_type || 2071 sev_guest(kvm) || !sev_guest(source_kvm)) { 2072 ret = -EINVAL; 2073 goto out_unlock; 2074 } 2075 2076 src_sev = to_kvm_sev_info(source_kvm); 2077 2078 dst_sev->misc_cg = get_current_misc_cg(); 2079 cg_cleanup_sev = dst_sev; 2080 if (dst_sev->misc_cg != src_sev->misc_cg) { 2081 ret = sev_misc_cg_try_charge(dst_sev); 2082 if (ret) 2083 goto out_dst_cgroup; 2084 charged = true; 2085 } 2086 2087 ret = sev_lock_vcpus_for_migration(kvm, SEV_MIGRATION_SOURCE); 2088 if (ret) 2089 goto out_dst_cgroup; 2090 ret = sev_lock_vcpus_for_migration(source_kvm, SEV_MIGRATION_TARGET); 2091 if (ret) 2092 goto out_dst_vcpu; 2093 2094 ret = sev_check_source_vcpus(kvm, source_kvm); 2095 if (ret) 2096 goto out_source_vcpu; 2097 2098 sev_migrate_from(kvm, source_kvm); 2099 kvm_vm_dead(source_kvm); 2100 cg_cleanup_sev = src_sev; 2101 ret = 0; 2102 2103 out_source_vcpu: 2104 sev_unlock_vcpus_for_migration(source_kvm); 2105 out_dst_vcpu: 2106 sev_unlock_vcpus_for_migration(kvm); 2107 out_dst_cgroup: 2108 /* Operates on the source on success, on the destination on failure. */ 2109 if (charged) 2110 sev_misc_cg_uncharge(cg_cleanup_sev); 2111 put_misc_cg(cg_cleanup_sev->misc_cg); 2112 cg_cleanup_sev->misc_cg = NULL; 2113 out_unlock: 2114 sev_unlock_two_vms(kvm, source_kvm); 2115 return ret; 2116 } 2117 2118 int sev_dev_get_attr(u32 group, u64 attr, u64 *val) 2119 { 2120 if (group != KVM_X86_GRP_SEV) 2121 return -ENXIO; 2122 2123 switch (attr) { 2124 case KVM_X86_SEV_VMSA_FEATURES: 2125 *val = sev_supported_vmsa_features; 2126 return 0; 2127 2128 default: 2129 return -ENXIO; 2130 } 2131 } 2132 2133 /* 2134 * The guest context contains all the information, keys and metadata 2135 * associated with the guest that the firmware tracks to implement SEV 2136 * and SNP features. The firmware stores the guest context in hypervisor 2137 * provide page via the SNP_GCTX_CREATE command. 2138 */ 2139 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp) 2140 { 2141 struct sev_data_snp_addr data = {}; 2142 void *context; 2143 int rc; 2144 2145 /* Allocate memory for context page */ 2146 context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT); 2147 if (!context) 2148 return NULL; 2149 2150 data.address = __psp_pa(context); 2151 rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error); 2152 if (rc) { 2153 pr_warn("Failed to create SEV-SNP context, rc %d fw_error %d", 2154 rc, argp->error); 2155 snp_free_firmware_page(context); 2156 return NULL; 2157 } 2158 2159 return context; 2160 } 2161 2162 static int snp_bind_asid(struct kvm *kvm, int *error) 2163 { 2164 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2165 struct sev_data_snp_activate data = {0}; 2166 2167 data.gctx_paddr = __psp_pa(sev->snp_context); 2168 data.asid = sev_get_asid(kvm); 2169 return sev_issue_cmd(kvm, SEV_CMD_SNP_ACTIVATE, &data, error); 2170 } 2171 2172 static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) 2173 { 2174 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2175 struct sev_data_snp_launch_start start = {0}; 2176 struct kvm_sev_snp_launch_start params; 2177 int rc; 2178 2179 if (!sev_snp_guest(kvm)) 2180 return -ENOTTY; 2181 2182 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 2183 return -EFAULT; 2184 2185 /* Don't allow userspace to allocate memory for more than 1 SNP context. */ 2186 if (sev->snp_context) 2187 return -EINVAL; 2188 2189 if (params.flags) 2190 return -EINVAL; 2191 2192 if (params.policy & ~SNP_POLICY_MASK_VALID) 2193 return -EINVAL; 2194 2195 /* Check for policy bits that must be set */ 2196 if (!(params.policy & SNP_POLICY_MASK_RSVD_MBO) || 2197 !(params.policy & SNP_POLICY_MASK_SMT)) 2198 return -EINVAL; 2199 2200 if (params.policy & SNP_POLICY_MASK_SINGLE_SOCKET) 2201 return -EINVAL; 2202 2203 sev->snp_context = snp_context_create(kvm, argp); 2204 if (!sev->snp_context) 2205 return -ENOTTY; 2206 2207 start.gctx_paddr = __psp_pa(sev->snp_context); 2208 start.policy = params.policy; 2209 memcpy(start.gosvw, params.gosvw, sizeof(params.gosvw)); 2210 rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_START, &start, &argp->error); 2211 if (rc) { 2212 pr_debug("%s: SEV_CMD_SNP_LAUNCH_START firmware command failed, rc %d\n", 2213 __func__, rc); 2214 goto e_free_context; 2215 } 2216 2217 sev->fd = argp->sev_fd; 2218 rc = snp_bind_asid(kvm, &argp->error); 2219 if (rc) { 2220 pr_debug("%s: Failed to bind ASID to SEV-SNP context, rc %d\n", 2221 __func__, rc); 2222 goto e_free_context; 2223 } 2224 2225 return 0; 2226 2227 e_free_context: 2228 snp_decommission_context(kvm); 2229 2230 return rc; 2231 } 2232 2233 struct sev_gmem_populate_args { 2234 __u8 type; 2235 int sev_fd; 2236 int fw_error; 2237 }; 2238 2239 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn_start, kvm_pfn_t pfn, 2240 void __user *src, int order, void *opaque) 2241 { 2242 struct sev_gmem_populate_args *sev_populate_args = opaque; 2243 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2244 int n_private = 0, ret, i; 2245 int npages = (1 << order); 2246 gfn_t gfn; 2247 2248 if (WARN_ON_ONCE(sev_populate_args->type != KVM_SEV_SNP_PAGE_TYPE_ZERO && !src)) 2249 return -EINVAL; 2250 2251 for (gfn = gfn_start, i = 0; gfn < gfn_start + npages; gfn++, i++) { 2252 struct sev_data_snp_launch_update fw_args = {0}; 2253 bool assigned = false; 2254 int level; 2255 2256 ret = snp_lookup_rmpentry((u64)pfn + i, &assigned, &level); 2257 if (ret || assigned) { 2258 pr_debug("%s: Failed to ensure GFN 0x%llx RMP entry is initial shared state, ret: %d assigned: %d\n", 2259 __func__, gfn, ret, assigned); 2260 ret = ret ? -EINVAL : -EEXIST; 2261 goto err; 2262 } 2263 2264 if (src) { 2265 void *vaddr = kmap_local_pfn(pfn + i); 2266 2267 if (copy_from_user(vaddr, src + i * PAGE_SIZE, PAGE_SIZE)) { 2268 ret = -EFAULT; 2269 goto err; 2270 } 2271 kunmap_local(vaddr); 2272 } 2273 2274 ret = rmp_make_private(pfn + i, gfn << PAGE_SHIFT, PG_LEVEL_4K, 2275 sev_get_asid(kvm), true); 2276 if (ret) 2277 goto err; 2278 2279 n_private++; 2280 2281 fw_args.gctx_paddr = __psp_pa(sev->snp_context); 2282 fw_args.address = __sme_set(pfn_to_hpa(pfn + i)); 2283 fw_args.page_size = PG_LEVEL_TO_RMP(PG_LEVEL_4K); 2284 fw_args.page_type = sev_populate_args->type; 2285 2286 ret = __sev_issue_cmd(sev_populate_args->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE, 2287 &fw_args, &sev_populate_args->fw_error); 2288 if (ret) 2289 goto fw_err; 2290 } 2291 2292 return 0; 2293 2294 fw_err: 2295 /* 2296 * If the firmware command failed handle the reclaim and cleanup of that 2297 * PFN specially vs. prior pages which can be cleaned up below without 2298 * needing to reclaim in advance. 2299 * 2300 * Additionally, when invalid CPUID function entries are detected, 2301 * firmware writes the expected values into the page and leaves it 2302 * unencrypted so it can be used for debugging and error-reporting. 2303 * 2304 * Copy this page back into the source buffer so userspace can use this 2305 * information to provide information on which CPUID leaves/fields 2306 * failed CPUID validation. 2307 */ 2308 if (!snp_page_reclaim(kvm, pfn + i) && 2309 sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_CPUID && 2310 sev_populate_args->fw_error == SEV_RET_INVALID_PARAM) { 2311 void *vaddr = kmap_local_pfn(pfn + i); 2312 2313 if (copy_to_user(src + i * PAGE_SIZE, vaddr, PAGE_SIZE)) 2314 pr_debug("Failed to write CPUID page back to userspace\n"); 2315 2316 kunmap_local(vaddr); 2317 } 2318 2319 /* pfn + i is hypervisor-owned now, so skip below cleanup for it. */ 2320 n_private--; 2321 2322 err: 2323 pr_debug("%s: exiting with error ret %d (fw_error %d), restoring %d gmem PFNs to shared.\n", 2324 __func__, ret, sev_populate_args->fw_error, n_private); 2325 for (i = 0; i < n_private; i++) 2326 kvm_rmp_make_shared(kvm, pfn + i, PG_LEVEL_4K); 2327 2328 return ret; 2329 } 2330 2331 static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp) 2332 { 2333 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2334 struct sev_gmem_populate_args sev_populate_args = {0}; 2335 struct kvm_sev_snp_launch_update params; 2336 struct kvm_memory_slot *memslot; 2337 long npages, count; 2338 void __user *src; 2339 int ret = 0; 2340 2341 if (!sev_snp_guest(kvm) || !sev->snp_context) 2342 return -EINVAL; 2343 2344 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 2345 return -EFAULT; 2346 2347 pr_debug("%s: GFN start 0x%llx length 0x%llx type %d flags %d\n", __func__, 2348 params.gfn_start, params.len, params.type, params.flags); 2349 2350 if (!PAGE_ALIGNED(params.len) || params.flags || 2351 (params.type != KVM_SEV_SNP_PAGE_TYPE_NORMAL && 2352 params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO && 2353 params.type != KVM_SEV_SNP_PAGE_TYPE_UNMEASURED && 2354 params.type != KVM_SEV_SNP_PAGE_TYPE_SECRETS && 2355 params.type != KVM_SEV_SNP_PAGE_TYPE_CPUID)) 2356 return -EINVAL; 2357 2358 npages = params.len / PAGE_SIZE; 2359 2360 /* 2361 * For each GFN that's being prepared as part of the initial guest 2362 * state, the following pre-conditions are verified: 2363 * 2364 * 1) The backing memslot is a valid private memslot. 2365 * 2) The GFN has been set to private via KVM_SET_MEMORY_ATTRIBUTES 2366 * beforehand. 2367 * 3) The PFN of the guest_memfd has not already been set to private 2368 * in the RMP table. 2369 * 2370 * The KVM MMU relies on kvm->mmu_invalidate_seq to retry nested page 2371 * faults if there's a race between a fault and an attribute update via 2372 * KVM_SET_MEMORY_ATTRIBUTES, and a similar approach could be utilized 2373 * here. However, kvm->slots_lock guards against both this as well as 2374 * concurrent memslot updates occurring while these checks are being 2375 * performed, so use that here to make it easier to reason about the 2376 * initial expected state and better guard against unexpected 2377 * situations. 2378 */ 2379 mutex_lock(&kvm->slots_lock); 2380 2381 memslot = gfn_to_memslot(kvm, params.gfn_start); 2382 if (!kvm_slot_can_be_private(memslot)) { 2383 ret = -EINVAL; 2384 goto out; 2385 } 2386 2387 sev_populate_args.sev_fd = argp->sev_fd; 2388 sev_populate_args.type = params.type; 2389 src = params.type == KVM_SEV_SNP_PAGE_TYPE_ZERO ? NULL : u64_to_user_ptr(params.uaddr); 2390 2391 count = kvm_gmem_populate(kvm, params.gfn_start, src, npages, 2392 sev_gmem_post_populate, &sev_populate_args); 2393 if (count < 0) { 2394 argp->error = sev_populate_args.fw_error; 2395 pr_debug("%s: kvm_gmem_populate failed, ret %ld (fw_error %d)\n", 2396 __func__, count, argp->error); 2397 ret = -EIO; 2398 } else { 2399 params.gfn_start += count; 2400 params.len -= count * PAGE_SIZE; 2401 if (params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO) 2402 params.uaddr += count * PAGE_SIZE; 2403 2404 ret = 0; 2405 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params))) 2406 ret = -EFAULT; 2407 } 2408 2409 out: 2410 mutex_unlock(&kvm->slots_lock); 2411 2412 return ret; 2413 } 2414 2415 static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp) 2416 { 2417 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2418 struct sev_data_snp_launch_update data = {}; 2419 struct kvm_vcpu *vcpu; 2420 unsigned long i; 2421 int ret; 2422 2423 data.gctx_paddr = __psp_pa(sev->snp_context); 2424 data.page_type = SNP_PAGE_TYPE_VMSA; 2425 2426 kvm_for_each_vcpu(i, vcpu, kvm) { 2427 struct vcpu_svm *svm = to_svm(vcpu); 2428 u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT; 2429 2430 ret = sev_es_sync_vmsa(svm); 2431 if (ret) 2432 return ret; 2433 2434 /* Transition the VMSA page to a firmware state. */ 2435 ret = rmp_make_private(pfn, INITIAL_VMSA_GPA, PG_LEVEL_4K, sev->asid, true); 2436 if (ret) 2437 return ret; 2438 2439 /* Issue the SNP command to encrypt the VMSA */ 2440 data.address = __sme_pa(svm->sev_es.vmsa); 2441 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE, 2442 &data, &argp->error); 2443 if (ret) { 2444 snp_page_reclaim(kvm, pfn); 2445 2446 return ret; 2447 } 2448 2449 svm->vcpu.arch.guest_state_protected = true; 2450 /* 2451 * SEV-ES (and thus SNP) guest mandates LBR Virtualization to 2452 * be _always_ ON. Enable it only after setting 2453 * guest_state_protected because KVM_SET_MSRS allows dynamic 2454 * toggling of LBRV (for performance reason) on write access to 2455 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set. 2456 */ 2457 svm_enable_lbrv(vcpu); 2458 } 2459 2460 return 0; 2461 } 2462 2463 static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) 2464 { 2465 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2466 struct kvm_sev_snp_launch_finish params; 2467 struct sev_data_snp_launch_finish *data; 2468 void *id_block = NULL, *id_auth = NULL; 2469 int ret; 2470 2471 if (!sev_snp_guest(kvm)) 2472 return -ENOTTY; 2473 2474 if (!sev->snp_context) 2475 return -EINVAL; 2476 2477 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params))) 2478 return -EFAULT; 2479 2480 if (params.flags) 2481 return -EINVAL; 2482 2483 /* Measure all vCPUs using LAUNCH_UPDATE before finalizing the launch flow. */ 2484 ret = snp_launch_update_vmsa(kvm, argp); 2485 if (ret) 2486 return ret; 2487 2488 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT); 2489 if (!data) 2490 return -ENOMEM; 2491 2492 if (params.id_block_en) { 2493 id_block = psp_copy_user_blob(params.id_block_uaddr, KVM_SEV_SNP_ID_BLOCK_SIZE); 2494 if (IS_ERR(id_block)) { 2495 ret = PTR_ERR(id_block); 2496 goto e_free; 2497 } 2498 2499 data->id_block_en = 1; 2500 data->id_block_paddr = __sme_pa(id_block); 2501 2502 id_auth = psp_copy_user_blob(params.id_auth_uaddr, KVM_SEV_SNP_ID_AUTH_SIZE); 2503 if (IS_ERR(id_auth)) { 2504 ret = PTR_ERR(id_auth); 2505 goto e_free_id_block; 2506 } 2507 2508 data->id_auth_paddr = __sme_pa(id_auth); 2509 2510 if (params.auth_key_en) 2511 data->auth_key_en = 1; 2512 } 2513 2514 data->vcek_disabled = params.vcek_disabled; 2515 2516 memcpy(data->host_data, params.host_data, KVM_SEV_SNP_FINISH_DATA_SIZE); 2517 data->gctx_paddr = __psp_pa(sev->snp_context); 2518 ret = sev_issue_cmd(kvm, SEV_CMD_SNP_LAUNCH_FINISH, data, &argp->error); 2519 2520 /* 2521 * Now that there will be no more SNP_LAUNCH_UPDATE ioctls, private pages 2522 * can be given to the guest simply by marking the RMP entry as private. 2523 * This can happen on first access and also with KVM_PRE_FAULT_MEMORY. 2524 */ 2525 if (!ret) 2526 kvm->arch.pre_fault_allowed = true; 2527 2528 kfree(id_auth); 2529 2530 e_free_id_block: 2531 kfree(id_block); 2532 2533 e_free: 2534 kfree(data); 2535 2536 return ret; 2537 } 2538 2539 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp) 2540 { 2541 struct kvm_sev_cmd sev_cmd; 2542 int r; 2543 2544 if (!sev_enabled) 2545 return -ENOTTY; 2546 2547 if (!argp) 2548 return 0; 2549 2550 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd))) 2551 return -EFAULT; 2552 2553 mutex_lock(&kvm->lock); 2554 2555 /* Only the enc_context_owner handles some memory enc operations. */ 2556 if (is_mirroring_enc_context(kvm) && 2557 !is_cmd_allowed_from_mirror(sev_cmd.id)) { 2558 r = -EINVAL; 2559 goto out; 2560 } 2561 2562 /* 2563 * Once KVM_SEV_INIT2 initializes a KVM instance as an SNP guest, only 2564 * allow the use of SNP-specific commands. 2565 */ 2566 if (sev_snp_guest(kvm) && sev_cmd.id < KVM_SEV_SNP_LAUNCH_START) { 2567 r = -EPERM; 2568 goto out; 2569 } 2570 2571 switch (sev_cmd.id) { 2572 case KVM_SEV_ES_INIT: 2573 if (!sev_es_enabled) { 2574 r = -ENOTTY; 2575 goto out; 2576 } 2577 fallthrough; 2578 case KVM_SEV_INIT: 2579 r = sev_guest_init(kvm, &sev_cmd); 2580 break; 2581 case KVM_SEV_INIT2: 2582 r = sev_guest_init2(kvm, &sev_cmd); 2583 break; 2584 case KVM_SEV_LAUNCH_START: 2585 r = sev_launch_start(kvm, &sev_cmd); 2586 break; 2587 case KVM_SEV_LAUNCH_UPDATE_DATA: 2588 r = sev_launch_update_data(kvm, &sev_cmd); 2589 break; 2590 case KVM_SEV_LAUNCH_UPDATE_VMSA: 2591 r = sev_launch_update_vmsa(kvm, &sev_cmd); 2592 break; 2593 case KVM_SEV_LAUNCH_MEASURE: 2594 r = sev_launch_measure(kvm, &sev_cmd); 2595 break; 2596 case KVM_SEV_LAUNCH_FINISH: 2597 r = sev_launch_finish(kvm, &sev_cmd); 2598 break; 2599 case KVM_SEV_GUEST_STATUS: 2600 r = sev_guest_status(kvm, &sev_cmd); 2601 break; 2602 case KVM_SEV_DBG_DECRYPT: 2603 r = sev_dbg_crypt(kvm, &sev_cmd, true); 2604 break; 2605 case KVM_SEV_DBG_ENCRYPT: 2606 r = sev_dbg_crypt(kvm, &sev_cmd, false); 2607 break; 2608 case KVM_SEV_LAUNCH_SECRET: 2609 r = sev_launch_secret(kvm, &sev_cmd); 2610 break; 2611 case KVM_SEV_GET_ATTESTATION_REPORT: 2612 r = sev_get_attestation_report(kvm, &sev_cmd); 2613 break; 2614 case KVM_SEV_SEND_START: 2615 r = sev_send_start(kvm, &sev_cmd); 2616 break; 2617 case KVM_SEV_SEND_UPDATE_DATA: 2618 r = sev_send_update_data(kvm, &sev_cmd); 2619 break; 2620 case KVM_SEV_SEND_FINISH: 2621 r = sev_send_finish(kvm, &sev_cmd); 2622 break; 2623 case KVM_SEV_SEND_CANCEL: 2624 r = sev_send_cancel(kvm, &sev_cmd); 2625 break; 2626 case KVM_SEV_RECEIVE_START: 2627 r = sev_receive_start(kvm, &sev_cmd); 2628 break; 2629 case KVM_SEV_RECEIVE_UPDATE_DATA: 2630 r = sev_receive_update_data(kvm, &sev_cmd); 2631 break; 2632 case KVM_SEV_RECEIVE_FINISH: 2633 r = sev_receive_finish(kvm, &sev_cmd); 2634 break; 2635 case KVM_SEV_SNP_LAUNCH_START: 2636 r = snp_launch_start(kvm, &sev_cmd); 2637 break; 2638 case KVM_SEV_SNP_LAUNCH_UPDATE: 2639 r = snp_launch_update(kvm, &sev_cmd); 2640 break; 2641 case KVM_SEV_SNP_LAUNCH_FINISH: 2642 r = snp_launch_finish(kvm, &sev_cmd); 2643 break; 2644 default: 2645 r = -EINVAL; 2646 goto out; 2647 } 2648 2649 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd))) 2650 r = -EFAULT; 2651 2652 out: 2653 mutex_unlock(&kvm->lock); 2654 return r; 2655 } 2656 2657 int sev_mem_enc_register_region(struct kvm *kvm, 2658 struct kvm_enc_region *range) 2659 { 2660 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2661 struct enc_region *region; 2662 int ret = 0; 2663 2664 if (!sev_guest(kvm)) 2665 return -ENOTTY; 2666 2667 /* If kvm is mirroring encryption context it isn't responsible for it */ 2668 if (is_mirroring_enc_context(kvm)) 2669 return -EINVAL; 2670 2671 if (range->addr > ULONG_MAX || range->size > ULONG_MAX) 2672 return -EINVAL; 2673 2674 region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT); 2675 if (!region) 2676 return -ENOMEM; 2677 2678 mutex_lock(&kvm->lock); 2679 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 2680 FOLL_WRITE | FOLL_LONGTERM); 2681 if (IS_ERR(region->pages)) { 2682 ret = PTR_ERR(region->pages); 2683 mutex_unlock(&kvm->lock); 2684 goto e_free; 2685 } 2686 2687 /* 2688 * The guest may change the memory encryption attribute from C=0 -> C=1 2689 * or vice versa for this memory range. Lets make sure caches are 2690 * flushed to ensure that guest data gets written into memory with 2691 * correct C-bit. Note, this must be done before dropping kvm->lock, 2692 * as region and its array of pages can be freed by a different task 2693 * once kvm->lock is released. 2694 */ 2695 sev_clflush_pages(region->pages, region->npages); 2696 2697 region->uaddr = range->addr; 2698 region->size = range->size; 2699 2700 list_add_tail(®ion->list, &sev->regions_list); 2701 mutex_unlock(&kvm->lock); 2702 2703 return ret; 2704 2705 e_free: 2706 kfree(region); 2707 return ret; 2708 } 2709 2710 static struct enc_region * 2711 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) 2712 { 2713 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2714 struct list_head *head = &sev->regions_list; 2715 struct enc_region *i; 2716 2717 list_for_each_entry(i, head, list) { 2718 if (i->uaddr == range->addr && 2719 i->size == range->size) 2720 return i; 2721 } 2722 2723 return NULL; 2724 } 2725 2726 static void __unregister_enc_region_locked(struct kvm *kvm, 2727 struct enc_region *region) 2728 { 2729 sev_unpin_memory(kvm, region->pages, region->npages); 2730 list_del(®ion->list); 2731 kfree(region); 2732 } 2733 2734 int sev_mem_enc_unregister_region(struct kvm *kvm, 2735 struct kvm_enc_region *range) 2736 { 2737 struct enc_region *region; 2738 int ret; 2739 2740 /* If kvm is mirroring encryption context it isn't responsible for it */ 2741 if (is_mirroring_enc_context(kvm)) 2742 return -EINVAL; 2743 2744 mutex_lock(&kvm->lock); 2745 2746 if (!sev_guest(kvm)) { 2747 ret = -ENOTTY; 2748 goto failed; 2749 } 2750 2751 region = find_enc_region(kvm, range); 2752 if (!region) { 2753 ret = -EINVAL; 2754 goto failed; 2755 } 2756 2757 /* 2758 * Ensure that all guest tagged cache entries are flushed before 2759 * releasing the pages back to the system for use. CLFLUSH will 2760 * not do this, so issue a WBINVD. 2761 */ 2762 wbinvd_on_all_cpus(); 2763 2764 __unregister_enc_region_locked(kvm, region); 2765 2766 mutex_unlock(&kvm->lock); 2767 return 0; 2768 2769 failed: 2770 mutex_unlock(&kvm->lock); 2771 return ret; 2772 } 2773 2774 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd) 2775 { 2776 CLASS(fd, f)(source_fd); 2777 struct kvm *source_kvm; 2778 struct kvm_sev_info *source_sev, *mirror_sev; 2779 int ret; 2780 2781 if (fd_empty(f)) 2782 return -EBADF; 2783 2784 if (!file_is_kvm(fd_file(f))) 2785 return -EBADF; 2786 2787 source_kvm = fd_file(f)->private_data; 2788 ret = sev_lock_two_vms(kvm, source_kvm); 2789 if (ret) 2790 return ret; 2791 2792 /* 2793 * Mirrors of mirrors should work, but let's not get silly. Also 2794 * disallow out-of-band SEV/SEV-ES init if the target is already an 2795 * SEV guest, or if vCPUs have been created. KVM relies on vCPUs being 2796 * created after SEV/SEV-ES initialization, e.g. to init intercepts. 2797 */ 2798 if (sev_guest(kvm) || !sev_guest(source_kvm) || 2799 is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) { 2800 ret = -EINVAL; 2801 goto e_unlock; 2802 } 2803 2804 /* 2805 * The mirror kvm holds an enc_context_owner ref so its asid can't 2806 * disappear until we're done with it 2807 */ 2808 source_sev = to_kvm_sev_info(source_kvm); 2809 kvm_get_kvm(source_kvm); 2810 mirror_sev = to_kvm_sev_info(kvm); 2811 list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms); 2812 2813 /* Set enc_context_owner and copy its encryption context over */ 2814 mirror_sev->enc_context_owner = source_kvm; 2815 mirror_sev->active = true; 2816 mirror_sev->asid = source_sev->asid; 2817 mirror_sev->fd = source_sev->fd; 2818 mirror_sev->es_active = source_sev->es_active; 2819 mirror_sev->need_init = false; 2820 mirror_sev->handle = source_sev->handle; 2821 INIT_LIST_HEAD(&mirror_sev->regions_list); 2822 INIT_LIST_HEAD(&mirror_sev->mirror_vms); 2823 ret = 0; 2824 2825 /* 2826 * Do not copy ap_jump_table. Since the mirror does not share the same 2827 * KVM contexts as the original, and they may have different 2828 * memory-views. 2829 */ 2830 2831 e_unlock: 2832 sev_unlock_two_vms(kvm, source_kvm); 2833 return ret; 2834 } 2835 2836 static int snp_decommission_context(struct kvm *kvm) 2837 { 2838 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2839 struct sev_data_snp_addr data = {}; 2840 int ret; 2841 2842 /* If context is not created then do nothing */ 2843 if (!sev->snp_context) 2844 return 0; 2845 2846 /* Do the decommision, which will unbind the ASID from the SNP context */ 2847 data.address = __sme_pa(sev->snp_context); 2848 down_write(&sev_deactivate_lock); 2849 ret = sev_do_cmd(SEV_CMD_SNP_DECOMMISSION, &data, NULL); 2850 up_write(&sev_deactivate_lock); 2851 2852 if (WARN_ONCE(ret, "Failed to release guest context, ret %d", ret)) 2853 return ret; 2854 2855 snp_free_firmware_page(sev->snp_context); 2856 sev->snp_context = NULL; 2857 2858 return 0; 2859 } 2860 2861 void sev_vm_destroy(struct kvm *kvm) 2862 { 2863 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 2864 struct list_head *head = &sev->regions_list; 2865 struct list_head *pos, *q; 2866 2867 if (!sev_guest(kvm)) 2868 return; 2869 2870 WARN_ON(!list_empty(&sev->mirror_vms)); 2871 2872 /* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */ 2873 if (is_mirroring_enc_context(kvm)) { 2874 struct kvm *owner_kvm = sev->enc_context_owner; 2875 2876 mutex_lock(&owner_kvm->lock); 2877 list_del(&sev->mirror_entry); 2878 mutex_unlock(&owner_kvm->lock); 2879 kvm_put_kvm(owner_kvm); 2880 return; 2881 } 2882 2883 /* 2884 * Ensure that all guest tagged cache entries are flushed before 2885 * releasing the pages back to the system for use. CLFLUSH will 2886 * not do this, so issue a WBINVD. 2887 */ 2888 wbinvd_on_all_cpus(); 2889 2890 /* 2891 * if userspace was terminated before unregistering the memory regions 2892 * then lets unpin all the registered memory. 2893 */ 2894 if (!list_empty(head)) { 2895 list_for_each_safe(pos, q, head) { 2896 __unregister_enc_region_locked(kvm, 2897 list_entry(pos, struct enc_region, list)); 2898 cond_resched(); 2899 } 2900 } 2901 2902 if (sev_snp_guest(kvm)) { 2903 snp_guest_req_cleanup(kvm); 2904 2905 /* 2906 * Decomission handles unbinding of the ASID. If it fails for 2907 * some unexpected reason, just leak the ASID. 2908 */ 2909 if (snp_decommission_context(kvm)) 2910 return; 2911 } else { 2912 sev_unbind_asid(kvm, sev->handle); 2913 } 2914 2915 sev_asid_free(sev); 2916 } 2917 2918 void __init sev_set_cpu_caps(void) 2919 { 2920 if (sev_enabled) { 2921 kvm_cpu_cap_set(X86_FEATURE_SEV); 2922 kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_VM); 2923 } 2924 if (sev_es_enabled) { 2925 kvm_cpu_cap_set(X86_FEATURE_SEV_ES); 2926 kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_ES_VM); 2927 } 2928 if (sev_snp_enabled) { 2929 kvm_cpu_cap_set(X86_FEATURE_SEV_SNP); 2930 kvm_caps.supported_vm_types |= BIT(KVM_X86_SNP_VM); 2931 } 2932 } 2933 2934 void __init sev_hardware_setup(void) 2935 { 2936 unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count; 2937 bool sev_snp_supported = false; 2938 bool sev_es_supported = false; 2939 bool sev_supported = false; 2940 2941 if (!sev_enabled || !npt_enabled || !nrips) 2942 goto out; 2943 2944 /* 2945 * SEV must obviously be supported in hardware. Sanity check that the 2946 * CPU supports decode assists, which is mandatory for SEV guests to 2947 * support instruction emulation. Ditto for flushing by ASID, as SEV 2948 * guests are bound to a single ASID, i.e. KVM can't rotate to a new 2949 * ASID to effect a TLB flush. 2950 */ 2951 if (!boot_cpu_has(X86_FEATURE_SEV) || 2952 WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)) || 2953 WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_FLUSHBYASID))) 2954 goto out; 2955 2956 /* 2957 * The kernel's initcall infrastructure lacks the ability to express 2958 * dependencies between initcalls, whereas the modules infrastructure 2959 * automatically handles dependencies via symbol loading. Ensure the 2960 * PSP SEV driver is initialized before proceeding if KVM is built-in, 2961 * as the dependency isn't handled by the initcall infrastructure. 2962 */ 2963 if (IS_BUILTIN(CONFIG_KVM_AMD) && sev_module_init()) 2964 goto out; 2965 2966 /* Retrieve SEV CPUID information */ 2967 cpuid(0x8000001f, &eax, &ebx, &ecx, &edx); 2968 2969 /* Set encryption bit location for SEV-ES guests */ 2970 sev_enc_bit = ebx & 0x3f; 2971 2972 /* Maximum number of encrypted guests supported simultaneously */ 2973 max_sev_asid = ecx; 2974 if (!max_sev_asid) 2975 goto out; 2976 2977 /* Minimum ASID value that should be used for SEV guest */ 2978 min_sev_asid = edx; 2979 sev_me_mask = 1UL << (ebx & 0x3f); 2980 2981 /* 2982 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap, 2983 * even though it's never used, so that the bitmap is indexed by the 2984 * actual ASID. 2985 */ 2986 nr_asids = max_sev_asid + 1; 2987 sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL); 2988 if (!sev_asid_bitmap) 2989 goto out; 2990 2991 sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL); 2992 if (!sev_reclaim_asid_bitmap) { 2993 bitmap_free(sev_asid_bitmap); 2994 sev_asid_bitmap = NULL; 2995 goto out; 2996 } 2997 2998 if (min_sev_asid <= max_sev_asid) { 2999 sev_asid_count = max_sev_asid - min_sev_asid + 1; 3000 WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count)); 3001 } 3002 sev_supported = true; 3003 3004 /* SEV-ES support requested? */ 3005 if (!sev_es_enabled) 3006 goto out; 3007 3008 /* 3009 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest 3010 * instruction stream, i.e. can't emulate in response to a #NPF and 3011 * instead relies on #NPF(RSVD) being reflected into the guest as #VC 3012 * (the guest can then do a #VMGEXIT to request MMIO emulation). 3013 */ 3014 if (!enable_mmio_caching) 3015 goto out; 3016 3017 /* Does the CPU support SEV-ES? */ 3018 if (!boot_cpu_has(X86_FEATURE_SEV_ES)) 3019 goto out; 3020 3021 if (!lbrv) { 3022 WARN_ONCE(!boot_cpu_has(X86_FEATURE_LBRV), 3023 "LBRV must be present for SEV-ES support"); 3024 goto out; 3025 } 3026 3027 /* Has the system been allocated ASIDs for SEV-ES? */ 3028 if (min_sev_asid == 1) 3029 goto out; 3030 3031 sev_es_asid_count = min_sev_asid - 1; 3032 WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count)); 3033 sev_es_supported = true; 3034 sev_snp_supported = sev_snp_enabled && cc_platform_has(CC_ATTR_HOST_SEV_SNP); 3035 3036 out: 3037 if (boot_cpu_has(X86_FEATURE_SEV)) 3038 pr_info("SEV %s (ASIDs %u - %u)\n", 3039 sev_supported ? min_sev_asid <= max_sev_asid ? "enabled" : 3040 "unusable" : 3041 "disabled", 3042 min_sev_asid, max_sev_asid); 3043 if (boot_cpu_has(X86_FEATURE_SEV_ES)) 3044 pr_info("SEV-ES %s (ASIDs %u - %u)\n", 3045 str_enabled_disabled(sev_es_supported), 3046 min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1); 3047 if (boot_cpu_has(X86_FEATURE_SEV_SNP)) 3048 pr_info("SEV-SNP %s (ASIDs %u - %u)\n", 3049 str_enabled_disabled(sev_snp_supported), 3050 min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1); 3051 3052 sev_enabled = sev_supported; 3053 sev_es_enabled = sev_es_supported; 3054 sev_snp_enabled = sev_snp_supported; 3055 3056 if (!sev_es_enabled || !cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) || 3057 !cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP)) 3058 sev_es_debug_swap_enabled = false; 3059 3060 sev_supported_vmsa_features = 0; 3061 if (sev_es_debug_swap_enabled) 3062 sev_supported_vmsa_features |= SVM_SEV_FEAT_DEBUG_SWAP; 3063 } 3064 3065 void sev_hardware_unsetup(void) 3066 { 3067 if (!sev_enabled) 3068 return; 3069 3070 /* No need to take sev_bitmap_lock, all VMs have been destroyed. */ 3071 sev_flush_asids(1, max_sev_asid); 3072 3073 bitmap_free(sev_asid_bitmap); 3074 bitmap_free(sev_reclaim_asid_bitmap); 3075 3076 misc_cg_set_capacity(MISC_CG_RES_SEV, 0); 3077 misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0); 3078 } 3079 3080 int sev_cpu_init(struct svm_cpu_data *sd) 3081 { 3082 if (!sev_enabled) 3083 return 0; 3084 3085 sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL); 3086 if (!sd->sev_vmcbs) 3087 return -ENOMEM; 3088 3089 return 0; 3090 } 3091 3092 /* 3093 * Pages used by hardware to hold guest encrypted state must be flushed before 3094 * returning them to the system. 3095 */ 3096 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va) 3097 { 3098 unsigned int asid = sev_get_asid(vcpu->kvm); 3099 3100 /* 3101 * Note! The address must be a kernel address, as regular page walk 3102 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user 3103 * address is non-deterministic and unsafe. This function deliberately 3104 * takes a pointer to deter passing in a user address. 3105 */ 3106 unsigned long addr = (unsigned long)va; 3107 3108 /* 3109 * If CPU enforced cache coherency for encrypted mappings of the 3110 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache 3111 * flush is still needed in order to work properly with DMA devices. 3112 */ 3113 if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) { 3114 clflush_cache_range(va, PAGE_SIZE); 3115 return; 3116 } 3117 3118 /* 3119 * VM Page Flush takes a host virtual address and a guest ASID. Fall 3120 * back to WBINVD if this faults so as not to make any problems worse 3121 * by leaving stale encrypted data in the cache. 3122 */ 3123 if (WARN_ON_ONCE(wrmsrq_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid))) 3124 goto do_wbinvd; 3125 3126 return; 3127 3128 do_wbinvd: 3129 wbinvd_on_all_cpus(); 3130 } 3131 3132 void sev_guest_memory_reclaimed(struct kvm *kvm) 3133 { 3134 /* 3135 * With SNP+gmem, private/encrypted memory is unreachable via the 3136 * hva-based mmu notifiers, so these events are only actually 3137 * pertaining to shared pages where there is no need to perform 3138 * the WBINVD to flush associated caches. 3139 */ 3140 if (!sev_guest(kvm) || sev_snp_guest(kvm)) 3141 return; 3142 3143 wbinvd_on_all_cpus(); 3144 } 3145 3146 void sev_free_vcpu(struct kvm_vcpu *vcpu) 3147 { 3148 struct vcpu_svm *svm; 3149 3150 if (!sev_es_guest(vcpu->kvm)) 3151 return; 3152 3153 svm = to_svm(vcpu); 3154 3155 /* 3156 * If it's an SNP guest, then the VMSA was marked in the RMP table as 3157 * a guest-owned page. Transition the page to hypervisor state before 3158 * releasing it back to the system. 3159 */ 3160 if (sev_snp_guest(vcpu->kvm)) { 3161 u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT; 3162 3163 if (kvm_rmp_make_shared(vcpu->kvm, pfn, PG_LEVEL_4K)) 3164 goto skip_vmsa_free; 3165 } 3166 3167 if (vcpu->arch.guest_state_protected) 3168 sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa); 3169 3170 __free_page(virt_to_page(svm->sev_es.vmsa)); 3171 3172 skip_vmsa_free: 3173 if (svm->sev_es.ghcb_sa_free) 3174 kvfree(svm->sev_es.ghcb_sa); 3175 } 3176 3177 static u64 kvm_ghcb_get_sw_exit_code(struct vmcb_control_area *control) 3178 { 3179 return (((u64)control->exit_code_hi) << 32) | control->exit_code; 3180 } 3181 3182 static void dump_ghcb(struct vcpu_svm *svm) 3183 { 3184 struct vmcb_control_area *control = &svm->vmcb->control; 3185 unsigned int nbits; 3186 3187 /* Re-use the dump_invalid_vmcb module parameter */ 3188 if (!dump_invalid_vmcb) { 3189 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n"); 3190 return; 3191 } 3192 3193 nbits = sizeof(svm->sev_es.valid_bitmap) * 8; 3194 3195 /* 3196 * Print KVM's snapshot of the GHCB values that were (unsuccessfully) 3197 * used to handle the exit. If the guest has since modified the GHCB 3198 * itself, dumping the raw GHCB won't help debug why KVM was unable to 3199 * handle the VMGEXIT that KVM observed. 3200 */ 3201 pr_err("GHCB (GPA=%016llx) snapshot:\n", svm->vmcb->control.ghcb_gpa); 3202 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code", 3203 kvm_ghcb_get_sw_exit_code(control), kvm_ghcb_sw_exit_code_is_valid(svm)); 3204 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1", 3205 control->exit_info_1, kvm_ghcb_sw_exit_info_1_is_valid(svm)); 3206 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2", 3207 control->exit_info_2, kvm_ghcb_sw_exit_info_2_is_valid(svm)); 3208 pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch", 3209 svm->sev_es.sw_scratch, kvm_ghcb_sw_scratch_is_valid(svm)); 3210 pr_err("%-20s%*pb\n", "valid_bitmap", nbits, svm->sev_es.valid_bitmap); 3211 } 3212 3213 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm) 3214 { 3215 struct kvm_vcpu *vcpu = &svm->vcpu; 3216 struct ghcb *ghcb = svm->sev_es.ghcb; 3217 3218 /* 3219 * The GHCB protocol so far allows for the following data 3220 * to be returned: 3221 * GPRs RAX, RBX, RCX, RDX 3222 * 3223 * Copy their values, even if they may not have been written during the 3224 * VM-Exit. It's the guest's responsibility to not consume random data. 3225 */ 3226 ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]); 3227 ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]); 3228 ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]); 3229 ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]); 3230 } 3231 3232 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm) 3233 { 3234 struct vmcb_control_area *control = &svm->vmcb->control; 3235 struct kvm_vcpu *vcpu = &svm->vcpu; 3236 struct ghcb *ghcb = svm->sev_es.ghcb; 3237 u64 exit_code; 3238 3239 /* 3240 * The GHCB protocol so far allows for the following data 3241 * to be supplied: 3242 * GPRs RAX, RBX, RCX, RDX 3243 * XCR0 3244 * CPL 3245 * 3246 * VMMCALL allows the guest to provide extra registers. KVM also 3247 * expects RSI for hypercalls, so include that, too. 3248 * 3249 * Copy their values to the appropriate location if supplied. 3250 */ 3251 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs)); 3252 3253 BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap)); 3254 memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap)); 3255 3256 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm, ghcb); 3257 vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm, ghcb); 3258 vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm, ghcb); 3259 vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm, ghcb); 3260 vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm, ghcb); 3261 3262 svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm, ghcb); 3263 3264 if (kvm_ghcb_xcr0_is_valid(svm)) { 3265 vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb); 3266 vcpu->arch.cpuid_dynamic_bits_dirty = true; 3267 } 3268 3269 /* Copy the GHCB exit information into the VMCB fields */ 3270 exit_code = ghcb_get_sw_exit_code(ghcb); 3271 control->exit_code = lower_32_bits(exit_code); 3272 control->exit_code_hi = upper_32_bits(exit_code); 3273 control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb); 3274 control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb); 3275 svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm, ghcb); 3276 3277 /* Clear the valid entries fields */ 3278 memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap)); 3279 } 3280 3281 static int sev_es_validate_vmgexit(struct vcpu_svm *svm) 3282 { 3283 struct vmcb_control_area *control = &svm->vmcb->control; 3284 struct kvm_vcpu *vcpu = &svm->vcpu; 3285 u64 exit_code; 3286 u64 reason; 3287 3288 /* 3289 * Retrieve the exit code now even though it may not be marked valid 3290 * as it could help with debugging. 3291 */ 3292 exit_code = kvm_ghcb_get_sw_exit_code(control); 3293 3294 /* Only GHCB Usage code 0 is supported */ 3295 if (svm->sev_es.ghcb->ghcb_usage) { 3296 reason = GHCB_ERR_INVALID_USAGE; 3297 goto vmgexit_err; 3298 } 3299 3300 reason = GHCB_ERR_MISSING_INPUT; 3301 3302 if (!kvm_ghcb_sw_exit_code_is_valid(svm) || 3303 !kvm_ghcb_sw_exit_info_1_is_valid(svm) || 3304 !kvm_ghcb_sw_exit_info_2_is_valid(svm)) 3305 goto vmgexit_err; 3306 3307 switch (exit_code) { 3308 case SVM_EXIT_READ_DR7: 3309 break; 3310 case SVM_EXIT_WRITE_DR7: 3311 if (!kvm_ghcb_rax_is_valid(svm)) 3312 goto vmgexit_err; 3313 break; 3314 case SVM_EXIT_RDTSC: 3315 break; 3316 case SVM_EXIT_RDPMC: 3317 if (!kvm_ghcb_rcx_is_valid(svm)) 3318 goto vmgexit_err; 3319 break; 3320 case SVM_EXIT_CPUID: 3321 if (!kvm_ghcb_rax_is_valid(svm) || 3322 !kvm_ghcb_rcx_is_valid(svm)) 3323 goto vmgexit_err; 3324 if (vcpu->arch.regs[VCPU_REGS_RAX] == 0xd) 3325 if (!kvm_ghcb_xcr0_is_valid(svm)) 3326 goto vmgexit_err; 3327 break; 3328 case SVM_EXIT_INVD: 3329 break; 3330 case SVM_EXIT_IOIO: 3331 if (control->exit_info_1 & SVM_IOIO_STR_MASK) { 3332 if (!kvm_ghcb_sw_scratch_is_valid(svm)) 3333 goto vmgexit_err; 3334 } else { 3335 if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK)) 3336 if (!kvm_ghcb_rax_is_valid(svm)) 3337 goto vmgexit_err; 3338 } 3339 break; 3340 case SVM_EXIT_MSR: 3341 if (!kvm_ghcb_rcx_is_valid(svm)) 3342 goto vmgexit_err; 3343 if (control->exit_info_1) { 3344 if (!kvm_ghcb_rax_is_valid(svm) || 3345 !kvm_ghcb_rdx_is_valid(svm)) 3346 goto vmgexit_err; 3347 } 3348 break; 3349 case SVM_EXIT_VMMCALL: 3350 if (!kvm_ghcb_rax_is_valid(svm) || 3351 !kvm_ghcb_cpl_is_valid(svm)) 3352 goto vmgexit_err; 3353 break; 3354 case SVM_EXIT_RDTSCP: 3355 break; 3356 case SVM_EXIT_WBINVD: 3357 break; 3358 case SVM_EXIT_MONITOR: 3359 if (!kvm_ghcb_rax_is_valid(svm) || 3360 !kvm_ghcb_rcx_is_valid(svm) || 3361 !kvm_ghcb_rdx_is_valid(svm)) 3362 goto vmgexit_err; 3363 break; 3364 case SVM_EXIT_MWAIT: 3365 if (!kvm_ghcb_rax_is_valid(svm) || 3366 !kvm_ghcb_rcx_is_valid(svm)) 3367 goto vmgexit_err; 3368 break; 3369 case SVM_VMGEXIT_MMIO_READ: 3370 case SVM_VMGEXIT_MMIO_WRITE: 3371 if (!kvm_ghcb_sw_scratch_is_valid(svm)) 3372 goto vmgexit_err; 3373 break; 3374 case SVM_VMGEXIT_AP_CREATION: 3375 if (!sev_snp_guest(vcpu->kvm)) 3376 goto vmgexit_err; 3377 if (lower_32_bits(control->exit_info_1) != SVM_VMGEXIT_AP_DESTROY) 3378 if (!kvm_ghcb_rax_is_valid(svm)) 3379 goto vmgexit_err; 3380 break; 3381 case SVM_VMGEXIT_NMI_COMPLETE: 3382 case SVM_VMGEXIT_AP_HLT_LOOP: 3383 case SVM_VMGEXIT_AP_JUMP_TABLE: 3384 case SVM_VMGEXIT_UNSUPPORTED_EVENT: 3385 case SVM_VMGEXIT_HV_FEATURES: 3386 case SVM_VMGEXIT_TERM_REQUEST: 3387 break; 3388 case SVM_VMGEXIT_PSC: 3389 if (!sev_snp_guest(vcpu->kvm) || !kvm_ghcb_sw_scratch_is_valid(svm)) 3390 goto vmgexit_err; 3391 break; 3392 case SVM_VMGEXIT_GUEST_REQUEST: 3393 case SVM_VMGEXIT_EXT_GUEST_REQUEST: 3394 if (!sev_snp_guest(vcpu->kvm) || 3395 !PAGE_ALIGNED(control->exit_info_1) || 3396 !PAGE_ALIGNED(control->exit_info_2) || 3397 control->exit_info_1 == control->exit_info_2) 3398 goto vmgexit_err; 3399 break; 3400 default: 3401 reason = GHCB_ERR_INVALID_EVENT; 3402 goto vmgexit_err; 3403 } 3404 3405 return 0; 3406 3407 vmgexit_err: 3408 if (reason == GHCB_ERR_INVALID_USAGE) { 3409 vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n", 3410 svm->sev_es.ghcb->ghcb_usage); 3411 } else if (reason == GHCB_ERR_INVALID_EVENT) { 3412 vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n", 3413 exit_code); 3414 } else { 3415 vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n", 3416 exit_code); 3417 dump_ghcb(svm); 3418 } 3419 3420 svm_vmgexit_bad_input(svm, reason); 3421 3422 /* Resume the guest to "return" the error code. */ 3423 return 1; 3424 } 3425 3426 void sev_es_unmap_ghcb(struct vcpu_svm *svm) 3427 { 3428 /* Clear any indication that the vCPU is in a type of AP Reset Hold */ 3429 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NONE; 3430 3431 if (!svm->sev_es.ghcb) 3432 return; 3433 3434 if (svm->sev_es.ghcb_sa_free) { 3435 /* 3436 * The scratch area lives outside the GHCB, so there is a 3437 * buffer that, depending on the operation performed, may 3438 * need to be synced, then freed. 3439 */ 3440 if (svm->sev_es.ghcb_sa_sync) { 3441 kvm_write_guest(svm->vcpu.kvm, 3442 svm->sev_es.sw_scratch, 3443 svm->sev_es.ghcb_sa, 3444 svm->sev_es.ghcb_sa_len); 3445 svm->sev_es.ghcb_sa_sync = false; 3446 } 3447 3448 kvfree(svm->sev_es.ghcb_sa); 3449 svm->sev_es.ghcb_sa = NULL; 3450 svm->sev_es.ghcb_sa_free = false; 3451 } 3452 3453 trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb); 3454 3455 sev_es_sync_to_ghcb(svm); 3456 3457 kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map); 3458 svm->sev_es.ghcb = NULL; 3459 } 3460 3461 int pre_sev_run(struct vcpu_svm *svm, int cpu) 3462 { 3463 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu); 3464 struct kvm *kvm = svm->vcpu.kvm; 3465 unsigned int asid = sev_get_asid(kvm); 3466 3467 /* 3468 * Reject KVM_RUN if userspace attempts to run the vCPU with an invalid 3469 * VMSA, e.g. if userspace forces the vCPU to be RUNNABLE after an SNP 3470 * AP Destroy event. 3471 */ 3472 if (sev_es_guest(kvm) && !VALID_PAGE(svm->vmcb->control.vmsa_pa)) 3473 return -EINVAL; 3474 3475 /* Assign the asid allocated with this SEV guest */ 3476 svm->asid = asid; 3477 3478 /* 3479 * Flush guest TLB: 3480 * 3481 * 1) when different VMCB for the same ASID is to be run on the same host CPU. 3482 * 2) or this VMCB was executed on different host CPU in previous VMRUNs. 3483 */ 3484 if (sd->sev_vmcbs[asid] == svm->vmcb && 3485 svm->vcpu.arch.last_vmentry_cpu == cpu) 3486 return 0; 3487 3488 sd->sev_vmcbs[asid] = svm->vmcb; 3489 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID; 3490 vmcb_mark_dirty(svm->vmcb, VMCB_ASID); 3491 return 0; 3492 } 3493 3494 #define GHCB_SCRATCH_AREA_LIMIT (16ULL * PAGE_SIZE) 3495 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len) 3496 { 3497 struct vmcb_control_area *control = &svm->vmcb->control; 3498 u64 ghcb_scratch_beg, ghcb_scratch_end; 3499 u64 scratch_gpa_beg, scratch_gpa_end; 3500 void *scratch_va; 3501 3502 scratch_gpa_beg = svm->sev_es.sw_scratch; 3503 if (!scratch_gpa_beg) { 3504 pr_err("vmgexit: scratch gpa not provided\n"); 3505 goto e_scratch; 3506 } 3507 3508 scratch_gpa_end = scratch_gpa_beg + len; 3509 if (scratch_gpa_end < scratch_gpa_beg) { 3510 pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n", 3511 len, scratch_gpa_beg); 3512 goto e_scratch; 3513 } 3514 3515 if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) { 3516 /* Scratch area begins within GHCB */ 3517 ghcb_scratch_beg = control->ghcb_gpa + 3518 offsetof(struct ghcb, shared_buffer); 3519 ghcb_scratch_end = control->ghcb_gpa + 3520 offsetof(struct ghcb, reserved_0xff0); 3521 3522 /* 3523 * If the scratch area begins within the GHCB, it must be 3524 * completely contained in the GHCB shared buffer area. 3525 */ 3526 if (scratch_gpa_beg < ghcb_scratch_beg || 3527 scratch_gpa_end > ghcb_scratch_end) { 3528 pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n", 3529 scratch_gpa_beg, scratch_gpa_end); 3530 goto e_scratch; 3531 } 3532 3533 scratch_va = (void *)svm->sev_es.ghcb; 3534 scratch_va += (scratch_gpa_beg - control->ghcb_gpa); 3535 } else { 3536 /* 3537 * The guest memory must be read into a kernel buffer, so 3538 * limit the size 3539 */ 3540 if (len > GHCB_SCRATCH_AREA_LIMIT) { 3541 pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n", 3542 len, GHCB_SCRATCH_AREA_LIMIT); 3543 goto e_scratch; 3544 } 3545 scratch_va = kvzalloc(len, GFP_KERNEL_ACCOUNT); 3546 if (!scratch_va) 3547 return -ENOMEM; 3548 3549 if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) { 3550 /* Unable to copy scratch area from guest */ 3551 pr_err("vmgexit: kvm_read_guest for scratch area failed\n"); 3552 3553 kvfree(scratch_va); 3554 return -EFAULT; 3555 } 3556 3557 /* 3558 * The scratch area is outside the GHCB. The operation will 3559 * dictate whether the buffer needs to be synced before running 3560 * the vCPU next time (i.e. a read was requested so the data 3561 * must be written back to the guest memory). 3562 */ 3563 svm->sev_es.ghcb_sa_sync = sync; 3564 svm->sev_es.ghcb_sa_free = true; 3565 } 3566 3567 svm->sev_es.ghcb_sa = scratch_va; 3568 svm->sev_es.ghcb_sa_len = len; 3569 3570 return 0; 3571 3572 e_scratch: 3573 svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_SCRATCH_AREA); 3574 3575 return 1; 3576 } 3577 3578 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask, 3579 unsigned int pos) 3580 { 3581 svm->vmcb->control.ghcb_gpa &= ~(mask << pos); 3582 svm->vmcb->control.ghcb_gpa |= (value & mask) << pos; 3583 } 3584 3585 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos) 3586 { 3587 return (svm->vmcb->control.ghcb_gpa >> pos) & mask; 3588 } 3589 3590 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) 3591 { 3592 svm->vmcb->control.ghcb_gpa = value; 3593 } 3594 3595 static int snp_rmptable_psmash(kvm_pfn_t pfn) 3596 { 3597 int ret; 3598 3599 pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1); 3600 3601 /* 3602 * PSMASH_FAIL_INUSE indicates another processor is modifying the 3603 * entry, so retry until that's no longer the case. 3604 */ 3605 do { 3606 ret = psmash(pfn); 3607 } while (ret == PSMASH_FAIL_INUSE); 3608 3609 return ret; 3610 } 3611 3612 static int snp_complete_psc_msr(struct kvm_vcpu *vcpu) 3613 { 3614 struct vcpu_svm *svm = to_svm(vcpu); 3615 3616 if (vcpu->run->hypercall.ret) 3617 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR); 3618 else 3619 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP); 3620 3621 return 1; /* resume guest */ 3622 } 3623 3624 static int snp_begin_psc_msr(struct vcpu_svm *svm, u64 ghcb_msr) 3625 { 3626 u64 gpa = gfn_to_gpa(GHCB_MSR_PSC_REQ_TO_GFN(ghcb_msr)); 3627 u8 op = GHCB_MSR_PSC_REQ_TO_OP(ghcb_msr); 3628 struct kvm_vcpu *vcpu = &svm->vcpu; 3629 3630 if (op != SNP_PAGE_STATE_PRIVATE && op != SNP_PAGE_STATE_SHARED) { 3631 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR); 3632 return 1; /* resume guest */ 3633 } 3634 3635 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) { 3636 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR); 3637 return 1; /* resume guest */ 3638 } 3639 3640 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL; 3641 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE; 3642 /* 3643 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2) 3644 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that 3645 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting 3646 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU. 3647 */ 3648 vcpu->run->hypercall.ret = 0; 3649 vcpu->run->hypercall.args[0] = gpa; 3650 vcpu->run->hypercall.args[1] = 1; 3651 vcpu->run->hypercall.args[2] = (op == SNP_PAGE_STATE_PRIVATE) 3652 ? KVM_MAP_GPA_RANGE_ENCRYPTED 3653 : KVM_MAP_GPA_RANGE_DECRYPTED; 3654 vcpu->run->hypercall.args[2] |= KVM_MAP_GPA_RANGE_PAGE_SZ_4K; 3655 3656 vcpu->arch.complete_userspace_io = snp_complete_psc_msr; 3657 3658 return 0; /* forward request to userspace */ 3659 } 3660 3661 struct psc_buffer { 3662 struct psc_hdr hdr; 3663 struct psc_entry entries[]; 3664 } __packed; 3665 3666 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc); 3667 3668 static void snp_complete_psc(struct vcpu_svm *svm, u64 psc_ret) 3669 { 3670 svm->sev_es.psc_inflight = 0; 3671 svm->sev_es.psc_idx = 0; 3672 svm->sev_es.psc_2m = false; 3673 3674 /* 3675 * PSC requests always get a "no action" response in SW_EXITINFO1, with 3676 * a PSC-specific return code in SW_EXITINFO2 that provides the "real" 3677 * return code. E.g. if the PSC request was interrupted, the need to 3678 * retry is communicated via SW_EXITINFO2, not SW_EXITINFO1. 3679 */ 3680 svm_vmgexit_no_action(svm, psc_ret); 3681 } 3682 3683 static void __snp_complete_one_psc(struct vcpu_svm *svm) 3684 { 3685 struct psc_buffer *psc = svm->sev_es.ghcb_sa; 3686 struct psc_entry *entries = psc->entries; 3687 struct psc_hdr *hdr = &psc->hdr; 3688 __u16 idx; 3689 3690 /* 3691 * Everything in-flight has been processed successfully. Update the 3692 * corresponding entries in the guest's PSC buffer and zero out the 3693 * count of in-flight PSC entries. 3694 */ 3695 for (idx = svm->sev_es.psc_idx; svm->sev_es.psc_inflight; 3696 svm->sev_es.psc_inflight--, idx++) { 3697 struct psc_entry *entry = &entries[idx]; 3698 3699 entry->cur_page = entry->pagesize ? 512 : 1; 3700 } 3701 3702 hdr->cur_entry = idx; 3703 } 3704 3705 static int snp_complete_one_psc(struct kvm_vcpu *vcpu) 3706 { 3707 struct vcpu_svm *svm = to_svm(vcpu); 3708 struct psc_buffer *psc = svm->sev_es.ghcb_sa; 3709 3710 if (vcpu->run->hypercall.ret) { 3711 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC); 3712 return 1; /* resume guest */ 3713 } 3714 3715 __snp_complete_one_psc(svm); 3716 3717 /* Handle the next range (if any). */ 3718 return snp_begin_psc(svm, psc); 3719 } 3720 3721 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc) 3722 { 3723 struct psc_entry *entries = psc->entries; 3724 struct kvm_vcpu *vcpu = &svm->vcpu; 3725 struct psc_hdr *hdr = &psc->hdr; 3726 struct psc_entry entry_start; 3727 u16 idx, idx_start, idx_end; 3728 int npages; 3729 bool huge; 3730 u64 gfn; 3731 3732 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) { 3733 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC); 3734 return 1; 3735 } 3736 3737 next_range: 3738 /* There should be no other PSCs in-flight at this point. */ 3739 if (WARN_ON_ONCE(svm->sev_es.psc_inflight)) { 3740 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC); 3741 return 1; 3742 } 3743 3744 /* 3745 * The PSC descriptor buffer can be modified by a misbehaved guest after 3746 * validation, so take care to only use validated copies of values used 3747 * for things like array indexing. 3748 */ 3749 idx_start = hdr->cur_entry; 3750 idx_end = hdr->end_entry; 3751 3752 if (idx_end >= VMGEXIT_PSC_MAX_COUNT) { 3753 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_HDR); 3754 return 1; 3755 } 3756 3757 /* Find the start of the next range which needs processing. */ 3758 for (idx = idx_start; idx <= idx_end; idx++, hdr->cur_entry++) { 3759 entry_start = entries[idx]; 3760 3761 gfn = entry_start.gfn; 3762 huge = entry_start.pagesize; 3763 npages = huge ? 512 : 1; 3764 3765 if (entry_start.cur_page > npages || !IS_ALIGNED(gfn, npages)) { 3766 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_ENTRY); 3767 return 1; 3768 } 3769 3770 if (entry_start.cur_page) { 3771 /* 3772 * If this is a partially-completed 2M range, force 4K handling 3773 * for the remaining pages since they're effectively split at 3774 * this point. Subsequent code should ensure this doesn't get 3775 * combined with adjacent PSC entries where 2M handling is still 3776 * possible. 3777 */ 3778 npages -= entry_start.cur_page; 3779 gfn += entry_start.cur_page; 3780 huge = false; 3781 } 3782 3783 if (npages) 3784 break; 3785 } 3786 3787 if (idx > idx_end) { 3788 /* Nothing more to process. */ 3789 snp_complete_psc(svm, 0); 3790 return 1; 3791 } 3792 3793 svm->sev_es.psc_2m = huge; 3794 svm->sev_es.psc_idx = idx; 3795 svm->sev_es.psc_inflight = 1; 3796 3797 /* 3798 * Find all subsequent PSC entries that contain adjacent GPA 3799 * ranges/operations and can be combined into a single 3800 * KVM_HC_MAP_GPA_RANGE exit. 3801 */ 3802 while (++idx <= idx_end) { 3803 struct psc_entry entry = entries[idx]; 3804 3805 if (entry.operation != entry_start.operation || 3806 entry.gfn != entry_start.gfn + npages || 3807 entry.cur_page || !!entry.pagesize != huge) 3808 break; 3809 3810 svm->sev_es.psc_inflight++; 3811 npages += huge ? 512 : 1; 3812 } 3813 3814 switch (entry_start.operation) { 3815 case VMGEXIT_PSC_OP_PRIVATE: 3816 case VMGEXIT_PSC_OP_SHARED: 3817 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL; 3818 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE; 3819 /* 3820 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2) 3821 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that 3822 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting 3823 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU. 3824 */ 3825 vcpu->run->hypercall.ret = 0; 3826 vcpu->run->hypercall.args[0] = gfn_to_gpa(gfn); 3827 vcpu->run->hypercall.args[1] = npages; 3828 vcpu->run->hypercall.args[2] = entry_start.operation == VMGEXIT_PSC_OP_PRIVATE 3829 ? KVM_MAP_GPA_RANGE_ENCRYPTED 3830 : KVM_MAP_GPA_RANGE_DECRYPTED; 3831 vcpu->run->hypercall.args[2] |= entry_start.pagesize 3832 ? KVM_MAP_GPA_RANGE_PAGE_SZ_2M 3833 : KVM_MAP_GPA_RANGE_PAGE_SZ_4K; 3834 vcpu->arch.complete_userspace_io = snp_complete_one_psc; 3835 return 0; /* forward request to userspace */ 3836 default: 3837 /* 3838 * Only shared/private PSC operations are currently supported, so if the 3839 * entire range consists of unsupported operations (e.g. SMASH/UNSMASH), 3840 * then consider the entire range completed and avoid exiting to 3841 * userspace. In theory snp_complete_psc() can always be called directly 3842 * at this point to complete the current range and start the next one, 3843 * but that could lead to unexpected levels of recursion. 3844 */ 3845 __snp_complete_one_psc(svm); 3846 goto next_range; 3847 } 3848 3849 BUG(); 3850 } 3851 3852 /* 3853 * Invoked as part of svm_vcpu_reset() processing of an init event. 3854 */ 3855 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu) 3856 { 3857 struct vcpu_svm *svm = to_svm(vcpu); 3858 struct kvm_memory_slot *slot; 3859 struct page *page; 3860 kvm_pfn_t pfn; 3861 gfn_t gfn; 3862 3863 if (!sev_snp_guest(vcpu->kvm)) 3864 return; 3865 3866 guard(mutex)(&svm->sev_es.snp_vmsa_mutex); 3867 3868 if (!svm->sev_es.snp_ap_waiting_for_reset) 3869 return; 3870 3871 svm->sev_es.snp_ap_waiting_for_reset = false; 3872 3873 /* Mark the vCPU as offline and not runnable */ 3874 vcpu->arch.pv.pv_unhalted = false; 3875 kvm_set_mp_state(vcpu, KVM_MP_STATE_HALTED); 3876 3877 /* Clear use of the VMSA */ 3878 svm->vmcb->control.vmsa_pa = INVALID_PAGE; 3879 3880 /* 3881 * When replacing the VMSA during SEV-SNP AP creation, 3882 * mark the VMCB dirty so that full state is always reloaded. 3883 */ 3884 vmcb_mark_all_dirty(svm->vmcb); 3885 3886 if (!VALID_PAGE(svm->sev_es.snp_vmsa_gpa)) 3887 return; 3888 3889 gfn = gpa_to_gfn(svm->sev_es.snp_vmsa_gpa); 3890 svm->sev_es.snp_vmsa_gpa = INVALID_PAGE; 3891 3892 slot = gfn_to_memslot(vcpu->kvm, gfn); 3893 if (!slot) 3894 return; 3895 3896 /* 3897 * The new VMSA will be private memory guest memory, so retrieve the 3898 * PFN from the gmem backend. 3899 */ 3900 if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL)) 3901 return; 3902 3903 /* 3904 * From this point forward, the VMSA will always be a guest-mapped page 3905 * rather than the initial one allocated by KVM in svm->sev_es.vmsa. In 3906 * theory, svm->sev_es.vmsa could be free'd and cleaned up here, but 3907 * that involves cleanups like wbinvd_on_all_cpus() which would ideally 3908 * be handled during teardown rather than guest boot. Deferring that 3909 * also allows the existing logic for SEV-ES VMSAs to be re-used with 3910 * minimal SNP-specific changes. 3911 */ 3912 svm->sev_es.snp_has_guest_vmsa = true; 3913 3914 /* Use the new VMSA */ 3915 svm->vmcb->control.vmsa_pa = pfn_to_hpa(pfn); 3916 3917 /* Mark the vCPU as runnable */ 3918 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE); 3919 3920 /* 3921 * gmem pages aren't currently migratable, but if this ever changes 3922 * then care should be taken to ensure svm->sev_es.vmsa is pinned 3923 * through some other means. 3924 */ 3925 kvm_release_page_clean(page); 3926 } 3927 3928 static int sev_snp_ap_creation(struct vcpu_svm *svm) 3929 { 3930 struct kvm_sev_info *sev = to_kvm_sev_info(svm->vcpu.kvm); 3931 struct kvm_vcpu *vcpu = &svm->vcpu; 3932 struct kvm_vcpu *target_vcpu; 3933 struct vcpu_svm *target_svm; 3934 unsigned int request; 3935 unsigned int apic_id; 3936 3937 request = lower_32_bits(svm->vmcb->control.exit_info_1); 3938 apic_id = upper_32_bits(svm->vmcb->control.exit_info_1); 3939 3940 /* Validate the APIC ID */ 3941 target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id); 3942 if (!target_vcpu) { 3943 vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n", 3944 apic_id); 3945 return -EINVAL; 3946 } 3947 3948 target_svm = to_svm(target_vcpu); 3949 3950 guard(mutex)(&target_svm->sev_es.snp_vmsa_mutex); 3951 3952 switch (request) { 3953 case SVM_VMGEXIT_AP_CREATE_ON_INIT: 3954 case SVM_VMGEXIT_AP_CREATE: 3955 if (vcpu->arch.regs[VCPU_REGS_RAX] != sev->vmsa_features) { 3956 vcpu_unimpl(vcpu, "vmgexit: mismatched AP sev_features [%#lx] != [%#llx] from guest\n", 3957 vcpu->arch.regs[VCPU_REGS_RAX], sev->vmsa_features); 3958 return -EINVAL; 3959 } 3960 3961 if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) { 3962 vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n", 3963 svm->vmcb->control.exit_info_2); 3964 return -EINVAL; 3965 } 3966 3967 /* 3968 * Malicious guest can RMPADJUST a large page into VMSA which 3969 * will hit the SNP erratum where the CPU will incorrectly signal 3970 * an RMP violation #PF if a hugepage collides with the RMP entry 3971 * of VMSA page, reject the AP CREATE request if VMSA address from 3972 * guest is 2M aligned. 3973 */ 3974 if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) { 3975 vcpu_unimpl(vcpu, 3976 "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n", 3977 svm->vmcb->control.exit_info_2); 3978 return -EINVAL; 3979 } 3980 3981 target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2; 3982 break; 3983 case SVM_VMGEXIT_AP_DESTROY: 3984 target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE; 3985 break; 3986 default: 3987 vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n", 3988 request); 3989 return -EINVAL; 3990 } 3991 3992 target_svm->sev_es.snp_ap_waiting_for_reset = true; 3993 3994 /* 3995 * Unless Creation is deferred until INIT, signal the vCPU to update 3996 * its state. 3997 */ 3998 if (request != SVM_VMGEXIT_AP_CREATE_ON_INIT) { 3999 kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu); 4000 kvm_vcpu_kick(target_vcpu); 4001 } 4002 4003 return 0; 4004 } 4005 4006 static int snp_handle_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa) 4007 { 4008 struct sev_data_snp_guest_request data = {0}; 4009 struct kvm *kvm = svm->vcpu.kvm; 4010 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 4011 sev_ret_code fw_err = 0; 4012 int ret; 4013 4014 if (!sev_snp_guest(kvm)) 4015 return -EINVAL; 4016 4017 mutex_lock(&sev->guest_req_mutex); 4018 4019 if (kvm_read_guest(kvm, req_gpa, sev->guest_req_buf, PAGE_SIZE)) { 4020 ret = -EIO; 4021 goto out_unlock; 4022 } 4023 4024 data.gctx_paddr = __psp_pa(sev->snp_context); 4025 data.req_paddr = __psp_pa(sev->guest_req_buf); 4026 data.res_paddr = __psp_pa(sev->guest_resp_buf); 4027 4028 /* 4029 * Firmware failures are propagated on to guest, but any other failure 4030 * condition along the way should be reported to userspace. E.g. if 4031 * the PSP is dead and commands are timing out. 4032 */ 4033 ret = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &fw_err); 4034 if (ret && !fw_err) 4035 goto out_unlock; 4036 4037 if (kvm_write_guest(kvm, resp_gpa, sev->guest_resp_buf, PAGE_SIZE)) { 4038 ret = -EIO; 4039 goto out_unlock; 4040 } 4041 4042 /* No action is requested *from KVM* if there was a firmware error. */ 4043 svm_vmgexit_no_action(svm, SNP_GUEST_ERR(0, fw_err)); 4044 4045 ret = 1; /* resume guest */ 4046 4047 out_unlock: 4048 mutex_unlock(&sev->guest_req_mutex); 4049 return ret; 4050 } 4051 4052 static int snp_handle_ext_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa) 4053 { 4054 struct kvm *kvm = svm->vcpu.kvm; 4055 u8 msg_type; 4056 4057 if (!sev_snp_guest(kvm)) 4058 return -EINVAL; 4059 4060 if (kvm_read_guest(kvm, req_gpa + offsetof(struct snp_guest_msg_hdr, msg_type), 4061 &msg_type, 1)) 4062 return -EIO; 4063 4064 /* 4065 * As per GHCB spec, requests of type MSG_REPORT_REQ also allow for 4066 * additional certificate data to be provided alongside the attestation 4067 * report via the guest-provided data pages indicated by RAX/RBX. The 4068 * certificate data is optional and requires additional KVM enablement 4069 * to provide an interface for userspace to provide it, but KVM still 4070 * needs to be able to handle extended guest requests either way. So 4071 * provide a stub implementation that will always return an empty 4072 * certificate table in the guest-provided data pages. 4073 */ 4074 if (msg_type == SNP_MSG_REPORT_REQ) { 4075 struct kvm_vcpu *vcpu = &svm->vcpu; 4076 u64 data_npages; 4077 gpa_t data_gpa; 4078 4079 if (!kvm_ghcb_rax_is_valid(svm) || !kvm_ghcb_rbx_is_valid(svm)) 4080 goto request_invalid; 4081 4082 data_gpa = vcpu->arch.regs[VCPU_REGS_RAX]; 4083 data_npages = vcpu->arch.regs[VCPU_REGS_RBX]; 4084 4085 if (!PAGE_ALIGNED(data_gpa)) 4086 goto request_invalid; 4087 4088 /* 4089 * As per GHCB spec (see "SNP Extended Guest Request"), the 4090 * certificate table is terminated by 24-bytes of zeroes. 4091 */ 4092 if (data_npages && kvm_clear_guest(kvm, data_gpa, 24)) 4093 return -EIO; 4094 } 4095 4096 return snp_handle_guest_req(svm, req_gpa, resp_gpa); 4097 4098 request_invalid: 4099 svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT); 4100 return 1; /* resume guest */ 4101 } 4102 4103 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) 4104 { 4105 struct vmcb_control_area *control = &svm->vmcb->control; 4106 struct kvm_vcpu *vcpu = &svm->vcpu; 4107 struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm); 4108 u64 ghcb_info; 4109 int ret = 1; 4110 4111 ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK; 4112 4113 trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id, 4114 control->ghcb_gpa); 4115 4116 switch (ghcb_info) { 4117 case GHCB_MSR_SEV_INFO_REQ: 4118 set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version, 4119 GHCB_VERSION_MIN, 4120 sev_enc_bit)); 4121 break; 4122 case GHCB_MSR_CPUID_REQ: { 4123 u64 cpuid_fn, cpuid_reg, cpuid_value; 4124 4125 cpuid_fn = get_ghcb_msr_bits(svm, 4126 GHCB_MSR_CPUID_FUNC_MASK, 4127 GHCB_MSR_CPUID_FUNC_POS); 4128 4129 /* Initialize the registers needed by the CPUID intercept */ 4130 vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn; 4131 vcpu->arch.regs[VCPU_REGS_RCX] = 0; 4132 4133 ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID); 4134 if (!ret) { 4135 /* Error, keep GHCB MSR value as-is */ 4136 break; 4137 } 4138 4139 cpuid_reg = get_ghcb_msr_bits(svm, 4140 GHCB_MSR_CPUID_REG_MASK, 4141 GHCB_MSR_CPUID_REG_POS); 4142 if (cpuid_reg == 0) 4143 cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX]; 4144 else if (cpuid_reg == 1) 4145 cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX]; 4146 else if (cpuid_reg == 2) 4147 cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX]; 4148 else 4149 cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX]; 4150 4151 set_ghcb_msr_bits(svm, cpuid_value, 4152 GHCB_MSR_CPUID_VALUE_MASK, 4153 GHCB_MSR_CPUID_VALUE_POS); 4154 4155 set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP, 4156 GHCB_MSR_INFO_MASK, 4157 GHCB_MSR_INFO_POS); 4158 break; 4159 } 4160 case GHCB_MSR_AP_RESET_HOLD_REQ: 4161 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_MSR_PROTO; 4162 ret = kvm_emulate_ap_reset_hold(&svm->vcpu); 4163 4164 /* 4165 * Preset the result to a non-SIPI return and then only set 4166 * the result to non-zero when delivering a SIPI. 4167 */ 4168 set_ghcb_msr_bits(svm, 0, 4169 GHCB_MSR_AP_RESET_HOLD_RESULT_MASK, 4170 GHCB_MSR_AP_RESET_HOLD_RESULT_POS); 4171 4172 set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP, 4173 GHCB_MSR_INFO_MASK, 4174 GHCB_MSR_INFO_POS); 4175 break; 4176 case GHCB_MSR_HV_FT_REQ: 4177 set_ghcb_msr_bits(svm, GHCB_HV_FT_SUPPORTED, 4178 GHCB_MSR_HV_FT_MASK, GHCB_MSR_HV_FT_POS); 4179 set_ghcb_msr_bits(svm, GHCB_MSR_HV_FT_RESP, 4180 GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS); 4181 break; 4182 case GHCB_MSR_PREF_GPA_REQ: 4183 if (!sev_snp_guest(vcpu->kvm)) 4184 goto out_terminate; 4185 4186 set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_NONE, GHCB_MSR_GPA_VALUE_MASK, 4187 GHCB_MSR_GPA_VALUE_POS); 4188 set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_RESP, GHCB_MSR_INFO_MASK, 4189 GHCB_MSR_INFO_POS); 4190 break; 4191 case GHCB_MSR_REG_GPA_REQ: { 4192 u64 gfn; 4193 4194 if (!sev_snp_guest(vcpu->kvm)) 4195 goto out_terminate; 4196 4197 gfn = get_ghcb_msr_bits(svm, GHCB_MSR_GPA_VALUE_MASK, 4198 GHCB_MSR_GPA_VALUE_POS); 4199 4200 svm->sev_es.ghcb_registered_gpa = gfn_to_gpa(gfn); 4201 4202 set_ghcb_msr_bits(svm, gfn, GHCB_MSR_GPA_VALUE_MASK, 4203 GHCB_MSR_GPA_VALUE_POS); 4204 set_ghcb_msr_bits(svm, GHCB_MSR_REG_GPA_RESP, GHCB_MSR_INFO_MASK, 4205 GHCB_MSR_INFO_POS); 4206 break; 4207 } 4208 case GHCB_MSR_PSC_REQ: 4209 if (!sev_snp_guest(vcpu->kvm)) 4210 goto out_terminate; 4211 4212 ret = snp_begin_psc_msr(svm, control->ghcb_gpa); 4213 break; 4214 case GHCB_MSR_TERM_REQ: { 4215 u64 reason_set, reason_code; 4216 4217 reason_set = get_ghcb_msr_bits(svm, 4218 GHCB_MSR_TERM_REASON_SET_MASK, 4219 GHCB_MSR_TERM_REASON_SET_POS); 4220 reason_code = get_ghcb_msr_bits(svm, 4221 GHCB_MSR_TERM_REASON_MASK, 4222 GHCB_MSR_TERM_REASON_POS); 4223 pr_info("SEV-ES guest requested termination: %#llx:%#llx\n", 4224 reason_set, reason_code); 4225 4226 goto out_terminate; 4227 } 4228 default: 4229 /* Error, keep GHCB MSR value as-is */ 4230 break; 4231 } 4232 4233 trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id, 4234 control->ghcb_gpa, ret); 4235 4236 return ret; 4237 4238 out_terminate: 4239 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT; 4240 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM; 4241 vcpu->run->system_event.ndata = 1; 4242 vcpu->run->system_event.data[0] = control->ghcb_gpa; 4243 4244 return 0; 4245 } 4246 4247 int sev_handle_vmgexit(struct kvm_vcpu *vcpu) 4248 { 4249 struct vcpu_svm *svm = to_svm(vcpu); 4250 struct vmcb_control_area *control = &svm->vmcb->control; 4251 u64 ghcb_gpa, exit_code; 4252 int ret; 4253 4254 /* Validate the GHCB */ 4255 ghcb_gpa = control->ghcb_gpa; 4256 if (ghcb_gpa & GHCB_MSR_INFO_MASK) 4257 return sev_handle_vmgexit_msr_protocol(svm); 4258 4259 if (!ghcb_gpa) { 4260 vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n"); 4261 4262 /* Without a GHCB, just return right back to the guest */ 4263 return 1; 4264 } 4265 4266 if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) { 4267 /* Unable to map GHCB from guest */ 4268 vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n", 4269 ghcb_gpa); 4270 4271 /* Without a GHCB, just return right back to the guest */ 4272 return 1; 4273 } 4274 4275 svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva; 4276 4277 trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb); 4278 4279 sev_es_sync_from_ghcb(svm); 4280 4281 /* SEV-SNP guest requires that the GHCB GPA must be registered */ 4282 if (sev_snp_guest(svm->vcpu.kvm) && !ghcb_gpa_is_registered(svm, ghcb_gpa)) { 4283 vcpu_unimpl(&svm->vcpu, "vmgexit: GHCB GPA [%#llx] is not registered.\n", ghcb_gpa); 4284 return -EINVAL; 4285 } 4286 4287 ret = sev_es_validate_vmgexit(svm); 4288 if (ret) 4289 return ret; 4290 4291 svm_vmgexit_success(svm, 0); 4292 4293 exit_code = kvm_ghcb_get_sw_exit_code(control); 4294 switch (exit_code) { 4295 case SVM_VMGEXIT_MMIO_READ: 4296 ret = setup_vmgexit_scratch(svm, true, control->exit_info_2); 4297 if (ret) 4298 break; 4299 4300 ret = kvm_sev_es_mmio_read(vcpu, 4301 control->exit_info_1, 4302 control->exit_info_2, 4303 svm->sev_es.ghcb_sa); 4304 break; 4305 case SVM_VMGEXIT_MMIO_WRITE: 4306 ret = setup_vmgexit_scratch(svm, false, control->exit_info_2); 4307 if (ret) 4308 break; 4309 4310 ret = kvm_sev_es_mmio_write(vcpu, 4311 control->exit_info_1, 4312 control->exit_info_2, 4313 svm->sev_es.ghcb_sa); 4314 break; 4315 case SVM_VMGEXIT_NMI_COMPLETE: 4316 ++vcpu->stat.nmi_window_exits; 4317 svm->nmi_masked = false; 4318 kvm_make_request(KVM_REQ_EVENT, vcpu); 4319 ret = 1; 4320 break; 4321 case SVM_VMGEXIT_AP_HLT_LOOP: 4322 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NAE_EVENT; 4323 ret = kvm_emulate_ap_reset_hold(vcpu); 4324 break; 4325 case SVM_VMGEXIT_AP_JUMP_TABLE: { 4326 struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm); 4327 4328 switch (control->exit_info_1) { 4329 case 0: 4330 /* Set AP jump table address */ 4331 sev->ap_jump_table = control->exit_info_2; 4332 break; 4333 case 1: 4334 /* Get AP jump table address */ 4335 svm_vmgexit_success(svm, sev->ap_jump_table); 4336 break; 4337 default: 4338 pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n", 4339 control->exit_info_1); 4340 svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT); 4341 } 4342 4343 ret = 1; 4344 break; 4345 } 4346 case SVM_VMGEXIT_HV_FEATURES: 4347 svm_vmgexit_success(svm, GHCB_HV_FT_SUPPORTED); 4348 ret = 1; 4349 break; 4350 case SVM_VMGEXIT_TERM_REQUEST: 4351 pr_info("SEV-ES guest requested termination: reason %#llx info %#llx\n", 4352 control->exit_info_1, control->exit_info_2); 4353 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT; 4354 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM; 4355 vcpu->run->system_event.ndata = 1; 4356 vcpu->run->system_event.data[0] = control->ghcb_gpa; 4357 break; 4358 case SVM_VMGEXIT_PSC: 4359 ret = setup_vmgexit_scratch(svm, true, control->exit_info_2); 4360 if (ret) 4361 break; 4362 4363 ret = snp_begin_psc(svm, svm->sev_es.ghcb_sa); 4364 break; 4365 case SVM_VMGEXIT_AP_CREATION: 4366 ret = sev_snp_ap_creation(svm); 4367 if (ret) { 4368 svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT); 4369 } 4370 4371 ret = 1; 4372 break; 4373 case SVM_VMGEXIT_GUEST_REQUEST: 4374 ret = snp_handle_guest_req(svm, control->exit_info_1, control->exit_info_2); 4375 break; 4376 case SVM_VMGEXIT_EXT_GUEST_REQUEST: 4377 ret = snp_handle_ext_guest_req(svm, control->exit_info_1, control->exit_info_2); 4378 break; 4379 case SVM_VMGEXIT_UNSUPPORTED_EVENT: 4380 vcpu_unimpl(vcpu, 4381 "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n", 4382 control->exit_info_1, control->exit_info_2); 4383 ret = -EINVAL; 4384 break; 4385 default: 4386 ret = svm_invoke_exit_handler(vcpu, exit_code); 4387 } 4388 4389 return ret; 4390 } 4391 4392 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in) 4393 { 4394 int count; 4395 int bytes; 4396 int r; 4397 4398 if (svm->vmcb->control.exit_info_2 > INT_MAX) 4399 return -EINVAL; 4400 4401 count = svm->vmcb->control.exit_info_2; 4402 if (unlikely(check_mul_overflow(count, size, &bytes))) 4403 return -EINVAL; 4404 4405 r = setup_vmgexit_scratch(svm, in, bytes); 4406 if (r) 4407 return r; 4408 4409 return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa, 4410 count, in); 4411 } 4412 4413 static void sev_es_vcpu_after_set_cpuid(struct vcpu_svm *svm) 4414 { 4415 struct kvm_vcpu *vcpu = &svm->vcpu; 4416 4417 if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) { 4418 bool v_tsc_aux = guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) || 4419 guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID); 4420 4421 set_msr_interception(vcpu, svm->msrpm, MSR_TSC_AUX, v_tsc_aux, v_tsc_aux); 4422 } 4423 4424 /* 4425 * For SEV-ES, accesses to MSR_IA32_XSS should not be intercepted if 4426 * the host/guest supports its use. 4427 * 4428 * KVM treats the guest as being capable of using XSAVES even if XSAVES 4429 * isn't enabled in guest CPUID as there is no intercept for XSAVES, 4430 * i.e. the guest can use XSAVES/XRSTOR to read/write XSS if XSAVE is 4431 * exposed to the guest and XSAVES is supported in hardware. Condition 4432 * full XSS passthrough on the guest being able to use XSAVES *and* 4433 * XSAVES being exposed to the guest so that KVM can at least honor 4434 * guest CPUID for RDMSR and WRMSR. 4435 */ 4436 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) && 4437 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES)) 4438 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 1, 1); 4439 else 4440 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 0, 0); 4441 } 4442 4443 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm) 4444 { 4445 struct kvm_vcpu *vcpu = &svm->vcpu; 4446 struct kvm_cpuid_entry2 *best; 4447 4448 /* For sev guests, the memory encryption bit is not reserved in CR3. */ 4449 best = kvm_find_cpuid_entry(vcpu, 0x8000001F); 4450 if (best) 4451 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f)); 4452 4453 if (sev_es_guest(svm->vcpu.kvm)) 4454 sev_es_vcpu_after_set_cpuid(svm); 4455 } 4456 4457 static void sev_es_init_vmcb(struct vcpu_svm *svm) 4458 { 4459 struct vmcb *vmcb = svm->vmcb01.ptr; 4460 struct kvm_vcpu *vcpu = &svm->vcpu; 4461 4462 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE; 4463 4464 /* 4465 * An SEV-ES guest requires a VMSA area that is a separate from the 4466 * VMCB page. Do not include the encryption mask on the VMSA physical 4467 * address since hardware will access it using the guest key. Note, 4468 * the VMSA will be NULL if this vCPU is the destination for intrahost 4469 * migration, and will be copied later. 4470 */ 4471 if (svm->sev_es.vmsa && !svm->sev_es.snp_has_guest_vmsa) 4472 svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa); 4473 4474 /* Can't intercept CR register access, HV can't modify CR registers */ 4475 svm_clr_intercept(svm, INTERCEPT_CR0_READ); 4476 svm_clr_intercept(svm, INTERCEPT_CR4_READ); 4477 svm_clr_intercept(svm, INTERCEPT_CR8_READ); 4478 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE); 4479 svm_clr_intercept(svm, INTERCEPT_CR4_WRITE); 4480 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE); 4481 4482 svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0); 4483 4484 /* Track EFER/CR register changes */ 4485 svm_set_intercept(svm, TRAP_EFER_WRITE); 4486 svm_set_intercept(svm, TRAP_CR0_WRITE); 4487 svm_set_intercept(svm, TRAP_CR4_WRITE); 4488 svm_set_intercept(svm, TRAP_CR8_WRITE); 4489 4490 vmcb->control.intercepts[INTERCEPT_DR] = 0; 4491 if (!sev_vcpu_has_debug_swap(svm)) { 4492 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ); 4493 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE); 4494 recalc_intercepts(svm); 4495 } else { 4496 /* 4497 * Disable #DB intercept iff DebugSwap is enabled. KVM doesn't 4498 * allow debugging SEV-ES guests, and enables DebugSwap iff 4499 * NO_NESTED_DATA_BP is supported, so there's no reason to 4500 * intercept #DB when DebugSwap is enabled. For simplicity 4501 * with respect to guest debug, intercept #DB for other VMs 4502 * even if NO_NESTED_DATA_BP is supported, i.e. even if the 4503 * guest can't DoS the CPU with infinite #DB vectoring. 4504 */ 4505 clr_exception_intercept(svm, DB_VECTOR); 4506 } 4507 4508 /* Can't intercept XSETBV, HV can't modify XCR0 directly */ 4509 svm_clr_intercept(svm, INTERCEPT_XSETBV); 4510 4511 /* Clear intercepts on selected MSRs */ 4512 set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1); 4513 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1); 4514 } 4515 4516 void sev_init_vmcb(struct vcpu_svm *svm) 4517 { 4518 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE; 4519 clr_exception_intercept(svm, UD_VECTOR); 4520 4521 /* 4522 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as 4523 * KVM can't decrypt guest memory to decode the faulting instruction. 4524 */ 4525 clr_exception_intercept(svm, GP_VECTOR); 4526 4527 if (sev_es_guest(svm->vcpu.kvm)) 4528 sev_es_init_vmcb(svm); 4529 } 4530 4531 void sev_es_vcpu_reset(struct vcpu_svm *svm) 4532 { 4533 struct kvm_vcpu *vcpu = &svm->vcpu; 4534 struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm); 4535 4536 /* 4537 * Set the GHCB MSR value as per the GHCB specification when emulating 4538 * vCPU RESET for an SEV-ES guest. 4539 */ 4540 set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version, 4541 GHCB_VERSION_MIN, 4542 sev_enc_bit)); 4543 4544 mutex_init(&svm->sev_es.snp_vmsa_mutex); 4545 } 4546 4547 void sev_es_prepare_switch_to_guest(struct vcpu_svm *svm, struct sev_es_save_area *hostsa) 4548 { 4549 struct kvm *kvm = svm->vcpu.kvm; 4550 4551 /* 4552 * All host state for SEV-ES guests is categorized into three swap types 4553 * based on how it is handled by hardware during a world switch: 4554 * 4555 * A: VMRUN: Host state saved in host save area 4556 * VMEXIT: Host state loaded from host save area 4557 * 4558 * B: VMRUN: Host state _NOT_ saved in host save area 4559 * VMEXIT: Host state loaded from host save area 4560 * 4561 * C: VMRUN: Host state _NOT_ saved in host save area 4562 * VMEXIT: Host state initialized to default(reset) values 4563 * 4564 * Manually save type-B state, i.e. state that is loaded by VMEXIT but 4565 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed 4566 * by common SVM code). 4567 */ 4568 hostsa->xcr0 = kvm_host.xcr0; 4569 hostsa->pkru = read_pkru(); 4570 hostsa->xss = kvm_host.xss; 4571 4572 /* 4573 * If DebugSwap is enabled, debug registers are loaded but NOT saved by 4574 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU does 4575 * not save or load debug registers. Sadly, KVM can't prevent SNP 4576 * guests from lying about DebugSwap on secondary vCPUs, i.e. the 4577 * SEV_FEATURES provided at "AP Create" isn't guaranteed to match what 4578 * the guest has actually enabled (or not!) in the VMSA. 4579 * 4580 * If DebugSwap is *possible*, save the masks so that they're restored 4581 * if the guest enables DebugSwap. But for the DRs themselves, do NOT 4582 * rely on the CPU to restore the host values; KVM will restore them as 4583 * needed in common code, via hw_breakpoint_restore(). Note, KVM does 4584 * NOT support virtualizing Breakpoint Extensions, i.e. the mask MSRs 4585 * don't need to be restored per se, KVM just needs to ensure they are 4586 * loaded with the correct values *if* the CPU writes the MSRs. 4587 */ 4588 if (sev_vcpu_has_debug_swap(svm) || 4589 (sev_snp_guest(kvm) && cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP))) { 4590 hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0); 4591 hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1); 4592 hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2); 4593 hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3); 4594 } 4595 } 4596 4597 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector) 4598 { 4599 struct vcpu_svm *svm = to_svm(vcpu); 4600 4601 /* First SIPI: Use the values as initially set by the VMM */ 4602 if (!svm->sev_es.received_first_sipi) { 4603 svm->sev_es.received_first_sipi = true; 4604 return; 4605 } 4606 4607 /* Subsequent SIPI */ 4608 switch (svm->sev_es.ap_reset_hold_type) { 4609 case AP_RESET_HOLD_NAE_EVENT: 4610 /* 4611 * Return from an AP Reset Hold VMGEXIT, where the guest will 4612 * set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value. 4613 */ 4614 svm_vmgexit_success(svm, 1); 4615 break; 4616 case AP_RESET_HOLD_MSR_PROTO: 4617 /* 4618 * Return from an AP Reset Hold VMGEXIT, where the guest will 4619 * set the CS and RIP. Set GHCB data field to a non-zero value. 4620 */ 4621 set_ghcb_msr_bits(svm, 1, 4622 GHCB_MSR_AP_RESET_HOLD_RESULT_MASK, 4623 GHCB_MSR_AP_RESET_HOLD_RESULT_POS); 4624 4625 set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP, 4626 GHCB_MSR_INFO_MASK, 4627 GHCB_MSR_INFO_POS); 4628 break; 4629 default: 4630 break; 4631 } 4632 } 4633 4634 struct page *snp_safe_alloc_page_node(int node, gfp_t gfp) 4635 { 4636 unsigned long pfn; 4637 struct page *p; 4638 4639 if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP)) 4640 return alloc_pages_node(node, gfp | __GFP_ZERO, 0); 4641 4642 /* 4643 * Allocate an SNP-safe page to workaround the SNP erratum where 4644 * the CPU will incorrectly signal an RMP violation #PF if a 4645 * hugepage (2MB or 1GB) collides with the RMP entry of a 4646 * 2MB-aligned VMCB, VMSA, or AVIC backing page. 4647 * 4648 * Allocate one extra page, choose a page which is not 4649 * 2MB-aligned, and free the other. 4650 */ 4651 p = alloc_pages_node(node, gfp | __GFP_ZERO, 1); 4652 if (!p) 4653 return NULL; 4654 4655 split_page(p, 1); 4656 4657 pfn = page_to_pfn(p); 4658 if (IS_ALIGNED(pfn, PTRS_PER_PMD)) 4659 __free_page(p++); 4660 else 4661 __free_page(p + 1); 4662 4663 return p; 4664 } 4665 4666 void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code) 4667 { 4668 struct kvm_memory_slot *slot; 4669 struct kvm *kvm = vcpu->kvm; 4670 int order, rmp_level, ret; 4671 struct page *page; 4672 bool assigned; 4673 kvm_pfn_t pfn; 4674 gfn_t gfn; 4675 4676 gfn = gpa >> PAGE_SHIFT; 4677 4678 /* 4679 * The only time RMP faults occur for shared pages is when the guest is 4680 * triggering an RMP fault for an implicit page-state change from 4681 * shared->private. Implicit page-state changes are forwarded to 4682 * userspace via KVM_EXIT_MEMORY_FAULT events, however, so RMP faults 4683 * for shared pages should not end up here. 4684 */ 4685 if (!kvm_mem_is_private(kvm, gfn)) { 4686 pr_warn_ratelimited("SEV: Unexpected RMP fault for non-private GPA 0x%llx\n", 4687 gpa); 4688 return; 4689 } 4690 4691 slot = gfn_to_memslot(kvm, gfn); 4692 if (!kvm_slot_can_be_private(slot)) { 4693 pr_warn_ratelimited("SEV: Unexpected RMP fault, non-private slot for GPA 0x%llx\n", 4694 gpa); 4695 return; 4696 } 4697 4698 ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order); 4699 if (ret) { 4700 pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n", 4701 gpa); 4702 return; 4703 } 4704 4705 ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level); 4706 if (ret || !assigned) { 4707 pr_warn_ratelimited("SEV: Unexpected RMP fault, no assigned RMP entry found for GPA 0x%llx PFN 0x%llx error %d\n", 4708 gpa, pfn, ret); 4709 goto out_no_trace; 4710 } 4711 4712 /* 4713 * There are 2 cases where a PSMASH may be needed to resolve an #NPF 4714 * with PFERR_GUEST_RMP_BIT set: 4715 * 4716 * 1) RMPADJUST/PVALIDATE can trigger an #NPF with PFERR_GUEST_SIZEM 4717 * bit set if the guest issues them with a smaller granularity than 4718 * what is indicated by the page-size bit in the 2MB RMP entry for 4719 * the PFN that backs the GPA. 4720 * 4721 * 2) Guest access via NPT can trigger an #NPF if the NPT mapping is 4722 * smaller than what is indicated by the 2MB RMP entry for the PFN 4723 * that backs the GPA. 4724 * 4725 * In both these cases, the corresponding 2M RMP entry needs to 4726 * be PSMASH'd to 512 4K RMP entries. If the RMP entry is already 4727 * split into 4K RMP entries, then this is likely a spurious case which 4728 * can occur when there are concurrent accesses by the guest to a 2MB 4729 * GPA range that is backed by a 2MB-aligned PFN who's RMP entry is in 4730 * the process of being PMASH'd into 4K entries. These cases should 4731 * resolve automatically on subsequent accesses, so just ignore them 4732 * here. 4733 */ 4734 if (rmp_level == PG_LEVEL_4K) 4735 goto out; 4736 4737 ret = snp_rmptable_psmash(pfn); 4738 if (ret) { 4739 /* 4740 * Look it up again. If it's 4K now then the PSMASH may have 4741 * raced with another process and the issue has already resolved 4742 * itself. 4743 */ 4744 if (!snp_lookup_rmpentry(pfn, &assigned, &rmp_level) && 4745 assigned && rmp_level == PG_LEVEL_4K) 4746 goto out; 4747 4748 pr_warn_ratelimited("SEV: Unable to split RMP entry for GPA 0x%llx PFN 0x%llx ret %d\n", 4749 gpa, pfn, ret); 4750 } 4751 4752 kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD); 4753 out: 4754 trace_kvm_rmp_fault(vcpu, gpa, pfn, error_code, rmp_level, ret); 4755 out_no_trace: 4756 kvm_release_page_unused(page); 4757 } 4758 4759 static bool is_pfn_range_shared(kvm_pfn_t start, kvm_pfn_t end) 4760 { 4761 kvm_pfn_t pfn = start; 4762 4763 while (pfn < end) { 4764 int ret, rmp_level; 4765 bool assigned; 4766 4767 ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level); 4768 if (ret) { 4769 pr_warn_ratelimited("SEV: Failed to retrieve RMP entry: PFN 0x%llx GFN start 0x%llx GFN end 0x%llx RMP level %d error %d\n", 4770 pfn, start, end, rmp_level, ret); 4771 return false; 4772 } 4773 4774 if (assigned) { 4775 pr_debug("%s: overlap detected, PFN 0x%llx start 0x%llx end 0x%llx RMP level %d\n", 4776 __func__, pfn, start, end, rmp_level); 4777 return false; 4778 } 4779 4780 pfn++; 4781 } 4782 4783 return true; 4784 } 4785 4786 static u8 max_level_for_order(int order) 4787 { 4788 if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M)) 4789 return PG_LEVEL_2M; 4790 4791 return PG_LEVEL_4K; 4792 } 4793 4794 static bool is_large_rmp_possible(struct kvm *kvm, kvm_pfn_t pfn, int order) 4795 { 4796 kvm_pfn_t pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD); 4797 4798 /* 4799 * If this is a large folio, and the entire 2M range containing the 4800 * PFN is currently shared, then the entire 2M-aligned range can be 4801 * set to private via a single 2M RMP entry. 4802 */ 4803 if (max_level_for_order(order) > PG_LEVEL_4K && 4804 is_pfn_range_shared(pfn_aligned, pfn_aligned + PTRS_PER_PMD)) 4805 return true; 4806 4807 return false; 4808 } 4809 4810 int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order) 4811 { 4812 struct kvm_sev_info *sev = to_kvm_sev_info(kvm); 4813 kvm_pfn_t pfn_aligned; 4814 gfn_t gfn_aligned; 4815 int level, rc; 4816 bool assigned; 4817 4818 if (!sev_snp_guest(kvm)) 4819 return 0; 4820 4821 rc = snp_lookup_rmpentry(pfn, &assigned, &level); 4822 if (rc) { 4823 pr_err_ratelimited("SEV: Failed to look up RMP entry: GFN %llx PFN %llx error %d\n", 4824 gfn, pfn, rc); 4825 return -ENOENT; 4826 } 4827 4828 if (assigned) { 4829 pr_debug("%s: already assigned: gfn %llx pfn %llx max_order %d level %d\n", 4830 __func__, gfn, pfn, max_order, level); 4831 return 0; 4832 } 4833 4834 if (is_large_rmp_possible(kvm, pfn, max_order)) { 4835 level = PG_LEVEL_2M; 4836 pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD); 4837 gfn_aligned = ALIGN_DOWN(gfn, PTRS_PER_PMD); 4838 } else { 4839 level = PG_LEVEL_4K; 4840 pfn_aligned = pfn; 4841 gfn_aligned = gfn; 4842 } 4843 4844 rc = rmp_make_private(pfn_aligned, gfn_to_gpa(gfn_aligned), level, sev->asid, false); 4845 if (rc) { 4846 pr_err_ratelimited("SEV: Failed to update RMP entry: GFN %llx PFN %llx level %d error %d\n", 4847 gfn, pfn, level, rc); 4848 return -EINVAL; 4849 } 4850 4851 pr_debug("%s: updated: gfn %llx pfn %llx pfn_aligned %llx max_order %d level %d\n", 4852 __func__, gfn, pfn, pfn_aligned, max_order, level); 4853 4854 return 0; 4855 } 4856 4857 void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end) 4858 { 4859 kvm_pfn_t pfn; 4860 4861 if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP)) 4862 return; 4863 4864 pr_debug("%s: PFN start 0x%llx PFN end 0x%llx\n", __func__, start, end); 4865 4866 for (pfn = start; pfn < end;) { 4867 bool use_2m_update = false; 4868 int rc, rmp_level; 4869 bool assigned; 4870 4871 rc = snp_lookup_rmpentry(pfn, &assigned, &rmp_level); 4872 if (rc || !assigned) 4873 goto next_pfn; 4874 4875 use_2m_update = IS_ALIGNED(pfn, PTRS_PER_PMD) && 4876 end >= (pfn + PTRS_PER_PMD) && 4877 rmp_level > PG_LEVEL_4K; 4878 4879 /* 4880 * If an unaligned PFN corresponds to a 2M region assigned as a 4881 * large page in the RMP table, PSMASH the region into individual 4882 * 4K RMP entries before attempting to convert a 4K sub-page. 4883 */ 4884 if (!use_2m_update && rmp_level > PG_LEVEL_4K) { 4885 /* 4886 * This shouldn't fail, but if it does, report it, but 4887 * still try to update RMP entry to shared and pray this 4888 * was a spurious error that can be addressed later. 4889 */ 4890 rc = snp_rmptable_psmash(pfn); 4891 WARN_ONCE(rc, "SEV: Failed to PSMASH RMP entry for PFN 0x%llx error %d\n", 4892 pfn, rc); 4893 } 4894 4895 rc = rmp_make_shared(pfn, use_2m_update ? PG_LEVEL_2M : PG_LEVEL_4K); 4896 if (WARN_ONCE(rc, "SEV: Failed to update RMP entry for PFN 0x%llx error %d\n", 4897 pfn, rc)) 4898 goto next_pfn; 4899 4900 /* 4901 * SEV-ES avoids host/guest cache coherency issues through 4902 * WBINVD hooks issued via MMU notifiers during run-time, and 4903 * KVM's VM destroy path at shutdown. Those MMU notifier events 4904 * don't cover gmem since there is no requirement to map pages 4905 * to a HVA in order to use them for a running guest. While the 4906 * shutdown path would still likely cover things for SNP guests, 4907 * userspace may also free gmem pages during run-time via 4908 * hole-punching operations on the guest_memfd, so flush the 4909 * cache entries for these pages before free'ing them back to 4910 * the host. 4911 */ 4912 clflush_cache_range(__va(pfn_to_hpa(pfn)), 4913 use_2m_update ? PMD_SIZE : PAGE_SIZE); 4914 next_pfn: 4915 pfn += use_2m_update ? PTRS_PER_PMD : 1; 4916 cond_resched(); 4917 } 4918 } 4919 4920 int sev_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) 4921 { 4922 int level, rc; 4923 bool assigned; 4924 4925 if (!sev_snp_guest(kvm)) 4926 return 0; 4927 4928 rc = snp_lookup_rmpentry(pfn, &assigned, &level); 4929 if (rc || !assigned) 4930 return PG_LEVEL_4K; 4931 4932 return level; 4933 } 4934