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