FILE
core.c
File preview with syntax highlighting.
linux-6.19.14/arch/x86/coco/sev/core.c
1// SPDX-License-Identifier: GPL-2.0-only 2/* 3 * AMD Memory Encryption Support 4 * 5 * Copyright (C) 2019 SUSE 6 * 7 * Author: Joerg Roedel <jroedel@suse.de> 8 */ 9 10#define pr_fmt(fmt) "SEV: " fmt 11 12#include <linux/sched/debug.h> /* For show_regs() */ 13#include <linux/percpu-defs.h> 14#include <linux/cc_platform.h> 15#include <linux/printk.h> 16#include <linux/mm_types.h> 17#include <linux/set_memory.h> 18#include <linux/memblock.h> 19#include <linux/kernel.h> 20#include <linux/mm.h> 21#include <linux/cpumask.h> 22#include <linux/efi.h> 23#include <linux/platform_device.h> 24#include <linux/io.h> 25#include <linux/psp-sev.h> 26#include <linux/dmi.h> 27#include <uapi/linux/sev-guest.h> 28#include <crypto/gcm.h> 29 30#include <asm/init.h> 31#include <asm/cpu_entry_area.h> 32#include <asm/stacktrace.h> 33#include <asm/sev.h> 34#include <asm/sev-internal.h> 35#include <asm/insn-eval.h> 36#include <asm/fpu/xcr.h> 37#include <asm/processor.h> 38#include <asm/realmode.h> 39#include <asm/setup.h> 40#include <asm/traps.h> 41#include <asm/svm.h> 42#include <asm/smp.h> 43#include <asm/cpu.h> 44#include <asm/apic.h> 45#include <asm/cpuid/api.h> 46#include <asm/cmdline.h> 47#include <asm/msr.h> 48 49/* Bitmap of SEV features supported by the hypervisor */ 50u64 sev_hv_features __ro_after_init; 51SYM_PIC_ALIAS(sev_hv_features); 52 53/* Secrets page physical address from the CC blob */ 54u64 sev_secrets_pa __ro_after_init; 55SYM_PIC_ALIAS(sev_secrets_pa); 56 57/* For early boot SVSM communication */ 58struct svsm_ca boot_svsm_ca_page __aligned(PAGE_SIZE); 59SYM_PIC_ALIAS(boot_svsm_ca_page); 60 61/* 62 * SVSM related information: 63 * During boot, the page tables are set up as identity mapped and later 64 * changed to use kernel virtual addresses. Maintain separate virtual and 65 * physical addresses for the CAA to allow SVSM functions to be used during 66 * early boot, both with identity mapped virtual addresses and proper kernel 67 * virtual addresses. 68 */ 69u64 boot_svsm_caa_pa __ro_after_init; 70SYM_PIC_ALIAS(boot_svsm_caa_pa); 71 72DEFINE_PER_CPU(struct svsm_ca *, svsm_caa); 73DEFINE_PER_CPU(u64, svsm_caa_pa); 74 75static inline struct svsm_ca *svsm_get_caa(void) 76{ 77 if (sev_cfg.use_cas) 78 return this_cpu_read(svsm_caa); 79 else 80 return rip_rel_ptr(&boot_svsm_ca_page); 81} 82 83static inline u64 svsm_get_caa_pa(void) 84{ 85 if (sev_cfg.use_cas) 86 return this_cpu_read(svsm_caa_pa); 87 else 88 return boot_svsm_caa_pa; 89} 90 91/* AP INIT values as documented in the APM2 section "Processor Initialization State" */ 92#define AP_INIT_CS_LIMIT 0xffff 93#define AP_INIT_DS_LIMIT 0xffff 94#define AP_INIT_LDTR_LIMIT 0xffff 95#define AP_INIT_GDTR_LIMIT 0xffff 96#define AP_INIT_IDTR_LIMIT 0xffff 97#define AP_INIT_TR_LIMIT 0xffff 98#define AP_INIT_RFLAGS_DEFAULT 0x2 99#define AP_INIT_DR6_DEFAULT 0xffff0ff0 100#define AP_INIT_GPAT_DEFAULT 0x0007040600070406ULL 101#define AP_INIT_XCR0_DEFAULT 0x1 102#define AP_INIT_X87_FTW_DEFAULT 0x5555 103#define AP_INIT_X87_FCW_DEFAULT 0x0040 104#define AP_INIT_CR0_DEFAULT 0x60000010 105#define AP_INIT_MXCSR_DEFAULT 0x1f80 106 107static const char * const sev_status_feat_names[] = { 108 [MSR_AMD64_SEV_ENABLED_BIT] = "SEV", 109 [MSR_AMD64_SEV_ES_ENABLED_BIT] = "SEV-ES", 110 [MSR_AMD64_SEV_SNP_ENABLED_BIT] = "SEV-SNP", 111 [MSR_AMD64_SNP_VTOM_BIT] = "vTom", 112 [MSR_AMD64_SNP_REFLECT_VC_BIT] = "ReflectVC", 113 [MSR_AMD64_SNP_RESTRICTED_INJ_BIT] = "RI", 114 [MSR_AMD64_SNP_ALT_INJ_BIT] = "AI", 115 [MSR_AMD64_SNP_DEBUG_SWAP_BIT] = "DebugSwap", 116 [MSR_AMD64_SNP_PREVENT_HOST_IBS_BIT] = "NoHostIBS", 117 [MSR_AMD64_SNP_BTB_ISOLATION_BIT] = "BTBIsol", 118 [MSR_AMD64_SNP_VMPL_SSS_BIT] = "VmplSSS", 119 [MSR_AMD64_SNP_SECURE_TSC_BIT] = "SecureTSC", 120 [MSR_AMD64_SNP_VMGEXIT_PARAM_BIT] = "VMGExitParam", 121 [MSR_AMD64_SNP_IBS_VIRT_BIT] = "IBSVirt", 122 [MSR_AMD64_SNP_VMSA_REG_PROT_BIT] = "VMSARegProt", 123 [MSR_AMD64_SNP_SMT_PROT_BIT] = "SMTProt", 124 [MSR_AMD64_SNP_SECURE_AVIC_BIT] = "SecureAVIC", 125 [MSR_AMD64_SNP_IBPB_ON_ENTRY_BIT] = "IBPBOnEntry", 126}; 127 128/* 129 * For Secure TSC guests, the BSP fetches TSC_INFO using SNP guest messaging and 130 * initializes snp_tsc_scale and snp_tsc_offset. These values are replicated 131 * across the APs VMSA fields (TSC_SCALE and TSC_OFFSET). 132 */ 133static u64 snp_tsc_scale __ro_after_init; 134static u64 snp_tsc_offset __ro_after_init; 135static unsigned long snp_tsc_freq_khz __ro_after_init; 136 137DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data); 138DEFINE_PER_CPU(struct sev_es_save_area *, sev_vmsa); 139 140/* 141 * SVSM related information: 142 * When running under an SVSM, the VMPL that Linux is executing at must be 143 * non-zero. The VMPL is therefore used to indicate the presence of an SVSM. 144 */ 145u8 snp_vmpl __ro_after_init; 146EXPORT_SYMBOL_GPL(snp_vmpl); 147SYM_PIC_ALIAS(snp_vmpl); 148 149/* 150 * Since feature negotiation related variables are set early in the boot 151 * process they must reside in the .data section so as not to be zeroed 152 * out when the .bss section is later cleared. 153 * 154 * GHCB protocol version negotiated with the hypervisor. 155 */ 156u16 ghcb_version __ro_after_init; 157SYM_PIC_ALIAS(ghcb_version); 158 159/* For early boot hypervisor communication in SEV-ES enabled guests */ 160static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE); 161 162/* 163 * Needs to be in the .data section because we need it NULL before bss is 164 * cleared 165 */ 166struct ghcb *boot_ghcb __section(".data"); 167 168static u64 __init get_snp_jump_table_addr(void) 169{ 170 struct snp_secrets_page *secrets; 171 void __iomem *mem; 172 u64 addr; 173 174 mem = ioremap_encrypted(sev_secrets_pa, PAGE_SIZE); 175 if (!mem) { 176 pr_err("Unable to locate AP jump table address: failed to map the SNP secrets page.\n"); 177 return 0; 178 } 179 180 secrets = (__force struct snp_secrets_page *)mem; 181 182 addr = secrets->os_area.ap_jump_table_pa; 183 iounmap(mem); 184 185 return addr; 186} 187 188static u64 __init get_jump_table_addr(void) 189{ 190 struct ghcb_state state; 191 unsigned long flags; 192 struct ghcb *ghcb; 193 u64 ret = 0; 194 195 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 196 return get_snp_jump_table_addr(); 197 198 local_irq_save(flags); 199 200 ghcb = __sev_get_ghcb(&state); 201 202 vc_ghcb_invalidate(ghcb); 203 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE); 204 ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE); 205 ghcb_set_sw_exit_info_2(ghcb, 0); 206 207 sev_es_wr_ghcb_msr(__pa(ghcb)); 208 VMGEXIT(); 209 210 if (ghcb_sw_exit_info_1_is_valid(ghcb) && 211 ghcb_sw_exit_info_2_is_valid(ghcb)) 212 ret = ghcb->save.sw_exit_info_2; 213 214 __sev_put_ghcb(&state); 215 216 local_irq_restore(flags); 217 218 return ret; 219} 220 221static int svsm_perform_ghcb_protocol(struct ghcb *ghcb, struct svsm_call *call) 222{ 223 struct es_em_ctxt ctxt; 224 u8 pending = 0; 225 226 vc_ghcb_invalidate(ghcb); 227 228 /* 229 * Fill in protocol and format specifiers. This can be called very early 230 * in the boot, so use rip-relative references as needed. 231 */ 232 ghcb->protocol_version = ghcb_version; 233 ghcb->ghcb_usage = GHCB_DEFAULT_USAGE; 234 235 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_SNP_RUN_VMPL); 236 ghcb_set_sw_exit_info_1(ghcb, 0); 237 ghcb_set_sw_exit_info_2(ghcb, 0); 238 239 sev_es_wr_ghcb_msr(__pa(ghcb)); 240 241 svsm_issue_call(call, &pending); 242 243 if (pending) 244 return -EINVAL; 245 246 switch (verify_exception_info(ghcb, &ctxt)) { 247 case ES_OK: 248 break; 249 case ES_EXCEPTION: 250 vc_forward_exception(&ctxt); 251 fallthrough; 252 default: 253 return -EINVAL; 254 } 255 256 return svsm_process_result_codes(call); 257} 258 259static int svsm_perform_call_protocol(struct svsm_call *call) 260{ 261 struct ghcb_state state; 262 unsigned long flags; 263 struct ghcb *ghcb; 264 int ret; 265 266 flags = native_local_irq_save(); 267 268 if (sev_cfg.ghcbs_initialized) 269 ghcb = __sev_get_ghcb(&state); 270 else if (boot_ghcb) 271 ghcb = boot_ghcb; 272 else 273 ghcb = NULL; 274 275 do { 276 ret = ghcb ? svsm_perform_ghcb_protocol(ghcb, call) 277 : __pi_svsm_perform_msr_protocol(call); 278 } while (ret == -EAGAIN); 279 280 if (sev_cfg.ghcbs_initialized) 281 __sev_put_ghcb(&state); 282 283 native_local_irq_restore(flags); 284 285 return ret; 286} 287 288static inline void __pval_terminate(u64 pfn, bool action, unsigned int page_size, 289 int ret, u64 svsm_ret) 290{ 291 WARN(1, "PVALIDATE failure: pfn: 0x%llx, action: %u, size: %u, ret: %d, svsm_ret: 0x%llx\n", 292 pfn, action, page_size, ret, svsm_ret); 293 294 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE); 295} 296 297static void svsm_pval_terminate(struct svsm_pvalidate_call *pc, int ret, u64 svsm_ret) 298{ 299 unsigned int page_size; 300 bool action; 301 u64 pfn; 302 303 pfn = pc->entry[pc->cur_index].pfn; 304 action = pc->entry[pc->cur_index].action; 305 page_size = pc->entry[pc->cur_index].page_size; 306 307 __pval_terminate(pfn, action, page_size, ret, svsm_ret); 308} 309 310static void pval_pages(struct snp_psc_desc *desc) 311{ 312 struct psc_entry *e; 313 unsigned long vaddr; 314 unsigned int size; 315 unsigned int i; 316 bool validate; 317 u64 pfn; 318 int rc; 319 320 for (i = 0; i <= desc->hdr.end_entry; i++) { 321 e = &desc->entries[i]; 322 323 pfn = e->gfn; 324 vaddr = (unsigned long)pfn_to_kaddr(pfn); 325 size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K; 326 validate = e->operation == SNP_PAGE_STATE_PRIVATE; 327 328 rc = pvalidate(vaddr, size, validate); 329 if (!rc) 330 continue; 331 332 if (rc == PVALIDATE_FAIL_SIZEMISMATCH && size == RMP_PG_SIZE_2M) { 333 unsigned long vaddr_end = vaddr + PMD_SIZE; 334 335 for (; vaddr < vaddr_end; vaddr += PAGE_SIZE, pfn++) { 336 rc = pvalidate(vaddr, RMP_PG_SIZE_4K, validate); 337 if (rc) 338 __pval_terminate(pfn, validate, RMP_PG_SIZE_4K, rc, 0); 339 } 340 } else { 341 __pval_terminate(pfn, validate, size, rc, 0); 342 } 343 } 344} 345 346static u64 svsm_build_ca_from_pfn_range(u64 pfn, u64 pfn_end, bool action, 347 struct svsm_pvalidate_call *pc) 348{ 349 struct svsm_pvalidate_entry *pe; 350 351 /* Nothing in the CA yet */ 352 pc->num_entries = 0; 353 pc->cur_index = 0; 354 355 pe = &pc->entry[0]; 356 357 while (pfn < pfn_end) { 358 pe->page_size = RMP_PG_SIZE_4K; 359 pe->action = action; 360 pe->ignore_cf = 0; 361 pe->rsvd = 0; 362 pe->pfn = pfn; 363 364 pe++; 365 pfn++; 366 367 pc->num_entries++; 368 if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT) 369 break; 370 } 371 372 return pfn; 373} 374 375static int svsm_build_ca_from_psc_desc(struct snp_psc_desc *desc, unsigned int desc_entry, 376 struct svsm_pvalidate_call *pc) 377{ 378 struct svsm_pvalidate_entry *pe; 379 struct psc_entry *e; 380 381 /* Nothing in the CA yet */ 382 pc->num_entries = 0; 383 pc->cur_index = 0; 384 385 pe = &pc->entry[0]; 386 e = &desc->entries[desc_entry]; 387 388 while (desc_entry <= desc->hdr.end_entry) { 389 pe->page_size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K; 390 pe->action = e->operation == SNP_PAGE_STATE_PRIVATE; 391 pe->ignore_cf = 0; 392 pe->rsvd = 0; 393 pe->pfn = e->gfn; 394 395 pe++; 396 e++; 397 398 desc_entry++; 399 pc->num_entries++; 400 if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT) 401 break; 402 } 403 404 return desc_entry; 405} 406 407static void svsm_pval_pages(struct snp_psc_desc *desc) 408{ 409 struct svsm_pvalidate_entry pv_4k[VMGEXIT_PSC_MAX_ENTRY]; 410 unsigned int i, pv_4k_count = 0; 411 struct svsm_pvalidate_call *pc; 412 struct svsm_call call = {}; 413 unsigned long flags; 414 bool action; 415 u64 pc_pa; 416 int ret; 417 418 /* 419 * This can be called very early in the boot, use native functions in 420 * order to avoid paravirt issues. 421 */ 422 flags = native_local_irq_save(); 423 424 /* 425 * The SVSM calling area (CA) can support processing 510 entries at a 426 * time. Loop through the Page State Change descriptor until the CA is 427 * full or the last entry in the descriptor is reached, at which time 428 * the SVSM is invoked. This repeats until all entries in the descriptor 429 * are processed. 430 */ 431 call.caa = svsm_get_caa(); 432 433 pc = (struct svsm_pvalidate_call *)call.caa->svsm_buffer; 434 pc_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer); 435 436 /* Protocol 0, Call ID 1 */ 437 call.rax = SVSM_CORE_CALL(SVSM_CORE_PVALIDATE); 438 call.rcx = pc_pa; 439 440 for (i = 0; i <= desc->hdr.end_entry;) { 441 i = svsm_build_ca_from_psc_desc(desc, i, pc); 442 443 do { 444 ret = svsm_perform_call_protocol(&call); 445 if (!ret) 446 continue; 447 448 /* 449 * Check if the entry failed because of an RMP mismatch (a 450 * PVALIDATE at 2M was requested, but the page is mapped in 451 * the RMP as 4K). 452 */ 453 454 if (call.rax_out == SVSM_PVALIDATE_FAIL_SIZEMISMATCH && 455 pc->entry[pc->cur_index].page_size == RMP_PG_SIZE_2M) { 456 /* Save this entry for post-processing at 4K */ 457 pv_4k[pv_4k_count++] = pc->entry[pc->cur_index]; 458 459 /* Skip to the next one unless at the end of the list */ 460 pc->cur_index++; 461 if (pc->cur_index < pc->num_entries) 462 ret = -EAGAIN; 463 else 464 ret = 0; 465 } 466 } while (ret == -EAGAIN); 467 468 if (ret) 469 svsm_pval_terminate(pc, ret, call.rax_out); 470 } 471 472 /* Process any entries that failed to be validated at 2M and validate them at 4K */ 473 for (i = 0; i < pv_4k_count; i++) { 474 u64 pfn, pfn_end; 475 476 action = pv_4k[i].action; 477 pfn = pv_4k[i].pfn; 478 pfn_end = pfn + 512; 479 480 while (pfn < pfn_end) { 481 pfn = svsm_build_ca_from_pfn_range(pfn, pfn_end, action, pc); 482 483 ret = svsm_perform_call_protocol(&call); 484 if (ret) 485 svsm_pval_terminate(pc, ret, call.rax_out); 486 } 487 } 488 489 native_local_irq_restore(flags); 490} 491 492static void pvalidate_pages(struct snp_psc_desc *desc) 493{ 494 struct psc_entry *e; 495 unsigned int i; 496 497 if (snp_vmpl) 498 svsm_pval_pages(desc); 499 else 500 pval_pages(desc); 501 502 /* 503 * If not affected by the cache-coherency vulnerability there is no need 504 * to perform the cache eviction mitigation. 505 */ 506 if (cpu_feature_enabled(X86_FEATURE_COHERENCY_SFW_NO)) 507 return; 508 509 for (i = 0; i <= desc->hdr.end_entry; i++) { 510 e = &desc->entries[i]; 511 512 /* 513 * If validating memory (making it private) perform the cache 514 * eviction mitigation. 515 */ 516 if (e->operation == SNP_PAGE_STATE_PRIVATE) 517 sev_evict_cache(pfn_to_kaddr(e->gfn), e->pagesize ? 512 : 1); 518 } 519} 520 521static int vmgexit_psc(struct ghcb *ghcb, struct snp_psc_desc *desc) 522{ 523 int cur_entry, end_entry, ret = 0; 524 struct snp_psc_desc *data; 525 struct es_em_ctxt ctxt; 526 527 vc_ghcb_invalidate(ghcb); 528 529 /* Copy the input desc into GHCB shared buffer */ 530 data = (struct snp_psc_desc *)ghcb->shared_buffer; 531 memcpy(ghcb->shared_buffer, desc, min_t(int, GHCB_SHARED_BUF_SIZE, sizeof(*desc))); 532 533 /* 534 * As per the GHCB specification, the hypervisor can resume the guest 535 * before processing all the entries. Check whether all the entries 536 * are processed. If not, then keep retrying. Note, the hypervisor 537 * will update the data memory directly to indicate the status, so 538 * reference the data->hdr everywhere. 539 * 540 * The strategy here is to wait for the hypervisor to change the page 541 * state in the RMP table before guest accesses the memory pages. If the 542 * page state change was not successful, then later memory access will 543 * result in a crash. 544 */ 545 cur_entry = data->hdr.cur_entry; 546 end_entry = data->hdr.end_entry; 547 548 while (data->hdr.cur_entry <= data->hdr.end_entry) { 549 ghcb_set_sw_scratch(ghcb, (u64)__pa(data)); 550 551 /* This will advance the shared buffer data points to. */ 552 ret = sev_es_ghcb_hv_call(ghcb, &ctxt, SVM_VMGEXIT_PSC, 0, 0); 553 554 /* 555 * Page State Change VMGEXIT can pass error code through 556 * exit_info_2. 557 */ 558 if (WARN(ret || ghcb->save.sw_exit_info_2, 559 "SNP: PSC failed ret=%d exit_info_2=%llx\n", 560 ret, ghcb->save.sw_exit_info_2)) { 561 ret = 1; 562 goto out; 563 } 564 565 /* Verify that reserved bit is not set */ 566 if (WARN(data->hdr.reserved, "Reserved bit is set in the PSC header\n")) { 567 ret = 1; 568 goto out; 569 } 570 571 /* 572 * Sanity check that entry processing is not going backwards. 573 * This will happen only if hypervisor is tricking us. 574 */ 575 if (WARN(data->hdr.end_entry > end_entry || cur_entry > data->hdr.cur_entry, 576"SNP: PSC processing going backward, end_entry %d (got %d) cur_entry %d (got %d)\n", 577 end_entry, data->hdr.end_entry, cur_entry, data->hdr.cur_entry)) { 578 ret = 1; 579 goto out; 580 } 581 } 582 583out: 584 return ret; 585} 586 587static unsigned long __set_pages_state(struct snp_psc_desc *data, unsigned long vaddr, 588 unsigned long vaddr_end, int op) 589{ 590 struct ghcb_state state; 591 bool use_large_entry; 592 struct psc_hdr *hdr; 593 struct psc_entry *e; 594 unsigned long flags; 595 unsigned long pfn; 596 struct ghcb *ghcb; 597 int i; 598 599 hdr = &data->hdr; 600 e = data->entries; 601 602 memset(data, 0, sizeof(*data)); 603 i = 0; 604 605 while (vaddr < vaddr_end && i < ARRAY_SIZE(data->entries)) { 606 hdr->end_entry = i; 607 608 if (is_vmalloc_addr((void *)vaddr)) { 609 pfn = vmalloc_to_pfn((void *)vaddr); 610 use_large_entry = false; 611 } else { 612 pfn = __pa(vaddr) >> PAGE_SHIFT; 613 use_large_entry = true; 614 } 615 616 e->gfn = pfn; 617 e->operation = op; 618 619 if (use_large_entry && IS_ALIGNED(vaddr, PMD_SIZE) && 620 (vaddr_end - vaddr) >= PMD_SIZE) { 621 e->pagesize = RMP_PG_SIZE_2M; 622 vaddr += PMD_SIZE; 623 } else { 624 e->pagesize = RMP_PG_SIZE_4K; 625 vaddr += PAGE_SIZE; 626 } 627 628 e++; 629 i++; 630 } 631 632 /* Page validation must be rescinded before changing to shared */ 633 if (op == SNP_PAGE_STATE_SHARED) 634 pvalidate_pages(data); 635 636 local_irq_save(flags); 637 638 if (sev_cfg.ghcbs_initialized) 639 ghcb = __sev_get_ghcb(&state); 640 else 641 ghcb = boot_ghcb; 642 643 /* Invoke the hypervisor to perform the page state changes */ 644 if (!ghcb || vmgexit_psc(ghcb, data)) 645 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC); 646 647 if (sev_cfg.ghcbs_initialized) 648 __sev_put_ghcb(&state); 649 650 local_irq_restore(flags); 651 652 /* Page validation must be performed after changing to private */ 653 if (op == SNP_PAGE_STATE_PRIVATE) 654 pvalidate_pages(data); 655 656 return vaddr; 657} 658 659static void set_pages_state(unsigned long vaddr, unsigned long npages, int op) 660{ 661 struct snp_psc_desc desc; 662 unsigned long vaddr_end; 663 664 /* Use the MSR protocol when a GHCB is not available. */ 665 if (!boot_ghcb) { 666 struct psc_desc d = { op, svsm_get_caa(), svsm_get_caa_pa() }; 667 668 return early_set_pages_state(vaddr, __pa(vaddr), npages, &d); 669 } 670 671 vaddr = vaddr & PAGE_MASK; 672 vaddr_end = vaddr + (npages << PAGE_SHIFT); 673 674 while (vaddr < vaddr_end) 675 vaddr = __set_pages_state(&desc, vaddr, vaddr_end, op); 676} 677 678void snp_set_memory_shared(unsigned long vaddr, unsigned long npages) 679{ 680 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 681 return; 682 683 set_pages_state(vaddr, npages, SNP_PAGE_STATE_SHARED); 684} 685 686void snp_set_memory_private(unsigned long vaddr, unsigned long npages) 687{ 688 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 689 return; 690 691 set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE); 692} 693 694void snp_accept_memory(phys_addr_t start, phys_addr_t end) 695{ 696 unsigned long vaddr, npages; 697 698 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 699 return; 700 701 vaddr = (unsigned long)__va(start); 702 npages = (end - start) >> PAGE_SHIFT; 703 704 set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE); 705} 706 707static int vmgexit_ap_control(u64 event, struct sev_es_save_area *vmsa, u32 apic_id) 708{ 709 bool create = event != SVM_VMGEXIT_AP_DESTROY; 710 struct ghcb_state state; 711 unsigned long flags; 712 struct ghcb *ghcb; 713 int ret = 0; 714 715 local_irq_save(flags); 716 717 ghcb = __sev_get_ghcb(&state); 718 719 vc_ghcb_invalidate(ghcb); 720 721 if (create) 722 ghcb_set_rax(ghcb, vmsa->sev_features); 723 724 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_CREATION); 725 ghcb_set_sw_exit_info_1(ghcb, 726 ((u64)apic_id << 32) | 727 ((u64)snp_vmpl << 16) | 728 event); 729 ghcb_set_sw_exit_info_2(ghcb, __pa(vmsa)); 730 731 sev_es_wr_ghcb_msr(__pa(ghcb)); 732 VMGEXIT(); 733 734 if (!ghcb_sw_exit_info_1_is_valid(ghcb) || 735 lower_32_bits(ghcb->save.sw_exit_info_1)) { 736 pr_err("SNP AP %s error\n", (create ? "CREATE" : "DESTROY")); 737 ret = -EINVAL; 738 } 739 740 __sev_put_ghcb(&state); 741 742 local_irq_restore(flags); 743 744 return ret; 745} 746 747static int snp_set_vmsa(void *va, void *caa, int apic_id, bool make_vmsa) 748{ 749 int ret; 750 751 if (snp_vmpl) { 752 struct svsm_call call = {}; 753 unsigned long flags; 754 755 local_irq_save(flags); 756 757 call.caa = this_cpu_read(svsm_caa); 758 call.rcx = __pa(va); 759 760 if (make_vmsa) { 761 /* Protocol 0, Call ID 2 */ 762 call.rax = SVSM_CORE_CALL(SVSM_CORE_CREATE_VCPU); 763 call.rdx = __pa(caa); 764 call.r8 = apic_id; 765 } else { 766 /* Protocol 0, Call ID 3 */ 767 call.rax = SVSM_CORE_CALL(SVSM_CORE_DELETE_VCPU); 768 } 769 770 ret = svsm_perform_call_protocol(&call); 771 772 local_irq_restore(flags); 773 } else { 774 /* 775 * If the kernel runs at VMPL0, it can change the VMSA 776 * bit for a page using the RMPADJUST instruction. 777 * However, for the instruction to succeed it must 778 * target the permissions of a lesser privileged (higher 779 * numbered) VMPL level, so use VMPL1. 780 */ 781 u64 attrs = 1; 782 783 if (make_vmsa) 784 attrs |= RMPADJUST_VMSA_PAGE_BIT; 785 786 ret = rmpadjust((unsigned long)va, RMP_PG_SIZE_4K, attrs); 787 } 788 789 return ret; 790} 791 792static void snp_cleanup_vmsa(struct sev_es_save_area *vmsa, int apic_id) 793{ 794 int err; 795 796 err = snp_set_vmsa(vmsa, NULL, apic_id, false); 797 if (err) 798 pr_err("clear VMSA page failed (%u), leaking page\n", err); 799 else 800 free_page((unsigned long)vmsa); 801} 802 803static void set_pte_enc(pte_t *kpte, int level, void *va) 804{ 805 struct pte_enc_desc d = { 806 .kpte = kpte, 807 .pte_level = level, 808 .va = va, 809 .encrypt = true 810 }; 811 812 prepare_pte_enc(&d); 813 set_pte_enc_mask(kpte, d.pfn, d.new_pgprot); 814} 815 816static void unshare_all_memory(void) 817{ 818 unsigned long addr, end, size, ghcb; 819 struct sev_es_runtime_data *data; 820 unsigned int npages, level; 821 bool skipped_addr; 822 pte_t *pte; 823 int cpu; 824 825 /* Unshare the direct mapping. */ 826 addr = PAGE_OFFSET; 827 end = PAGE_OFFSET + get_max_mapped(); 828 829 while (addr < end) { 830 pte = lookup_address(addr, &level); 831 size = page_level_size(level); 832 npages = size / PAGE_SIZE; 833 skipped_addr = false; 834 835 if (!pte || !pte_decrypted(*pte) || pte_none(*pte)) { 836 addr += size; 837 continue; 838 } 839 840 /* 841 * Ensure that all the per-CPU GHCBs are made private at the 842 * end of the unsharing loop so that the switch to the slower 843 * MSR protocol happens last. 844 */ 845 for_each_possible_cpu(cpu) { 846 data = per_cpu(runtime_data, cpu); 847 ghcb = (unsigned long)&data->ghcb_page; 848 849 /* Handle the case of a huge page containing the GHCB page */ 850 if (addr <= ghcb && ghcb < addr + size) { 851 skipped_addr = true; 852 break; 853 } 854 } 855 856 if (!skipped_addr) { 857 set_pte_enc(pte, level, (void *)addr); 858 snp_set_memory_private(addr, npages); 859 } 860 addr += size; 861 } 862 863 /* Unshare all bss decrypted memory. */ 864 addr = (unsigned long)__start_bss_decrypted; 865 end = (unsigned long)__start_bss_decrypted_unused; 866 npages = (end - addr) >> PAGE_SHIFT; 867 868 for (; addr < end; addr += PAGE_SIZE) { 869 pte = lookup_address(addr, &level); 870 if (!pte || !pte_decrypted(*pte) || pte_none(*pte)) 871 continue; 872 873 set_pte_enc(pte, level, (void *)addr); 874 } 875 addr = (unsigned long)__start_bss_decrypted; 876 snp_set_memory_private(addr, npages); 877 878 __flush_tlb_all(); 879} 880 881/* Stop new private<->shared conversions */ 882void snp_kexec_begin(void) 883{ 884 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 885 return; 886 887 if (!IS_ENABLED(CONFIG_KEXEC_CORE)) 888 return; 889 890 /* 891 * Crash kernel ends up here with interrupts disabled: can't wait for 892 * conversions to finish. 893 * 894 * If race happened, just report and proceed. 895 */ 896 if (!set_memory_enc_stop_conversion()) 897 pr_warn("Failed to stop shared<->private conversions\n"); 898} 899 900/* 901 * Shutdown all APs except the one handling kexec/kdump and clearing 902 * the VMSA tag on AP's VMSA pages as they are not being used as 903 * VMSA page anymore. 904 */ 905static void shutdown_all_aps(void) 906{ 907 struct sev_es_save_area *vmsa; 908 int apic_id, this_cpu, cpu; 909 910 this_cpu = get_cpu(); 911 912 /* 913 * APs are already in HLT loop when enc_kexec_finish() callback 914 * is invoked. 915 */ 916 for_each_present_cpu(cpu) { 917 vmsa = per_cpu(sev_vmsa, cpu); 918 919 /* 920 * The BSP or offlined APs do not have guest allocated VMSA 921 * and there is no need to clear the VMSA tag for this page. 922 */ 923 if (!vmsa) 924 continue; 925 926 /* 927 * Cannot clear the VMSA tag for the currently running vCPU. 928 */ 929 if (this_cpu == cpu) { 930 unsigned long pa; 931 struct page *p; 932 933 pa = __pa(vmsa); 934 /* 935 * Mark the VMSA page of the running vCPU as offline 936 * so that is excluded and not touched by makedumpfile 937 * while generating vmcore during kdump. 938 */ 939 p = pfn_to_online_page(pa >> PAGE_SHIFT); 940 if (p) 941 __SetPageOffline(p); 942 continue; 943 } 944 945 apic_id = cpuid_to_apicid[cpu]; 946 947 /* 948 * Issue AP destroy to ensure AP gets kicked out of guest mode 949 * to allow using RMPADJUST to remove the VMSA tag on it's 950 * VMSA page. 951 */ 952 vmgexit_ap_control(SVM_VMGEXIT_AP_DESTROY, vmsa, apic_id); 953 snp_cleanup_vmsa(vmsa, apic_id); 954 } 955 956 put_cpu(); 957} 958 959void snp_kexec_finish(void) 960{ 961 struct sev_es_runtime_data *data; 962 unsigned long size, addr; 963 unsigned int level, cpu; 964 struct ghcb *ghcb; 965 pte_t *pte; 966 967 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 968 return; 969 970 if (!IS_ENABLED(CONFIG_KEXEC_CORE)) 971 return; 972 973 shutdown_all_aps(); 974 975 unshare_all_memory(); 976 977 /* 978 * Switch to using the MSR protocol to change per-CPU GHCBs to 979 * private. All the per-CPU GHCBs have been switched back to private, 980 * so can't do any more GHCB calls to the hypervisor beyond this point 981 * until the kexec'ed kernel starts running. 982 */ 983 boot_ghcb = NULL; 984 sev_cfg.ghcbs_initialized = false; 985 986 for_each_possible_cpu(cpu) { 987 data = per_cpu(runtime_data, cpu); 988 ghcb = &data->ghcb_page; 989 pte = lookup_address((unsigned long)ghcb, &level); 990 size = page_level_size(level); 991 /* Handle the case of a huge page containing the GHCB page */ 992 addr = (unsigned long)ghcb & page_level_mask(level); 993 set_pte_enc(pte, level, (void *)addr); 994 snp_set_memory_private(addr, (size / PAGE_SIZE)); 995 } 996} 997 998#define __ATTR_BASE (SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK) 999#define INIT_CS_ATTRIBS (__ATTR_BASE | SVM_SELECTOR_READ_MASK | SVM_SELECTOR_CODE_MASK) 1000#define INIT_DS_ATTRIBS (__ATTR_BASE | SVM_SELECTOR_WRITE_MASK) 1001 1002#define INIT_LDTR_ATTRIBS (SVM_SELECTOR_P_MASK | 2) 1003#define INIT_TR_ATTRIBS (SVM_SELECTOR_P_MASK | 3) 1004 1005static void *snp_alloc_vmsa_page(int cpu) 1006{ 1007 struct page *p; 1008 1009 /* 1010 * Allocate VMSA page to work around the SNP erratum where the CPU will 1011 * incorrectly signal an RMP violation #PF if a large page (2MB or 1GB) 1012 * collides with the RMP entry of VMSA page. The recommended workaround 1013 * is to not use a large page. 1014 * 1015 * Allocate an 8k page which is also 8k-aligned. 1016 */ 1017 p = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL_ACCOUNT | __GFP_ZERO, 1); 1018 if (!p) 1019 return NULL; 1020 1021 split_page(p, 1); 1022 1023 /* Free the first 4k. This page may be 2M/1G aligned and cannot be used. */ 1024 __free_page(p); 1025 1026 return page_address(p + 1); 1027} 1028 1029static int wakeup_cpu_via_vmgexit(u32 apic_id, unsigned long start_ip, unsigned int cpu) 1030{ 1031 struct sev_es_save_area *cur_vmsa, *vmsa; 1032 struct svsm_ca *caa; 1033 u8 sipi_vector; 1034 int ret; 1035 u64 cr4; 1036 1037 /* 1038 * The hypervisor SNP feature support check has happened earlier, just check 1039 * the AP_CREATION one here. 1040 */ 1041 if (!(sev_hv_features & GHCB_HV_FT_SNP_AP_CREATION)) 1042 return -EOPNOTSUPP; 1043 1044 /* 1045 * Verify the desired start IP against the known trampoline start IP 1046 * to catch any future new trampolines that may be introduced that 1047 * would require a new protected guest entry point. 1048 */ 1049 if (WARN_ONCE(start_ip != real_mode_header->trampoline_start, 1050 "Unsupported SNP start_ip: %lx\n", start_ip)) 1051 return -EINVAL; 1052 1053 /* Override start_ip with known protected guest start IP */ 1054 start_ip = real_mode_header->sev_es_trampoline_start; 1055 cur_vmsa = per_cpu(sev_vmsa, cpu); 1056 1057 /* 1058 * A new VMSA is created each time because there is no guarantee that 1059 * the current VMSA is the kernels or that the vCPU is not running. If 1060 * an attempt was done to use the current VMSA with a running vCPU, a 1061 * #VMEXIT of that vCPU would wipe out all of the settings being done 1062 * here. 1063 */ 1064 vmsa = (struct sev_es_save_area *)snp_alloc_vmsa_page(cpu); 1065 if (!vmsa) 1066 return -ENOMEM; 1067 1068 /* If an SVSM is present, the SVSM per-CPU CAA will be !NULL */ 1069 caa = per_cpu(svsm_caa, cpu); 1070 1071 /* CR4 should maintain the MCE value */ 1072 cr4 = native_read_cr4() & X86_CR4_MCE; 1073 1074 /* Set the CS value based on the start_ip converted to a SIPI vector */ 1075 sipi_vector = (start_ip >> 12); 1076 vmsa->cs.base = sipi_vector << 12; 1077 vmsa->cs.limit = AP_INIT_CS_LIMIT; 1078 vmsa->cs.attrib = INIT_CS_ATTRIBS; 1079 vmsa->cs.selector = sipi_vector << 8; 1080 1081 /* Set the RIP value based on start_ip */ 1082 vmsa->rip = start_ip & 0xfff; 1083 1084 /* Set AP INIT defaults as documented in the APM */ 1085 vmsa->ds.limit = AP_INIT_DS_LIMIT; 1086 vmsa->ds.attrib = INIT_DS_ATTRIBS; 1087 vmsa->es = vmsa->ds; 1088 vmsa->fs = vmsa->ds; 1089 vmsa->gs = vmsa->ds; 1090 vmsa->ss = vmsa->ds; 1091 1092 vmsa->gdtr.limit = AP_INIT_GDTR_LIMIT; 1093 vmsa->ldtr.limit = AP_INIT_LDTR_LIMIT; 1094 vmsa->ldtr.attrib = INIT_LDTR_ATTRIBS; 1095 vmsa->idtr.limit = AP_INIT_IDTR_LIMIT; 1096 vmsa->tr.limit = AP_INIT_TR_LIMIT; 1097 vmsa->tr.attrib = INIT_TR_ATTRIBS; 1098 1099 vmsa->cr4 = cr4; 1100 vmsa->cr0 = AP_INIT_CR0_DEFAULT; 1101 vmsa->dr7 = DR7_RESET_VALUE; 1102 vmsa->dr6 = AP_INIT_DR6_DEFAULT; 1103 vmsa->rflags = AP_INIT_RFLAGS_DEFAULT; 1104 vmsa->g_pat = AP_INIT_GPAT_DEFAULT; 1105 vmsa->xcr0 = AP_INIT_XCR0_DEFAULT; 1106 vmsa->mxcsr = AP_INIT_MXCSR_DEFAULT; 1107 vmsa->x87_ftw = AP_INIT_X87_FTW_DEFAULT; 1108 vmsa->x87_fcw = AP_INIT_X87_FCW_DEFAULT; 1109 1110 if (cc_platform_has(CC_ATTR_SNP_SECURE_AVIC)) 1111 vmsa->vintr_ctrl |= V_GIF_MASK | V_NMI_ENABLE_MASK; 1112 1113 /* SVME must be set. */ 1114 vmsa->efer = EFER_SVME; 1115 1116 /* 1117 * Set the SNP-specific fields for this VMSA: 1118 * VMPL level 1119 * SEV_FEATURES (matches the SEV STATUS MSR right shifted 2 bits) 1120 */ 1121 vmsa->vmpl = snp_vmpl; 1122 vmsa->sev_features = sev_status >> 2; 1123 1124 /* Populate AP's TSC scale/offset to get accurate TSC values. */ 1125 if (cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC)) { 1126 vmsa->tsc_scale = snp_tsc_scale; 1127 vmsa->tsc_offset = snp_tsc_offset; 1128 } 1129 1130 /* Switch the page over to a VMSA page now that it is initialized */ 1131 ret = snp_set_vmsa(vmsa, caa, apic_id, true); 1132 if (ret) { 1133 pr_err("set VMSA page failed (%u)\n", ret); 1134 free_page((unsigned long)vmsa); 1135 1136 return -EINVAL; 1137 } 1138 1139 /* Issue VMGEXIT AP Creation NAE event */ 1140 ret = vmgexit_ap_control(SVM_VMGEXIT_AP_CREATE, vmsa, apic_id); 1141 if (ret) { 1142 snp_cleanup_vmsa(vmsa, apic_id); 1143 vmsa = NULL; 1144 } 1145 1146 /* Free up any previous VMSA page */ 1147 if (cur_vmsa) 1148 snp_cleanup_vmsa(cur_vmsa, apic_id); 1149 1150 /* Record the current VMSA page */ 1151 per_cpu(sev_vmsa, cpu) = vmsa; 1152 1153 return ret; 1154} 1155 1156void __init snp_set_wakeup_secondary_cpu(void) 1157{ 1158 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1159 return; 1160 1161 /* 1162 * Always set this override if SNP is enabled. This makes it the 1163 * required method to start APs under SNP. If the hypervisor does 1164 * not support AP creation, then no APs will be started. 1165 */ 1166 apic_update_callback(wakeup_secondary_cpu, wakeup_cpu_via_vmgexit); 1167} 1168 1169int __init sev_es_setup_ap_jump_table(struct real_mode_header *rmh) 1170{ 1171 u16 startup_cs, startup_ip; 1172 phys_addr_t jump_table_pa; 1173 u64 jump_table_addr; 1174 u16 __iomem *jump_table; 1175 1176 jump_table_addr = get_jump_table_addr(); 1177 1178 /* On UP guests there is no jump table so this is not a failure */ 1179 if (!jump_table_addr) 1180 return 0; 1181 1182 /* Check if AP Jump Table is page-aligned */ 1183 if (jump_table_addr & ~PAGE_MASK) 1184 return -EINVAL; 1185 1186 jump_table_pa = jump_table_addr & PAGE_MASK; 1187 1188 startup_cs = (u16)(rmh->trampoline_start >> 4); 1189 startup_ip = (u16)(rmh->sev_es_trampoline_start - 1190 rmh->trampoline_start); 1191 1192 jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE); 1193 if (!jump_table) 1194 return -EIO; 1195 1196 writew(startup_ip, &jump_table[0]); 1197 writew(startup_cs, &jump_table[1]); 1198 1199 iounmap(jump_table); 1200 1201 return 0; 1202} 1203 1204/* 1205 * This is needed by the OVMF UEFI firmware which will use whatever it finds in 1206 * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu 1207 * runtime GHCBs used by the kernel are also mapped in the EFI page-table. 1208 * 1209 * When running under SVSM the CA page is needed too, so map it as well. 1210 */ 1211int __init sev_es_efi_map_ghcbs_cas(pgd_t *pgd) 1212{ 1213 unsigned long address, pflags, pflags_enc; 1214 struct sev_es_runtime_data *data; 1215 int cpu; 1216 u64 pfn; 1217 1218 if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT)) 1219 return 0; 1220 1221 pflags = _PAGE_NX | _PAGE_RW; 1222 pflags_enc = cc_mkenc(pflags); 1223 1224 for_each_possible_cpu(cpu) { 1225 data = per_cpu(runtime_data, cpu); 1226 1227 address = __pa(&data->ghcb_page); 1228 pfn = address >> PAGE_SHIFT; 1229 1230 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags)) 1231 return 1; 1232 1233 if (snp_vmpl) { 1234 address = per_cpu(svsm_caa_pa, cpu); 1235 if (!address) 1236 return 1; 1237 1238 pfn = address >> PAGE_SHIFT; 1239 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags_enc)) 1240 return 1; 1241 } 1242 } 1243 1244 return 0; 1245} 1246 1247u64 savic_ghcb_msr_read(u32 reg) 1248{ 1249 u64 msr = APIC_BASE_MSR + (reg >> 4); 1250 struct pt_regs regs = { .cx = msr }; 1251 struct es_em_ctxt ctxt = { .regs = ®s }; 1252 struct ghcb_state state; 1253 enum es_result res; 1254 struct ghcb *ghcb; 1255 1256 guard(irqsave)(); 1257 1258 ghcb = __sev_get_ghcb(&state); 1259 vc_ghcb_invalidate(ghcb); 1260 1261 res = sev_es_ghcb_handle_msr(ghcb, &ctxt, false); 1262 if (res != ES_OK) { 1263 pr_err("Secure AVIC MSR (0x%llx) read returned error (%d)\n", msr, res); 1264 /* MSR read failures are treated as fatal errors */ 1265 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SAVIC_FAIL); 1266 } 1267 1268 __sev_put_ghcb(&state); 1269 1270 return regs.ax | regs.dx << 32; 1271} 1272 1273void savic_ghcb_msr_write(u32 reg, u64 value) 1274{ 1275 u64 msr = APIC_BASE_MSR + (reg >> 4); 1276 struct pt_regs regs = { 1277 .cx = msr, 1278 .ax = lower_32_bits(value), 1279 .dx = upper_32_bits(value) 1280 }; 1281 struct es_em_ctxt ctxt = { .regs = ®s }; 1282 struct ghcb_state state; 1283 enum es_result res; 1284 struct ghcb *ghcb; 1285 1286 guard(irqsave)(); 1287 1288 ghcb = __sev_get_ghcb(&state); 1289 vc_ghcb_invalidate(ghcb); 1290 1291 res = sev_es_ghcb_handle_msr(ghcb, &ctxt, true); 1292 if (res != ES_OK) { 1293 pr_err("Secure AVIC MSR (0x%llx) write returned error (%d)\n", msr, res); 1294 /* MSR writes should never fail. Any failure is fatal error for SNP guest */ 1295 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SAVIC_FAIL); 1296 } 1297 1298 __sev_put_ghcb(&state); 1299} 1300 1301enum es_result savic_register_gpa(u64 gpa) 1302{ 1303 struct ghcb_state state; 1304 struct es_em_ctxt ctxt; 1305 enum es_result res; 1306 struct ghcb *ghcb; 1307 1308 guard(irqsave)(); 1309 1310 ghcb = __sev_get_ghcb(&state); 1311 vc_ghcb_invalidate(ghcb); 1312 1313 ghcb_set_rax(ghcb, SVM_VMGEXIT_SAVIC_SELF_GPA); 1314 ghcb_set_rbx(ghcb, gpa); 1315 res = sev_es_ghcb_hv_call(ghcb, &ctxt, SVM_VMGEXIT_SAVIC, 1316 SVM_VMGEXIT_SAVIC_REGISTER_GPA, 0); 1317 1318 __sev_put_ghcb(&state); 1319 1320 return res; 1321} 1322 1323enum es_result savic_unregister_gpa(u64 *gpa) 1324{ 1325 struct ghcb_state state; 1326 struct es_em_ctxt ctxt; 1327 enum es_result res; 1328 struct ghcb *ghcb; 1329 1330 guard(irqsave)(); 1331 1332 ghcb = __sev_get_ghcb(&state); 1333 vc_ghcb_invalidate(ghcb); 1334 1335 ghcb_set_rax(ghcb, SVM_VMGEXIT_SAVIC_SELF_GPA); 1336 res = sev_es_ghcb_hv_call(ghcb, &ctxt, SVM_VMGEXIT_SAVIC, 1337 SVM_VMGEXIT_SAVIC_UNREGISTER_GPA, 0); 1338 if (gpa && res == ES_OK) 1339 *gpa = ghcb->save.rbx; 1340 1341 __sev_put_ghcb(&state); 1342 1343 return res; 1344} 1345 1346static void snp_register_per_cpu_ghcb(void) 1347{ 1348 struct sev_es_runtime_data *data; 1349 struct ghcb *ghcb; 1350 1351 data = this_cpu_read(runtime_data); 1352 ghcb = &data->ghcb_page; 1353 1354 snp_register_ghcb_early(__pa(ghcb)); 1355} 1356 1357void setup_ghcb(void) 1358{ 1359 if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT)) 1360 return; 1361 1362 /* 1363 * Check whether the runtime #VC exception handler is active. It uses 1364 * the per-CPU GHCB page which is set up by sev_es_init_vc_handling(). 1365 * 1366 * If SNP is active, register the per-CPU GHCB page so that the runtime 1367 * exception handler can use it. 1368 */ 1369 if (initial_vc_handler == (unsigned long)kernel_exc_vmm_communication) { 1370 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1371 snp_register_per_cpu_ghcb(); 1372 1373 sev_cfg.ghcbs_initialized = true; 1374 1375 return; 1376 } 1377 1378 /* 1379 * Make sure the hypervisor talks a supported protocol. 1380 * This gets called only in the BSP boot phase. 1381 */ 1382 if (!sev_es_negotiate_protocol()) 1383 sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ); 1384 1385 /* 1386 * Clear the boot_ghcb. The first exception comes in before the bss 1387 * section is cleared. 1388 */ 1389 memset(&boot_ghcb_page, 0, PAGE_SIZE); 1390 1391 /* Alright - Make the boot-ghcb public */ 1392 boot_ghcb = &boot_ghcb_page; 1393 1394 /* SNP guest requires that GHCB GPA must be registered. */ 1395 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1396 snp_register_ghcb_early(__pa(&boot_ghcb_page)); 1397} 1398 1399#ifdef CONFIG_HOTPLUG_CPU 1400static void sev_es_ap_hlt_loop(void) 1401{ 1402 struct ghcb_state state; 1403 struct ghcb *ghcb; 1404 1405 ghcb = __sev_get_ghcb(&state); 1406 1407 while (true) { 1408 vc_ghcb_invalidate(ghcb); 1409 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP); 1410 ghcb_set_sw_exit_info_1(ghcb, 0); 1411 ghcb_set_sw_exit_info_2(ghcb, 0); 1412 1413 sev_es_wr_ghcb_msr(__pa(ghcb)); 1414 VMGEXIT(); 1415 1416 /* Wakeup signal? */ 1417 if (ghcb_sw_exit_info_2_is_valid(ghcb) && 1418 ghcb->save.sw_exit_info_2) 1419 break; 1420 } 1421 1422 __sev_put_ghcb(&state); 1423} 1424 1425/* 1426 * Play_dead handler when running under SEV-ES. This is needed because 1427 * the hypervisor can't deliver an SIPI request to restart the AP. 1428 * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the 1429 * hypervisor wakes it up again. 1430 */ 1431static void sev_es_play_dead(void) 1432{ 1433 play_dead_common(); 1434 1435 /* IRQs now disabled */ 1436 1437 sev_es_ap_hlt_loop(); 1438 1439 /* 1440 * If we get here, the VCPU was woken up again. Jump to CPU 1441 * startup code to get it back online. 1442 */ 1443 soft_restart_cpu(); 1444} 1445#else /* CONFIG_HOTPLUG_CPU */ 1446#define sev_es_play_dead native_play_dead 1447#endif /* CONFIG_HOTPLUG_CPU */ 1448 1449#ifdef CONFIG_SMP 1450static void __init sev_es_setup_play_dead(void) 1451{ 1452 smp_ops.play_dead = sev_es_play_dead; 1453} 1454#else 1455static inline void sev_es_setup_play_dead(void) { } 1456#endif 1457 1458static void __init alloc_runtime_data(int cpu) 1459{ 1460 struct sev_es_runtime_data *data; 1461 1462 data = memblock_alloc_node(sizeof(*data), PAGE_SIZE, cpu_to_node(cpu)); 1463 if (!data) 1464 panic("Can't allocate SEV-ES runtime data"); 1465 1466 per_cpu(runtime_data, cpu) = data; 1467 1468 if (snp_vmpl) { 1469 struct svsm_ca *caa; 1470 1471 /* Allocate the SVSM CA page if an SVSM is present */ 1472 caa = cpu ? memblock_alloc_or_panic(sizeof(*caa), PAGE_SIZE) 1473 : &boot_svsm_ca_page; 1474 1475 per_cpu(svsm_caa, cpu) = caa; 1476 per_cpu(svsm_caa_pa, cpu) = __pa(caa); 1477 } 1478} 1479 1480static void __init init_ghcb(int cpu) 1481{ 1482 struct sev_es_runtime_data *data; 1483 int err; 1484 1485 data = per_cpu(runtime_data, cpu); 1486 1487 err = early_set_memory_decrypted((unsigned long)&data->ghcb_page, 1488 sizeof(data->ghcb_page)); 1489 if (err) 1490 panic("Can't map GHCBs unencrypted"); 1491 1492 memset(&data->ghcb_page, 0, sizeof(data->ghcb_page)); 1493 1494 data->ghcb_active = false; 1495 data->backup_ghcb_active = false; 1496} 1497 1498void __init sev_es_init_vc_handling(void) 1499{ 1500 int cpu; 1501 1502 BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE); 1503 1504 if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT)) 1505 return; 1506 1507 if (!sev_es_check_cpu_features()) 1508 panic("SEV-ES CPU Features missing"); 1509 1510 /* 1511 * SNP is supported in v2 of the GHCB spec which mandates support for HV 1512 * features. 1513 */ 1514 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) { 1515 sev_hv_features = get_hv_features(); 1516 1517 if (!(sev_hv_features & GHCB_HV_FT_SNP)) 1518 sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED); 1519 } 1520 1521 /* Initialize per-cpu GHCB pages */ 1522 for_each_possible_cpu(cpu) { 1523 alloc_runtime_data(cpu); 1524 init_ghcb(cpu); 1525 } 1526 1527 if (snp_vmpl) 1528 sev_cfg.use_cas = true; 1529 1530 sev_es_setup_play_dead(); 1531 1532 /* Secondary CPUs use the runtime #VC handler */ 1533 initial_vc_handler = (unsigned long)kernel_exc_vmm_communication; 1534} 1535 1536/* 1537 * SEV-SNP guests should only execute dmi_setup() if EFI_CONFIG_TABLES are 1538 * enabled, as the alternative (fallback) logic for DMI probing in the legacy 1539 * ROM region can cause a crash since this region is not pre-validated. 1540 */ 1541void __init snp_dmi_setup(void) 1542{ 1543 if (efi_enabled(EFI_CONFIG_TABLES)) 1544 dmi_setup(); 1545} 1546 1547static void dump_cpuid_table(void) 1548{ 1549 const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table(); 1550 int i = 0; 1551 1552 pr_info("count=%d reserved=0x%x reserved2=0x%llx\n", 1553 cpuid_table->count, cpuid_table->__reserved1, cpuid_table->__reserved2); 1554 1555 for (i = 0; i < SNP_CPUID_COUNT_MAX; i++) { 1556 const struct snp_cpuid_fn *fn = &cpuid_table->fn[i]; 1557 1558 pr_info("index=%3d fn=0x%08x subfn=0x%08x: eax=0x%08x ebx=0x%08x ecx=0x%08x edx=0x%08x xcr0_in=0x%016llx xss_in=0x%016llx reserved=0x%016llx\n", 1559 i, fn->eax_in, fn->ecx_in, fn->eax, fn->ebx, fn->ecx, 1560 fn->edx, fn->xcr0_in, fn->xss_in, fn->__reserved); 1561 } 1562} 1563 1564/* 1565 * It is useful from an auditing/testing perspective to provide an easy way 1566 * for the guest owner to know that the CPUID table has been initialized as 1567 * expected, but that initialization happens too early in boot to print any 1568 * sort of indicator, and there's not really any other good place to do it, 1569 * so do it here. 1570 * 1571 * If running as an SNP guest, report the current VM privilege level (VMPL). 1572 */ 1573static int __init report_snp_info(void) 1574{ 1575 const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table(); 1576 1577 if (cpuid_table->count) { 1578 pr_info("Using SNP CPUID table, %d entries present.\n", 1579 cpuid_table->count); 1580 1581 if (sev_cfg.debug) 1582 dump_cpuid_table(); 1583 } 1584 1585 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1586 pr_info("SNP running at VMPL%u.\n", snp_vmpl); 1587 1588 return 0; 1589} 1590arch_initcall(report_snp_info); 1591 1592static void update_attest_input(struct svsm_call *call, struct svsm_attest_call *input) 1593{ 1594 /* If (new) lengths have been returned, propagate them up */ 1595 if (call->rcx_out != call->rcx) 1596 input->manifest_buf.len = call->rcx_out; 1597 1598 if (call->rdx_out != call->rdx) 1599 input->certificates_buf.len = call->rdx_out; 1600 1601 if (call->r8_out != call->r8) 1602 input->report_buf.len = call->r8_out; 1603} 1604 1605int snp_issue_svsm_attest_req(u64 call_id, struct svsm_call *call, 1606 struct svsm_attest_call *input) 1607{ 1608 struct svsm_attest_call *ac; 1609 unsigned long flags; 1610 u64 attest_call_pa; 1611 int ret; 1612 1613 if (!snp_vmpl) 1614 return -EINVAL; 1615 1616 local_irq_save(flags); 1617 1618 call->caa = svsm_get_caa(); 1619 1620 ac = (struct svsm_attest_call *)call->caa->svsm_buffer; 1621 attest_call_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer); 1622 1623 *ac = *input; 1624 1625 /* 1626 * Set input registers for the request and set RDX and R8 to known 1627 * values in order to detect length values being returned in them. 1628 */ 1629 call->rax = call_id; 1630 call->rcx = attest_call_pa; 1631 call->rdx = -1; 1632 call->r8 = -1; 1633 ret = svsm_perform_call_protocol(call); 1634 update_attest_input(call, input); 1635 1636 local_irq_restore(flags); 1637 1638 return ret; 1639} 1640EXPORT_SYMBOL_GPL(snp_issue_svsm_attest_req); 1641 1642static int snp_issue_guest_request(struct snp_guest_req *req) 1643{ 1644 struct snp_req_data *input = &req->input; 1645 struct ghcb_state state; 1646 struct es_em_ctxt ctxt; 1647 unsigned long flags; 1648 struct ghcb *ghcb; 1649 int ret; 1650 1651 req->exitinfo2 = SEV_RET_NO_FW_CALL; 1652 1653 /* 1654 * __sev_get_ghcb() needs to run with IRQs disabled because it is using 1655 * a per-CPU GHCB. 1656 */ 1657 local_irq_save(flags); 1658 1659 ghcb = __sev_get_ghcb(&state); 1660 if (!ghcb) { 1661 ret = -EIO; 1662 goto e_restore_irq; 1663 } 1664 1665 vc_ghcb_invalidate(ghcb); 1666 1667 if (req->exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) { 1668 ghcb_set_rax(ghcb, input->data_gpa); 1669 ghcb_set_rbx(ghcb, input->data_npages); 1670 } 1671 1672 ret = sev_es_ghcb_hv_call(ghcb, &ctxt, req->exit_code, input->req_gpa, input->resp_gpa); 1673 if (ret) 1674 goto e_put; 1675 1676 req->exitinfo2 = ghcb->save.sw_exit_info_2; 1677 switch (req->exitinfo2) { 1678 case 0: 1679 break; 1680 1681 case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_BUSY): 1682 ret = -EAGAIN; 1683 break; 1684 1685 case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN): 1686 /* Number of expected pages are returned in RBX */ 1687 if (req->exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) { 1688 input->data_npages = ghcb_get_rbx(ghcb); 1689 ret = -ENOSPC; 1690 break; 1691 } 1692 fallthrough; 1693 default: 1694 ret = -EIO; 1695 break; 1696 } 1697 1698e_put: 1699 __sev_put_ghcb(&state); 1700e_restore_irq: 1701 local_irq_restore(flags); 1702 1703 return ret; 1704} 1705 1706/** 1707 * snp_svsm_vtpm_probe() - Probe if SVSM provides a vTPM device 1708 * 1709 * Check that there is SVSM and that it supports at least TPM_SEND_COMMAND 1710 * which is the only request used so far. 1711 * 1712 * Return: true if the platform provides a vTPM SVSM device, false otherwise. 1713 */ 1714static bool snp_svsm_vtpm_probe(void) 1715{ 1716 struct svsm_call call = {}; 1717 1718 /* The vTPM device is available only if a SVSM is present */ 1719 if (!snp_vmpl) 1720 return false; 1721 1722 call.caa = svsm_get_caa(); 1723 call.rax = SVSM_VTPM_CALL(SVSM_VTPM_QUERY); 1724 1725 if (svsm_perform_call_protocol(&call)) 1726 return false; 1727 1728 /* Check platform commands contains TPM_SEND_COMMAND - platform command 8 */ 1729 return call.rcx_out & BIT_ULL(8); 1730} 1731 1732/** 1733 * snp_svsm_vtpm_send_command() - Execute a vTPM operation on SVSM 1734 * @buffer: A buffer used to both send the command and receive the response. 1735 * 1736 * Execute a SVSM_VTPM_CMD call as defined by 1737 * "Secure VM Service Module for SEV-SNP Guests" Publication # 58019 Revision: 1.00 1738 * 1739 * All command request/response buffers have a common structure as specified by 1740 * the following table: 1741 * Byte Size    In/Out    Description 1742 * Offset    (Bytes) 1743 * 0x000     4          In        Platform command 1744 *                        Out       Platform command response size 1745 * 1746 * Each command can build upon this common request/response structure to create 1747 * a structure specific to the command. See include/linux/tpm_svsm.h for more 1748 * details. 1749 * 1750 * Return: 0 on success, -errno on failure 1751 */ 1752int snp_svsm_vtpm_send_command(u8 *buffer) 1753{ 1754 struct svsm_call call = {}; 1755 1756 call.caa = svsm_get_caa(); 1757 call.rax = SVSM_VTPM_CALL(SVSM_VTPM_CMD); 1758 call.rcx = __pa(buffer); 1759 1760 return svsm_perform_call_protocol(&call); 1761} 1762EXPORT_SYMBOL_GPL(snp_svsm_vtpm_send_command); 1763 1764static struct platform_device sev_guest_device = { 1765 .name = "sev-guest", 1766 .id = -1, 1767}; 1768 1769static struct platform_device tpm_svsm_device = { 1770 .name = "tpm-svsm", 1771 .id = -1, 1772}; 1773 1774static int __init snp_init_platform_device(void) 1775{ 1776 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1777 return -ENODEV; 1778 1779 if (platform_device_register(&sev_guest_device)) 1780 return -ENODEV; 1781 1782 if (snp_svsm_vtpm_probe() && 1783 platform_device_register(&tpm_svsm_device)) 1784 return -ENODEV; 1785 1786 pr_info("SNP guest platform devices initialized.\n"); 1787 return 0; 1788} 1789device_initcall(snp_init_platform_device); 1790 1791void sev_show_status(void) 1792{ 1793 int i; 1794 1795 pr_info("Status: "); 1796 for (i = 0; i < MSR_AMD64_SNP_RESV_BIT; i++) { 1797 if (sev_status & BIT_ULL(i)) { 1798 if (!sev_status_feat_names[i]) 1799 continue; 1800 1801 pr_cont("%s ", sev_status_feat_names[i]); 1802 } 1803 } 1804 pr_cont("\n"); 1805} 1806 1807#ifdef CONFIG_SYSFS 1808static ssize_t vmpl_show(struct kobject *kobj, 1809 struct kobj_attribute *attr, char *buf) 1810{ 1811 return sysfs_emit(buf, "%d\n", snp_vmpl); 1812} 1813 1814static struct kobj_attribute vmpl_attr = __ATTR_RO(vmpl); 1815 1816static struct attribute *vmpl_attrs[] = { 1817 &vmpl_attr.attr, 1818 NULL 1819}; 1820 1821static struct attribute_group sev_attr_group = { 1822 .attrs = vmpl_attrs, 1823}; 1824 1825static int __init sev_sysfs_init(void) 1826{ 1827 struct kobject *sev_kobj; 1828 struct device *dev_root; 1829 int ret; 1830 1831 if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) 1832 return -ENODEV; 1833 1834 dev_root = bus_get_dev_root(&cpu_subsys); 1835 if (!dev_root) 1836 return -ENODEV; 1837 1838 sev_kobj = kobject_create_and_add("sev", &dev_root->kobj); 1839 put_device(dev_root); 1840 1841 if (!sev_kobj) 1842 return -ENOMEM; 1843 1844 ret = sysfs_create_group(sev_kobj, &sev_attr_group); 1845 if (ret) 1846 kobject_put(sev_kobj); 1847 1848 return ret; 1849} 1850arch_initcall(sev_sysfs_init); 1851#endif // CONFIG_SYSFS 1852 1853static void free_shared_pages(void *buf, size_t sz) 1854{ 1855 unsigned int npages = PAGE_ALIGN(sz) >> PAGE_SHIFT; 1856 int ret; 1857 1858 if (!buf) 1859 return; 1860 1861 ret = set_memory_encrypted((unsigned long)buf, npages); 1862 if (ret) { 1863 WARN_ONCE(ret, "failed to restore encryption mask (leak it)\n"); 1864 return; 1865 } 1866 1867 __free_pages(virt_to_page(buf), get_order(sz)); 1868} 1869 1870static void *alloc_shared_pages(size_t sz) 1871{ 1872 unsigned int npages = PAGE_ALIGN(sz) >> PAGE_SHIFT; 1873 struct page *page; 1874 int ret; 1875 1876 page = alloc_pages(GFP_KERNEL_ACCOUNT, get_order(sz)); 1877 if (!page) 1878 return NULL; 1879 1880 ret = set_memory_decrypted((unsigned long)page_address(page), npages); 1881 if (ret) { 1882 pr_err("failed to mark page shared, ret=%d\n", ret); 1883 __free_pages(page, get_order(sz)); 1884 return NULL; 1885 } 1886 1887 return page_address(page); 1888} 1889 1890static u8 *get_vmpck(int id, struct snp_secrets_page *secrets, u32 **seqno) 1891{ 1892 u8 *key = NULL; 1893 1894 switch (id) { 1895 case 0: 1896 *seqno = &secrets->os_area.msg_seqno_0; 1897 key = secrets->vmpck0; 1898 break; 1899 case 1: 1900 *seqno = &secrets->os_area.msg_seqno_1; 1901 key = secrets->vmpck1; 1902 break; 1903 case 2: 1904 *seqno = &secrets->os_area.msg_seqno_2; 1905 key = secrets->vmpck2; 1906 break; 1907 case 3: 1908 *seqno = &secrets->os_area.msg_seqno_3; 1909 key = secrets->vmpck3; 1910 break; 1911 default: 1912 break; 1913 } 1914 1915 return key; 1916} 1917 1918static struct aesgcm_ctx *snp_init_crypto(u8 *key, size_t keylen) 1919{ 1920 struct aesgcm_ctx *ctx; 1921 1922 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); 1923 if (!ctx) 1924 return NULL; 1925 1926 if (aesgcm_expandkey(ctx, key, keylen, AUTHTAG_LEN)) { 1927 pr_err("Crypto context initialization failed\n"); 1928 kfree(ctx); 1929 return NULL; 1930 } 1931 1932 return ctx; 1933} 1934 1935int snp_msg_init(struct snp_msg_desc *mdesc, int vmpck_id) 1936{ 1937 /* Adjust the default VMPCK key based on the executing VMPL level */ 1938 if (vmpck_id == -1) 1939 vmpck_id = snp_vmpl; 1940 1941 mdesc->vmpck = get_vmpck(vmpck_id, mdesc->secrets, &mdesc->os_area_msg_seqno); 1942 if (!mdesc->vmpck) { 1943 pr_err("Invalid VMPCK%d communication key\n", vmpck_id); 1944 return -EINVAL; 1945 } 1946 1947 /* Verify that VMPCK is not zero. */ 1948 if (!memchr_inv(mdesc->vmpck, 0, VMPCK_KEY_LEN)) { 1949 pr_err("Empty VMPCK%d communication key\n", vmpck_id); 1950 return -EINVAL; 1951 } 1952 1953 mdesc->vmpck_id = vmpck_id; 1954 1955 mdesc->ctx = snp_init_crypto(mdesc->vmpck, VMPCK_KEY_LEN); 1956 if (!mdesc->ctx) 1957 return -ENOMEM; 1958 1959 return 0; 1960} 1961EXPORT_SYMBOL_GPL(snp_msg_init); 1962 1963struct snp_msg_desc *snp_msg_alloc(void) 1964{ 1965 struct snp_msg_desc *mdesc; 1966 void __iomem *mem; 1967 1968 BUILD_BUG_ON(sizeof(struct snp_guest_msg) > PAGE_SIZE); 1969 1970 mdesc = kzalloc(sizeof(struct snp_msg_desc), GFP_KERNEL); 1971 if (!mdesc) 1972 return ERR_PTR(-ENOMEM); 1973 1974 mem = ioremap_encrypted(sev_secrets_pa, PAGE_SIZE); 1975 if (!mem) 1976 goto e_free_mdesc; 1977 1978 mdesc->secrets = (__force struct snp_secrets_page *)mem; 1979 1980 /* Allocate the shared page used for the request and response message. */ 1981 mdesc->request = alloc_shared_pages(sizeof(struct snp_guest_msg)); 1982 if (!mdesc->request) 1983 goto e_unmap; 1984 1985 mdesc->response = alloc_shared_pages(sizeof(struct snp_guest_msg)); 1986 if (!mdesc->response) 1987 goto e_free_request; 1988 1989 return mdesc; 1990 1991e_free_request: 1992 free_shared_pages(mdesc->request, sizeof(struct snp_guest_msg)); 1993e_unmap: 1994 iounmap(mem); 1995e_free_mdesc: 1996 kfree(mdesc); 1997 1998 return ERR_PTR(-ENOMEM); 1999} 2000EXPORT_SYMBOL_GPL(snp_msg_alloc); 2001 2002void snp_msg_free(struct snp_msg_desc *mdesc) 2003{ 2004 if (!mdesc) 2005 return; 2006 2007 kfree(mdesc->ctx); 2008 free_shared_pages(mdesc->response, sizeof(struct snp_guest_msg)); 2009 free_shared_pages(mdesc->request, sizeof(struct snp_guest_msg)); 2010 iounmap((__force void __iomem *)mdesc->secrets); 2011 2012 kfree_sensitive(mdesc); 2013} 2014EXPORT_SYMBOL_GPL(snp_msg_free); 2015 2016/* Mutex to serialize the shared buffer access and command handling. */ 2017static DEFINE_MUTEX(snp_cmd_mutex); 2018 2019/* 2020 * If an error is received from the host or AMD Secure Processor (ASP) there 2021 * are two options. Either retry the exact same encrypted request or discontinue 2022 * using the VMPCK. 2023 * 2024 * This is because in the current encryption scheme GHCB v2 uses AES-GCM to 2025 * encrypt the requests. The IV for this scheme is the sequence number. GCM 2026 * cannot tolerate IV reuse. 2027 * 2028 * The ASP FW v1.51 only increments the sequence numbers on a successful 2029 * guest<->ASP back and forth and only accepts messages at its exact sequence 2030 * number. 2031 * 2032 * So if the sequence number were to be reused the encryption scheme is 2033 * vulnerable. If the sequence number were incremented for a fresh IV the ASP 2034 * will reject the request. 2035 */ 2036static void snp_disable_vmpck(struct snp_msg_desc *mdesc) 2037{ 2038 pr_alert("Disabling VMPCK%d communication key to prevent IV reuse.\n", 2039 mdesc->vmpck_id); 2040 memzero_explicit(mdesc->vmpck, VMPCK_KEY_LEN); 2041 mdesc->vmpck = NULL; 2042} 2043 2044static inline u64 __snp_get_msg_seqno(struct snp_msg_desc *mdesc) 2045{ 2046 u64 count; 2047 2048 lockdep_assert_held(&snp_cmd_mutex); 2049 2050 /* Read the current message sequence counter from secrets pages */ 2051 count = *mdesc->os_area_msg_seqno; 2052 2053 return count + 1; 2054} 2055 2056/* Return a non-zero on success */ 2057static u64 snp_get_msg_seqno(struct snp_msg_desc *mdesc) 2058{ 2059 u64 count = __snp_get_msg_seqno(mdesc); 2060 2061 /* 2062 * The message sequence counter for the SNP guest request is a 64-bit 2063 * value but the version 2 of GHCB specification defines a 32-bit storage 2064 * for it. If the counter exceeds the 32-bit value then return zero. 2065 * The caller should check the return value, but if the caller happens to 2066 * not check the value and use it, then the firmware treats zero as an 2067 * invalid number and will fail the message request. 2068 */ 2069 if (count >= UINT_MAX) { 2070 pr_err("request message sequence counter overflow\n"); 2071 return 0; 2072 } 2073 2074 return count; 2075} 2076 2077static void snp_inc_msg_seqno(struct snp_msg_desc *mdesc) 2078{ 2079 /* 2080 * The counter is also incremented by the PSP, so increment it by 2 2081 * and save in secrets page. 2082 */ 2083 *mdesc->os_area_msg_seqno += 2; 2084} 2085 2086static int verify_and_dec_payload(struct snp_msg_desc *mdesc, struct snp_guest_req *req) 2087{ 2088 struct snp_guest_msg *resp_msg = &mdesc->secret_response; 2089 struct snp_guest_msg *req_msg = &mdesc->secret_request; 2090 struct snp_guest_msg_hdr *req_msg_hdr = &req_msg->hdr; 2091 struct snp_guest_msg_hdr *resp_msg_hdr = &resp_msg->hdr; 2092 struct aesgcm_ctx *ctx = mdesc->ctx; 2093 u8 iv[GCM_AES_IV_SIZE] = {}; 2094 2095 pr_debug("response [seqno %lld type %d version %d sz %d]\n", 2096 resp_msg_hdr->msg_seqno, resp_msg_hdr->msg_type, resp_msg_hdr->msg_version, 2097 resp_msg_hdr->msg_sz); 2098 2099 /* Copy response from shared memory to encrypted memory. */ 2100 memcpy(resp_msg, mdesc->response, sizeof(*resp_msg)); 2101 2102 /* Verify that the sequence counter is incremented by 1 */ 2103 if (unlikely(resp_msg_hdr->msg_seqno != (req_msg_hdr->msg_seqno + 1))) 2104 return -EBADMSG; 2105 2106 /* Verify response message type and version number. */ 2107 if (resp_msg_hdr->msg_type != (req_msg_hdr->msg_type + 1) || 2108 resp_msg_hdr->msg_version != req_msg_hdr->msg_version) 2109 return -EBADMSG; 2110 2111 /* 2112 * If the message size is greater than our buffer length then return 2113 * an error. 2114 */ 2115 if (unlikely((resp_msg_hdr->msg_sz + ctx->authsize) > req->resp_sz)) 2116 return -EBADMSG; 2117 2118 /* Decrypt the payload */ 2119 memcpy(iv, &resp_msg_hdr->msg_seqno, min(sizeof(iv), sizeof(resp_msg_hdr->msg_seqno))); 2120 if (!aesgcm_decrypt(ctx, req->resp_buf, resp_msg->payload, resp_msg_hdr->msg_sz, 2121 &resp_msg_hdr->algo, AAD_LEN, iv, resp_msg_hdr->authtag)) 2122 return -EBADMSG; 2123 2124 return 0; 2125} 2126 2127static int enc_payload(struct snp_msg_desc *mdesc, u64 seqno, struct snp_guest_req *req) 2128{ 2129 struct snp_guest_msg *msg = &mdesc->secret_request; 2130 struct snp_guest_msg_hdr *hdr = &msg->hdr; 2131 struct aesgcm_ctx *ctx = mdesc->ctx; 2132 u8 iv[GCM_AES_IV_SIZE] = {}; 2133 2134 memset(msg, 0, sizeof(*msg)); 2135 2136 hdr->algo = SNP_AEAD_AES_256_GCM; 2137 hdr->hdr_version = MSG_HDR_VER; 2138 hdr->hdr_sz = sizeof(*hdr); 2139 hdr->msg_type = req->msg_type; 2140 hdr->msg_version = req->msg_version; 2141 hdr->msg_seqno = seqno; 2142 hdr->msg_vmpck = req->vmpck_id; 2143 hdr->msg_sz = req->req_sz; 2144 2145 /* Verify the sequence number is non-zero */ 2146 if (!hdr->msg_seqno) 2147 return -ENOSR; 2148 2149 pr_debug("request [seqno %lld type %d version %d sz %d]\n", 2150 hdr->msg_seqno, hdr->msg_type, hdr->msg_version, hdr->msg_sz); 2151 2152 if (WARN_ON((req->req_sz + ctx->authsize) > sizeof(msg->payload))) 2153 return -EBADMSG; 2154 2155 memcpy(iv, &hdr->msg_seqno, min(sizeof(iv), sizeof(hdr->msg_seqno))); 2156 aesgcm_encrypt(ctx, msg->payload, req->req_buf, req->req_sz, &hdr->algo, 2157 AAD_LEN, iv, hdr->authtag); 2158 2159 return 0; 2160} 2161 2162static int __handle_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *req) 2163{ 2164 unsigned long req_start = jiffies; 2165 unsigned int override_npages = 0; 2166 u64 override_err = 0; 2167 int rc; 2168 2169retry_request: 2170 /* 2171 * Call firmware to process the request. In this function the encrypted 2172 * message enters shared memory with the host. So after this call the 2173 * sequence number must be incremented or the VMPCK must be deleted to 2174 * prevent reuse of the IV. 2175 */ 2176 rc = snp_issue_guest_request(req); 2177 switch (rc) { 2178 case -ENOSPC: 2179 /* 2180 * If the extended guest request fails due to having too 2181 * small of a certificate data buffer, retry the same 2182 * guest request without the extended data request in 2183 * order to increment the sequence number and thus avoid 2184 * IV reuse. 2185 */ 2186 override_npages = req->input.data_npages; 2187 req->exit_code = SVM_VMGEXIT_GUEST_REQUEST; 2188 2189 /* 2190 * Override the error to inform callers the given extended 2191 * request buffer size was too small and give the caller the 2192 * required buffer size. 2193 */ 2194 override_err = SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN); 2195 2196 /* 2197 * If this call to the firmware succeeds, the sequence number can 2198 * be incremented allowing for continued use of the VMPCK. If 2199 * there is an error reflected in the return value, this value 2200 * is checked further down and the result will be the deletion 2201 * of the VMPCK and the error code being propagated back to the 2202 * user as an ioctl() return code. 2203 */ 2204 goto retry_request; 2205 2206 /* 2207 * The host may return SNP_GUEST_VMM_ERR_BUSY if the request has been 2208 * throttled. Retry in the driver to avoid returning and reusing the 2209 * message sequence number on a different message. 2210 */ 2211 case -EAGAIN: 2212 if (jiffies - req_start > SNP_REQ_MAX_RETRY_DURATION) { 2213 rc = -ETIMEDOUT; 2214 break; 2215 } 2216 schedule_timeout_killable(SNP_REQ_RETRY_DELAY); 2217 goto retry_request; 2218 } 2219 2220 /* 2221 * Increment the message sequence number. There is no harm in doing 2222 * this now because decryption uses the value stored in the response 2223 * structure and any failure will wipe the VMPCK, preventing further 2224 * use anyway. 2225 */ 2226 snp_inc_msg_seqno(mdesc); 2227 2228 if (override_err) { 2229 req->exitinfo2 = override_err; 2230 2231 /* 2232 * If an extended guest request was issued and the supplied certificate 2233 * buffer was not large enough, a standard guest request was issued to 2234 * prevent IV reuse. If the standard request was successful, return -EIO 2235 * back to the caller as would have originally been returned. 2236 */ 2237 if (!rc && override_err == SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN)) 2238 rc = -EIO; 2239 } 2240 2241 if (override_npages) 2242 req->input.data_npages = override_npages; 2243 2244 return rc; 2245} 2246 2247int snp_send_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *req) 2248{ 2249 u64 seqno; 2250 int rc; 2251 2252 /* 2253 * enc_payload() calls aesgcm_encrypt(), which can potentially offload to HW. 2254 * The offload's DMA SG list of data to encrypt has to be in linear mapping. 2255 */ 2256 if (!virt_addr_valid(req->req_buf) || !virt_addr_valid(req->resp_buf)) { 2257 pr_warn("AES-GSM buffers must be in linear mapping"); 2258 return -EINVAL; 2259 } 2260 2261 guard(mutex)(&snp_cmd_mutex); 2262 2263 /* Check if the VMPCK is not empty */ 2264 if (!mdesc->vmpck || !memchr_inv(mdesc->vmpck, 0, VMPCK_KEY_LEN)) { 2265 pr_err_ratelimited("VMPCK is disabled\n"); 2266 return -ENOTTY; 2267 } 2268 2269 /* Get message sequence and verify that its a non-zero */ 2270 seqno = snp_get_msg_seqno(mdesc); 2271 if (!seqno) 2272 return -EIO; 2273 2274 /* Clear shared memory's response for the host to populate. */ 2275 memset(mdesc->response, 0, sizeof(struct snp_guest_msg)); 2276 2277 /* Encrypt the userspace provided payload in mdesc->secret_request. */ 2278 rc = enc_payload(mdesc, seqno, req); 2279 if (rc) 2280 return rc; 2281 2282 /* 2283 * Write the fully encrypted request to the shared unencrypted 2284 * request page. 2285 */ 2286 memcpy(mdesc->request, &mdesc->secret_request, sizeof(mdesc->secret_request)); 2287 2288 /* Initialize the input address for guest request */ 2289 req->input.req_gpa = __pa(mdesc->request); 2290 req->input.resp_gpa = __pa(mdesc->response); 2291 req->input.data_gpa = req->certs_data ? __pa(req->certs_data) : 0; 2292 2293 rc = __handle_guest_request(mdesc, req); 2294 if (rc) { 2295 if (rc == -EIO && 2296 req->exitinfo2 == SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN)) 2297 return rc; 2298 2299 pr_alert("Detected error from ASP request. rc: %d, exitinfo2: 0x%llx\n", 2300 rc, req->exitinfo2); 2301 2302 snp_disable_vmpck(mdesc); 2303 return rc; 2304 } 2305 2306 rc = verify_and_dec_payload(mdesc, req); 2307 if (rc) { 2308 pr_alert("Detected unexpected decode failure from ASP. rc: %d\n", rc); 2309 snp_disable_vmpck(mdesc); 2310 return rc; 2311 } 2312 2313 return 0; 2314} 2315EXPORT_SYMBOL_GPL(snp_send_guest_request); 2316 2317static int __init snp_get_tsc_info(void) 2318{ 2319 struct snp_tsc_info_resp *tsc_resp; 2320 struct snp_tsc_info_req *tsc_req; 2321 struct snp_msg_desc *mdesc; 2322 struct snp_guest_req req = {}; 2323 int rc = -ENOMEM; 2324 2325 tsc_req = kzalloc(sizeof(*tsc_req), GFP_KERNEL); 2326 if (!tsc_req) 2327 return rc; 2328 2329 /* 2330 * The intermediate response buffer is used while decrypting the 2331 * response payload. Make sure that it has enough space to cover 2332 * the authtag. 2333 */ 2334 tsc_resp = kzalloc(sizeof(*tsc_resp) + AUTHTAG_LEN, GFP_KERNEL); 2335 if (!tsc_resp) 2336 goto e_free_tsc_req; 2337 2338 mdesc = snp_msg_alloc(); 2339 if (IS_ERR_OR_NULL(mdesc)) 2340 goto e_free_tsc_resp; 2341 2342 rc = snp_msg_init(mdesc, snp_vmpl); 2343 if (rc) 2344 goto e_free_mdesc; 2345 2346 req.msg_version = MSG_HDR_VER; 2347 req.msg_type = SNP_MSG_TSC_INFO_REQ; 2348 req.vmpck_id = snp_vmpl; 2349 req.req_buf = tsc_req; 2350 req.req_sz = sizeof(*tsc_req); 2351 req.resp_buf = (void *)tsc_resp; 2352 req.resp_sz = sizeof(*tsc_resp) + AUTHTAG_LEN; 2353 req.exit_code = SVM_VMGEXIT_GUEST_REQUEST; 2354 2355 rc = snp_send_guest_request(mdesc, &req); 2356 if (rc) 2357 goto e_request; 2358 2359 pr_debug("%s: response status 0x%x scale 0x%llx offset 0x%llx factor 0x%x\n", 2360 __func__, tsc_resp->status, tsc_resp->tsc_scale, tsc_resp->tsc_offset, 2361 tsc_resp->tsc_factor); 2362 2363 if (!tsc_resp->status) { 2364 snp_tsc_scale = tsc_resp->tsc_scale; 2365 snp_tsc_offset = tsc_resp->tsc_offset; 2366 } else { 2367 pr_err("Failed to get TSC info, response status 0x%x\n", tsc_resp->status); 2368 rc = -EIO; 2369 } 2370 2371e_request: 2372 /* The response buffer contains sensitive data, explicitly clear it. */ 2373 memzero_explicit(tsc_resp, sizeof(*tsc_resp) + AUTHTAG_LEN); 2374e_free_mdesc: 2375 snp_msg_free(mdesc); 2376e_free_tsc_resp: 2377 kfree(tsc_resp); 2378e_free_tsc_req: 2379 kfree(tsc_req); 2380 2381 return rc; 2382} 2383 2384void __init snp_secure_tsc_prepare(void) 2385{ 2386 if (!cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC)) 2387 return; 2388 2389 if (snp_get_tsc_info()) { 2390 pr_alert("Unable to retrieve Secure TSC info from ASP\n"); 2391 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECURE_TSC); 2392 } 2393 2394 pr_debug("SecureTSC enabled"); 2395} 2396 2397static unsigned long securetsc_get_tsc_khz(void) 2398{ 2399 return snp_tsc_freq_khz; 2400} 2401 2402void __init snp_secure_tsc_init(void) 2403{ 2404 struct snp_secrets_page *secrets; 2405 unsigned long tsc_freq_mhz; 2406 void *mem; 2407 2408 if (!cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC)) 2409 return; 2410 2411 mem = early_memremap_encrypted(sev_secrets_pa, PAGE_SIZE); 2412 if (!mem) { 2413 pr_err("Unable to get TSC_FACTOR: failed to map the SNP secrets page.\n"); 2414 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECURE_TSC); 2415 } 2416 2417 secrets = (__force struct snp_secrets_page *)mem; 2418 2419 setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ); 2420 rdmsrq(MSR_AMD64_GUEST_TSC_FREQ, tsc_freq_mhz); 2421 2422 /* Extract the GUEST TSC MHZ from BIT[17:0], rest is reserved space */ 2423 tsc_freq_mhz &= GENMASK_ULL(17, 0); 2424 2425 snp_tsc_freq_khz = SNP_SCALE_TSC_FREQ(tsc_freq_mhz * 1000, secrets->tsc_factor); 2426 2427 x86_platform.calibrate_cpu = securetsc_get_tsc_khz; 2428 x86_platform.calibrate_tsc = securetsc_get_tsc_khz; 2429 2430 early_memunmap(mem, PAGE_SIZE); 2431}
~/
Read-only file preview.