1 // SPDX-License-Identifier: GPL-2.0-only
3 * AMD Secure Encrypted Virtualization (SEV) interface
5 * Copyright (C) 2016,2019 Advanced Micro Devices, Inc.
7 * Author: Brijesh Singh <brijesh.singh@amd.com>
10 #include <linux/bitfield.h>
11 #include <linux/module.h>
12 #include <linux/kernel.h>
13 #include <linux/kthread.h>
14 #include <linux/sched.h>
15 #include <linux/interrupt.h>
16 #include <linux/spinlock.h>
17 #include <linux/spinlock_types.h>
18 #include <linux/types.h>
19 #include <linux/mutex.h>
20 #include <linux/delay.h>
21 #include <linux/hw_random.h>
22 #include <linux/ccp.h>
23 #include <linux/firmware.h>
24 #include <linux/panic_notifier.h>
25 #include <linux/gfp.h>
26 #include <linux/cpufeature.h>
28 #include <linux/fs_struct.h>
29 #include <linux/psp.h>
30 #include <linux/amd-iommu.h>
33 #include <asm/cacheflush.h>
34 #include <asm/e820/types.h>
40 #define DEVICE_NAME "sev"
41 #define SEV_FW_FILE "amd/sev.fw"
42 #define SEV_FW_NAME_SIZE 64
44 /* Minimum firmware version required for the SEV-SNP support */
45 #define SNP_MIN_API_MAJOR 1
46 #define SNP_MIN_API_MINOR 51
49 * Maximum number of firmware-writable buffers that might be specified
50 * in the parameters of a legacy SEV command buffer.
52 #define CMD_BUF_FW_WRITABLE_MAX 2
54 /* Leave room in the descriptor array for an end-of-list indicator. */
55 #define CMD_BUF_DESC_MAX (CMD_BUF_FW_WRITABLE_MAX + 1)
57 static DEFINE_MUTEX(sev_cmd_mutex);
58 static struct sev_misc_dev *misc_dev;
60 static int psp_cmd_timeout = 100;
61 module_param(psp_cmd_timeout, int, 0644);
62 MODULE_PARM_DESC(psp_cmd_timeout, " default timeout value, in seconds, for PSP commands");
64 static int psp_probe_timeout = 5;
65 module_param(psp_probe_timeout, int, 0644);
66 MODULE_PARM_DESC(psp_probe_timeout, " default timeout value, in seconds, during PSP device probe");
68 static char *init_ex_path;
69 module_param(init_ex_path, charp, 0444);
70 MODULE_PARM_DESC(init_ex_path, " Path for INIT_EX data; if set try INIT_EX");
72 static bool psp_init_on_probe = true;
73 module_param(psp_init_on_probe, bool, 0444);
74 MODULE_PARM_DESC(psp_init_on_probe, " if true, the PSP will be initialized on module init. Else the PSP will be initialized on the first command requiring it");
76 MODULE_FIRMWARE("amd/amd_sev_fam17h_model0xh.sbin"); /* 1st gen EPYC */
77 MODULE_FIRMWARE("amd/amd_sev_fam17h_model3xh.sbin"); /* 2nd gen EPYC */
78 MODULE_FIRMWARE("amd/amd_sev_fam19h_model0xh.sbin"); /* 3rd gen EPYC */
79 MODULE_FIRMWARE("amd/amd_sev_fam19h_model1xh.sbin"); /* 4th gen EPYC */
82 static int psp_timeout;
84 /* Trusted Memory Region (TMR):
85 * The TMR is a 1MB area that must be 1MB aligned. Use the page allocator
86 * to allocate the memory, which will return aligned memory for the specified
89 * When SEV-SNP is enabled the TMR needs to be 2MB aligned and 2MB sized.
91 #define SEV_TMR_SIZE (1024 * 1024)
92 #define SNP_TMR_SIZE (2 * 1024 * 1024)
94 static void *sev_es_tmr;
95 static size_t sev_es_tmr_size = SEV_TMR_SIZE;
97 /* INIT_EX NV Storage:
98 * The NV Storage is a 32Kb area and must be 4Kb page aligned. Use the page
99 * allocator to allocate the memory, which will return aligned memory for the
100 * specified allocation order.
102 #define NV_LENGTH (32 * 1024)
103 static void *sev_init_ex_buffer;
106 * SEV_DATA_RANGE_LIST:
107 * Array containing range of pages that firmware transitions to HV-fixed
110 static struct sev_data_range_list *snp_range_list;
112 static inline bool sev_version_greater_or_equal(u8 maj, u8 min)
114 struct sev_device *sev = psp_master->sev_data;
116 if (sev->api_major > maj)
119 if (sev->api_major == maj && sev->api_minor >= min)
125 static void sev_irq_handler(int irq, void *data, unsigned int status)
127 struct sev_device *sev = data;
130 /* Check if it is command completion: */
131 if (!(status & SEV_CMD_COMPLETE))
134 /* Check if it is SEV command completion: */
135 reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
136 if (FIELD_GET(PSP_CMDRESP_RESP, reg)) {
138 wake_up(&sev->int_queue);
142 static int sev_wait_cmd_ioc(struct sev_device *sev,
143 unsigned int *reg, unsigned int timeout)
148 * If invoked during panic handling, local interrupts are disabled,
149 * so the PSP command completion interrupt can't be used. Poll for
150 * PSP command completion instead.
152 if (irqs_disabled()) {
153 unsigned long timeout_usecs = (timeout * USEC_PER_SEC) / 10;
155 /* Poll for SEV command completion: */
156 while (timeout_usecs--) {
157 *reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
158 if (*reg & PSP_CMDRESP_RESP)
166 ret = wait_event_timeout(sev->int_queue,
167 sev->int_rcvd, timeout * HZ);
171 *reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
176 static int sev_cmd_buffer_len(int cmd)
179 case SEV_CMD_INIT: return sizeof(struct sev_data_init);
180 case SEV_CMD_INIT_EX: return sizeof(struct sev_data_init_ex);
181 case SEV_CMD_SNP_SHUTDOWN_EX: return sizeof(struct sev_data_snp_shutdown_ex);
182 case SEV_CMD_SNP_INIT_EX: return sizeof(struct sev_data_snp_init_ex);
183 case SEV_CMD_PLATFORM_STATUS: return sizeof(struct sev_user_data_status);
184 case SEV_CMD_PEK_CSR: return sizeof(struct sev_data_pek_csr);
185 case SEV_CMD_PEK_CERT_IMPORT: return sizeof(struct sev_data_pek_cert_import);
186 case SEV_CMD_PDH_CERT_EXPORT: return sizeof(struct sev_data_pdh_cert_export);
187 case SEV_CMD_LAUNCH_START: return sizeof(struct sev_data_launch_start);
188 case SEV_CMD_LAUNCH_UPDATE_DATA: return sizeof(struct sev_data_launch_update_data);
189 case SEV_CMD_LAUNCH_UPDATE_VMSA: return sizeof(struct sev_data_launch_update_vmsa);
190 case SEV_CMD_LAUNCH_FINISH: return sizeof(struct sev_data_launch_finish);
191 case SEV_CMD_LAUNCH_MEASURE: return sizeof(struct sev_data_launch_measure);
192 case SEV_CMD_ACTIVATE: return sizeof(struct sev_data_activate);
193 case SEV_CMD_DEACTIVATE: return sizeof(struct sev_data_deactivate);
194 case SEV_CMD_DECOMMISSION: return sizeof(struct sev_data_decommission);
195 case SEV_CMD_GUEST_STATUS: return sizeof(struct sev_data_guest_status);
196 case SEV_CMD_DBG_DECRYPT: return sizeof(struct sev_data_dbg);
197 case SEV_CMD_DBG_ENCRYPT: return sizeof(struct sev_data_dbg);
198 case SEV_CMD_SEND_START: return sizeof(struct sev_data_send_start);
199 case SEV_CMD_SEND_UPDATE_DATA: return sizeof(struct sev_data_send_update_data);
200 case SEV_CMD_SEND_UPDATE_VMSA: return sizeof(struct sev_data_send_update_vmsa);
201 case SEV_CMD_SEND_FINISH: return sizeof(struct sev_data_send_finish);
202 case SEV_CMD_RECEIVE_START: return sizeof(struct sev_data_receive_start);
203 case SEV_CMD_RECEIVE_FINISH: return sizeof(struct sev_data_receive_finish);
204 case SEV_CMD_RECEIVE_UPDATE_DATA: return sizeof(struct sev_data_receive_update_data);
205 case SEV_CMD_RECEIVE_UPDATE_VMSA: return sizeof(struct sev_data_receive_update_vmsa);
206 case SEV_CMD_LAUNCH_UPDATE_SECRET: return sizeof(struct sev_data_launch_secret);
207 case SEV_CMD_DOWNLOAD_FIRMWARE: return sizeof(struct sev_data_download_firmware);
208 case SEV_CMD_GET_ID: return sizeof(struct sev_data_get_id);
209 case SEV_CMD_ATTESTATION_REPORT: return sizeof(struct sev_data_attestation_report);
210 case SEV_CMD_SEND_CANCEL: return sizeof(struct sev_data_send_cancel);
211 case SEV_CMD_SNP_GCTX_CREATE: return sizeof(struct sev_data_snp_addr);
212 case SEV_CMD_SNP_LAUNCH_START: return sizeof(struct sev_data_snp_launch_start);
213 case SEV_CMD_SNP_LAUNCH_UPDATE: return sizeof(struct sev_data_snp_launch_update);
214 case SEV_CMD_SNP_ACTIVATE: return sizeof(struct sev_data_snp_activate);
215 case SEV_CMD_SNP_DECOMMISSION: return sizeof(struct sev_data_snp_addr);
216 case SEV_CMD_SNP_PAGE_RECLAIM: return sizeof(struct sev_data_snp_page_reclaim);
217 case SEV_CMD_SNP_GUEST_STATUS: return sizeof(struct sev_data_snp_guest_status);
218 case SEV_CMD_SNP_LAUNCH_FINISH: return sizeof(struct sev_data_snp_launch_finish);
219 case SEV_CMD_SNP_DBG_DECRYPT: return sizeof(struct sev_data_snp_dbg);
220 case SEV_CMD_SNP_DBG_ENCRYPT: return sizeof(struct sev_data_snp_dbg);
221 case SEV_CMD_SNP_PAGE_UNSMASH: return sizeof(struct sev_data_snp_page_unsmash);
222 case SEV_CMD_SNP_PLATFORM_STATUS: return sizeof(struct sev_data_snp_addr);
223 case SEV_CMD_SNP_GUEST_REQUEST: return sizeof(struct sev_data_snp_guest_request);
224 case SEV_CMD_SNP_CONFIG: return sizeof(struct sev_user_data_snp_config);
225 case SEV_CMD_SNP_COMMIT: return sizeof(struct sev_data_snp_commit);
232 static struct file *open_file_as_root(const char *filename, int flags, umode_t mode)
237 const struct cred *old_cred;
239 task_lock(&init_task);
240 get_fs_root(init_task.fs, &root);
241 task_unlock(&init_task);
243 cred = prepare_creds();
245 return ERR_PTR(-ENOMEM);
246 cred->fsuid = GLOBAL_ROOT_UID;
247 old_cred = override_creds(cred);
249 fp = file_open_root(&root, filename, flags, mode);
252 revert_creds(old_cred);
257 static int sev_read_init_ex_file(void)
259 struct sev_device *sev = psp_master->sev_data;
263 lockdep_assert_held(&sev_cmd_mutex);
265 if (!sev_init_ex_buffer)
268 fp = open_file_as_root(init_ex_path, O_RDONLY, 0);
270 int ret = PTR_ERR(fp);
272 if (ret == -ENOENT) {
274 "SEV: %s does not exist and will be created later.\n",
279 "SEV: could not open %s for read, error %d\n",
285 nread = kernel_read(fp, sev_init_ex_buffer, NV_LENGTH, NULL);
286 if (nread != NV_LENGTH) {
288 "SEV: could not read %u bytes to non volatile memory area, ret %ld\n",
292 dev_dbg(sev->dev, "SEV: read %ld bytes from NV file\n", nread);
293 filp_close(fp, NULL);
298 static int sev_write_init_ex_file(void)
300 struct sev_device *sev = psp_master->sev_data;
305 lockdep_assert_held(&sev_cmd_mutex);
307 if (!sev_init_ex_buffer)
310 fp = open_file_as_root(init_ex_path, O_CREAT | O_WRONLY, 0600);
312 int ret = PTR_ERR(fp);
315 "SEV: could not open file for write, error %d\n",
320 nwrite = kernel_write(fp, sev_init_ex_buffer, NV_LENGTH, &offset);
322 filp_close(fp, NULL);
324 if (nwrite != NV_LENGTH) {
326 "SEV: failed to write %u bytes to non volatile memory area, ret %ld\n",
331 dev_dbg(sev->dev, "SEV: write successful to NV file\n");
336 static int sev_write_init_ex_file_if_required(int cmd_id)
338 lockdep_assert_held(&sev_cmd_mutex);
340 if (!sev_init_ex_buffer)
344 * Only a few platform commands modify the SPI/NV area, but none of the
345 * non-platform commands do. Only INIT(_EX), PLATFORM_RESET, PEK_GEN,
346 * PEK_CERT_IMPORT, and PDH_GEN do.
349 case SEV_CMD_FACTORY_RESET:
350 case SEV_CMD_INIT_EX:
351 case SEV_CMD_PDH_GEN:
352 case SEV_CMD_PEK_CERT_IMPORT:
353 case SEV_CMD_PEK_GEN:
359 return sev_write_init_ex_file();
363 * snp_reclaim_pages() needs __sev_do_cmd_locked(), and __sev_do_cmd_locked()
364 * needs snp_reclaim_pages(), so a forward declaration is needed.
366 static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret);
368 static int snp_reclaim_pages(unsigned long paddr, unsigned int npages, bool locked)
372 paddr = __sme_clr(ALIGN_DOWN(paddr, PAGE_SIZE));
374 for (i = 0; i < npages; i++, paddr += PAGE_SIZE) {
375 struct sev_data_snp_page_reclaim data = {0};
380 ret = __sev_do_cmd_locked(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
382 ret = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
387 ret = rmp_make_shared(__phys_to_pfn(paddr), PG_LEVEL_4K);
396 * If there was a failure reclaiming the page then it is no longer safe
397 * to release it back to the system; leak it instead.
399 snp_leak_pages(__phys_to_pfn(paddr), npages - i);
403 static int rmp_mark_pages_firmware(unsigned long paddr, unsigned int npages, bool locked)
405 unsigned long pfn = __sme_clr(paddr) >> PAGE_SHIFT;
408 for (i = 0; i < npages; i++, pfn++) {
409 rc = rmp_make_private(pfn, 0, PG_LEVEL_4K, 0, true);
418 * Try unrolling the firmware state changes by
419 * reclaiming the pages which were already changed to the
422 snp_reclaim_pages(paddr, i, locked);
427 static struct page *__snp_alloc_firmware_pages(gfp_t gfp_mask, int order)
429 unsigned long npages = 1ul << order, paddr;
430 struct sev_device *sev;
433 if (!psp_master || !psp_master->sev_data)
436 page = alloc_pages(gfp_mask, order);
440 /* If SEV-SNP is initialized then add the page in RMP table. */
441 sev = psp_master->sev_data;
442 if (!sev->snp_initialized)
445 paddr = __pa((unsigned long)page_address(page));
446 if (rmp_mark_pages_firmware(paddr, npages, false))
452 void *snp_alloc_firmware_page(gfp_t gfp_mask)
456 page = __snp_alloc_firmware_pages(gfp_mask, 0);
458 return page ? page_address(page) : NULL;
460 EXPORT_SYMBOL_GPL(snp_alloc_firmware_page);
462 static void __snp_free_firmware_pages(struct page *page, int order, bool locked)
464 struct sev_device *sev = psp_master->sev_data;
465 unsigned long paddr, npages = 1ul << order;
470 paddr = __pa((unsigned long)page_address(page));
471 if (sev->snp_initialized &&
472 snp_reclaim_pages(paddr, npages, locked))
475 __free_pages(page, order);
478 void snp_free_firmware_page(void *addr)
483 __snp_free_firmware_pages(virt_to_page(addr), 0, false);
485 EXPORT_SYMBOL_GPL(snp_free_firmware_page);
487 static void *sev_fw_alloc(unsigned long len)
491 page = __snp_alloc_firmware_pages(GFP_KERNEL, get_order(len));
495 return page_address(page);
499 * struct cmd_buf_desc - descriptors for managing legacy SEV command address
500 * parameters corresponding to buffers that may be written to by firmware.
502 * @paddr_ptr: pointer to the address parameter in the command buffer which may
503 * need to be saved/restored depending on whether a bounce buffer
504 * is used. In the case of a bounce buffer, the command buffer
505 * needs to be updated with the address of the new bounce buffer
506 * snp_map_cmd_buf_desc() has allocated specifically for it. Must
507 * be NULL if this descriptor is only an end-of-list indicator.
509 * @paddr_orig: storage for the original address parameter, which can be used to
510 * restore the original value in @paddr_ptr in cases where it is
511 * replaced with the address of a bounce buffer.
513 * @len: length of buffer located at the address originally stored at @paddr_ptr
515 * @guest_owned: true if the address corresponds to guest-owned pages, in which
516 * case bounce buffers are not needed.
518 struct cmd_buf_desc {
526 * If a legacy SEV command parameter is a memory address, those pages in
527 * turn need to be transitioned to/from firmware-owned before/after
528 * executing the firmware command.
530 * Additionally, in cases where those pages are not guest-owned, a bounce
531 * buffer is needed in place of the original memory address parameter.
533 * A set of descriptors are used to keep track of this handling, and
534 * initialized here based on the specific commands being executed.
536 static void snp_populate_cmd_buf_desc_list(int cmd, void *cmd_buf,
537 struct cmd_buf_desc *desc_list)
540 case SEV_CMD_PDH_CERT_EXPORT: {
541 struct sev_data_pdh_cert_export *data = cmd_buf;
543 desc_list[0].paddr_ptr = &data->pdh_cert_address;
544 desc_list[0].len = data->pdh_cert_len;
545 desc_list[1].paddr_ptr = &data->cert_chain_address;
546 desc_list[1].len = data->cert_chain_len;
549 case SEV_CMD_GET_ID: {
550 struct sev_data_get_id *data = cmd_buf;
552 desc_list[0].paddr_ptr = &data->address;
553 desc_list[0].len = data->len;
556 case SEV_CMD_PEK_CSR: {
557 struct sev_data_pek_csr *data = cmd_buf;
559 desc_list[0].paddr_ptr = &data->address;
560 desc_list[0].len = data->len;
563 case SEV_CMD_LAUNCH_UPDATE_DATA: {
564 struct sev_data_launch_update_data *data = cmd_buf;
566 desc_list[0].paddr_ptr = &data->address;
567 desc_list[0].len = data->len;
568 desc_list[0].guest_owned = true;
571 case SEV_CMD_LAUNCH_UPDATE_VMSA: {
572 struct sev_data_launch_update_vmsa *data = cmd_buf;
574 desc_list[0].paddr_ptr = &data->address;
575 desc_list[0].len = data->len;
576 desc_list[0].guest_owned = true;
579 case SEV_CMD_LAUNCH_MEASURE: {
580 struct sev_data_launch_measure *data = cmd_buf;
582 desc_list[0].paddr_ptr = &data->address;
583 desc_list[0].len = data->len;
586 case SEV_CMD_LAUNCH_UPDATE_SECRET: {
587 struct sev_data_launch_secret *data = cmd_buf;
589 desc_list[0].paddr_ptr = &data->guest_address;
590 desc_list[0].len = data->guest_len;
591 desc_list[0].guest_owned = true;
594 case SEV_CMD_DBG_DECRYPT: {
595 struct sev_data_dbg *data = cmd_buf;
597 desc_list[0].paddr_ptr = &data->dst_addr;
598 desc_list[0].len = data->len;
599 desc_list[0].guest_owned = true;
602 case SEV_CMD_DBG_ENCRYPT: {
603 struct sev_data_dbg *data = cmd_buf;
605 desc_list[0].paddr_ptr = &data->dst_addr;
606 desc_list[0].len = data->len;
607 desc_list[0].guest_owned = true;
610 case SEV_CMD_ATTESTATION_REPORT: {
611 struct sev_data_attestation_report *data = cmd_buf;
613 desc_list[0].paddr_ptr = &data->address;
614 desc_list[0].len = data->len;
617 case SEV_CMD_SEND_START: {
618 struct sev_data_send_start *data = cmd_buf;
620 desc_list[0].paddr_ptr = &data->session_address;
621 desc_list[0].len = data->session_len;
624 case SEV_CMD_SEND_UPDATE_DATA: {
625 struct sev_data_send_update_data *data = cmd_buf;
627 desc_list[0].paddr_ptr = &data->hdr_address;
628 desc_list[0].len = data->hdr_len;
629 desc_list[1].paddr_ptr = &data->trans_address;
630 desc_list[1].len = data->trans_len;
633 case SEV_CMD_SEND_UPDATE_VMSA: {
634 struct sev_data_send_update_vmsa *data = cmd_buf;
636 desc_list[0].paddr_ptr = &data->hdr_address;
637 desc_list[0].len = data->hdr_len;
638 desc_list[1].paddr_ptr = &data->trans_address;
639 desc_list[1].len = data->trans_len;
642 case SEV_CMD_RECEIVE_UPDATE_DATA: {
643 struct sev_data_receive_update_data *data = cmd_buf;
645 desc_list[0].paddr_ptr = &data->guest_address;
646 desc_list[0].len = data->guest_len;
647 desc_list[0].guest_owned = true;
650 case SEV_CMD_RECEIVE_UPDATE_VMSA: {
651 struct sev_data_receive_update_vmsa *data = cmd_buf;
653 desc_list[0].paddr_ptr = &data->guest_address;
654 desc_list[0].len = data->guest_len;
655 desc_list[0].guest_owned = true;
663 static int snp_map_cmd_buf_desc(struct cmd_buf_desc *desc)
670 /* Allocate a bounce buffer if this isn't a guest owned page. */
671 if (!desc->guest_owned) {
674 page = alloc_pages(GFP_KERNEL_ACCOUNT, get_order(desc->len));
676 pr_warn("Failed to allocate bounce buffer for SEV legacy command.\n");
680 desc->paddr_orig = *desc->paddr_ptr;
681 *desc->paddr_ptr = __psp_pa(page_to_virt(page));
684 npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
686 /* Transition the buffer to firmware-owned. */
687 if (rmp_mark_pages_firmware(*desc->paddr_ptr, npages, true)) {
688 pr_warn("Error moving pages to firmware-owned state for SEV legacy command.\n");
695 static int snp_unmap_cmd_buf_desc(struct cmd_buf_desc *desc)
702 npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
704 /* Transition the buffers back to hypervisor-owned. */
705 if (snp_reclaim_pages(*desc->paddr_ptr, npages, true)) {
706 pr_warn("Failed to reclaim firmware-owned pages while issuing SEV legacy command.\n");
710 /* Copy data from bounce buffer and then free it. */
711 if (!desc->guest_owned) {
712 void *bounce_buf = __va(__sme_clr(*desc->paddr_ptr));
713 void *dst_buf = __va(__sme_clr(desc->paddr_orig));
715 memcpy(dst_buf, bounce_buf, desc->len);
716 __free_pages(virt_to_page(bounce_buf), get_order(desc->len));
718 /* Restore the original address in the command buffer. */
719 *desc->paddr_ptr = desc->paddr_orig;
725 static int snp_map_cmd_buf_desc_list(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
729 snp_populate_cmd_buf_desc_list(cmd, cmd_buf, desc_list);
731 for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
732 struct cmd_buf_desc *desc = &desc_list[i];
734 if (!desc->paddr_ptr)
737 if (snp_map_cmd_buf_desc(desc))
744 for (i--; i >= 0; i--)
745 snp_unmap_cmd_buf_desc(&desc_list[i]);
750 static int snp_unmap_cmd_buf_desc_list(struct cmd_buf_desc *desc_list)
754 for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
755 struct cmd_buf_desc *desc = &desc_list[i];
757 if (!desc->paddr_ptr)
760 if (snp_unmap_cmd_buf_desc(&desc_list[i]))
767 static bool sev_cmd_buf_writable(int cmd)
770 case SEV_CMD_PLATFORM_STATUS:
771 case SEV_CMD_GUEST_STATUS:
772 case SEV_CMD_LAUNCH_START:
773 case SEV_CMD_RECEIVE_START:
774 case SEV_CMD_LAUNCH_MEASURE:
775 case SEV_CMD_SEND_START:
776 case SEV_CMD_SEND_UPDATE_DATA:
777 case SEV_CMD_SEND_UPDATE_VMSA:
778 case SEV_CMD_PEK_CSR:
779 case SEV_CMD_PDH_CERT_EXPORT:
781 case SEV_CMD_ATTESTATION_REPORT:
788 /* After SNP is INIT'ed, the behavior of legacy SEV commands is changed. */
789 static bool snp_legacy_handling_needed(int cmd)
791 struct sev_device *sev = psp_master->sev_data;
793 return cmd < SEV_CMD_SNP_INIT && sev->snp_initialized;
796 static int snp_prep_cmd_buf(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
798 if (!snp_legacy_handling_needed(cmd))
801 if (snp_map_cmd_buf_desc_list(cmd, cmd_buf, desc_list))
805 * Before command execution, the command buffer needs to be put into
806 * the firmware-owned state.
808 if (sev_cmd_buf_writable(cmd)) {
809 if (rmp_mark_pages_firmware(__pa(cmd_buf), 1, true))
816 static int snp_reclaim_cmd_buf(int cmd, void *cmd_buf)
818 if (!snp_legacy_handling_needed(cmd))
822 * After command completion, the command buffer needs to be put back
823 * into the hypervisor-owned state.
825 if (sev_cmd_buf_writable(cmd))
826 if (snp_reclaim_pages(__pa(cmd_buf), 1, true))
832 static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret)
834 struct cmd_buf_desc desc_list[CMD_BUF_DESC_MAX] = {0};
835 struct psp_device *psp = psp_master;
836 struct sev_device *sev;
837 unsigned int cmdbuff_hi, cmdbuff_lo;
838 unsigned int phys_lsb, phys_msb;
839 unsigned int reg, ret = 0;
843 if (!psp || !psp->sev_data)
851 buf_len = sev_cmd_buffer_len(cmd);
852 if (WARN_ON_ONCE(!data != !buf_len))
856 * Copy the incoming data to driver's scratch buffer as __pa() will not
857 * work for some memory, e.g. vmalloc'd addresses, and @data may not be
858 * physically contiguous.
862 * Commands are generally issued one at a time and require the
863 * sev_cmd_mutex, but there could be recursive firmware requests
864 * due to SEV_CMD_SNP_PAGE_RECLAIM needing to be issued while
865 * preparing buffers for another command. This is the only known
866 * case of nesting in the current code, so exactly one
867 * additional command buffer is available for that purpose.
869 if (!sev->cmd_buf_active) {
870 cmd_buf = sev->cmd_buf;
871 sev->cmd_buf_active = true;
872 } else if (!sev->cmd_buf_backup_active) {
873 cmd_buf = sev->cmd_buf_backup;
874 sev->cmd_buf_backup_active = true;
877 "SEV: too many firmware commands in progress, no command buffers available.\n");
881 memcpy(cmd_buf, data, buf_len);
884 * The behavior of the SEV-legacy commands is altered when the
885 * SNP firmware is in the INIT state.
887 ret = snp_prep_cmd_buf(cmd, cmd_buf, desc_list);
890 "SEV: failed to prepare buffer for legacy command 0x%x. Error: %d\n",
895 cmd_buf = sev->cmd_buf;
898 /* Get the physical address of the command buffer */
899 phys_lsb = data ? lower_32_bits(__psp_pa(cmd_buf)) : 0;
900 phys_msb = data ? upper_32_bits(__psp_pa(cmd_buf)) : 0;
902 dev_dbg(sev->dev, "sev command id %#x buffer 0x%08x%08x timeout %us\n",
903 cmd, phys_msb, phys_lsb, psp_timeout);
905 print_hex_dump_debug("(in): ", DUMP_PREFIX_OFFSET, 16, 2, data,
908 iowrite32(phys_lsb, sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
909 iowrite32(phys_msb, sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
913 reg = FIELD_PREP(SEV_CMDRESP_CMD, cmd) | SEV_CMDRESP_IOC;
914 iowrite32(reg, sev->io_regs + sev->vdata->cmdresp_reg);
916 /* wait for command completion */
917 ret = sev_wait_cmd_ioc(sev, ®, psp_timeout);
922 dev_err(sev->dev, "sev command %#x timed out, disabling PSP\n", cmd);
928 psp_timeout = psp_cmd_timeout;
931 *psp_ret = FIELD_GET(PSP_CMDRESP_STS, reg);
933 if (FIELD_GET(PSP_CMDRESP_STS, reg)) {
934 dev_dbg(sev->dev, "sev command %#x failed (%#010lx)\n",
935 cmd, FIELD_GET(PSP_CMDRESP_STS, reg));
938 * PSP firmware may report additional error information in the
939 * command buffer registers on error. Print contents of command
940 * buffer registers if they changed.
942 cmdbuff_hi = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
943 cmdbuff_lo = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
944 if (cmdbuff_hi != phys_msb || cmdbuff_lo != phys_lsb) {
945 dev_dbg(sev->dev, "Additional error information reported in cmdbuff:");
946 dev_dbg(sev->dev, " cmdbuff hi: %#010x\n", cmdbuff_hi);
947 dev_dbg(sev->dev, " cmdbuff lo: %#010x\n", cmdbuff_lo);
951 ret = sev_write_init_ex_file_if_required(cmd);
955 * Copy potential output from the PSP back to data. Do this even on
956 * failure in case the caller wants to glean something from the error.
961 * Restore the page state after the command completes.
963 ret_reclaim = snp_reclaim_cmd_buf(cmd, cmd_buf);
966 "SEV: failed to reclaim buffer for legacy command %#x. Error: %d\n",
971 memcpy(data, cmd_buf, buf_len);
973 if (sev->cmd_buf_backup_active)
974 sev->cmd_buf_backup_active = false;
976 sev->cmd_buf_active = false;
978 if (snp_unmap_cmd_buf_desc_list(desc_list))
982 print_hex_dump_debug("(out): ", DUMP_PREFIX_OFFSET, 16, 2, data,
988 int sev_do_cmd(int cmd, void *data, int *psp_ret)
992 mutex_lock(&sev_cmd_mutex);
993 rc = __sev_do_cmd_locked(cmd, data, psp_ret);
994 mutex_unlock(&sev_cmd_mutex);
998 EXPORT_SYMBOL_GPL(sev_do_cmd);
1000 static int __sev_init_locked(int *error)
1002 struct sev_data_init data;
1004 memset(&data, 0, sizeof(data));
1007 * Do not include the encryption mask on the physical
1008 * address of the TMR (firmware should clear it anyway).
1010 data.tmr_address = __pa(sev_es_tmr);
1012 data.flags |= SEV_INIT_FLAGS_SEV_ES;
1013 data.tmr_len = sev_es_tmr_size;
1016 return __sev_do_cmd_locked(SEV_CMD_INIT, &data, error);
1019 static int __sev_init_ex_locked(int *error)
1021 struct sev_data_init_ex data;
1023 memset(&data, 0, sizeof(data));
1024 data.length = sizeof(data);
1025 data.nv_address = __psp_pa(sev_init_ex_buffer);
1026 data.nv_len = NV_LENGTH;
1030 * Do not include the encryption mask on the physical
1031 * address of the TMR (firmware should clear it anyway).
1033 data.tmr_address = __pa(sev_es_tmr);
1035 data.flags |= SEV_INIT_FLAGS_SEV_ES;
1036 data.tmr_len = sev_es_tmr_size;
1039 return __sev_do_cmd_locked(SEV_CMD_INIT_EX, &data, error);
1042 static inline int __sev_do_init_locked(int *psp_ret)
1044 if (sev_init_ex_buffer)
1045 return __sev_init_ex_locked(psp_ret);
1047 return __sev_init_locked(psp_ret);
1050 static void snp_set_hsave_pa(void *arg)
1052 wrmsrl(MSR_VM_HSAVE_PA, 0);
1055 static int snp_filter_reserved_mem_regions(struct resource *rs, void *arg)
1057 struct sev_data_range_list *range_list = arg;
1058 struct sev_data_range *range = &range_list->ranges[range_list->num_elements];
1062 * Ensure the list of HV_FIXED pages that will be passed to firmware
1063 * do not exceed the page-sized argument buffer.
1065 if ((range_list->num_elements * sizeof(struct sev_data_range) +
1066 sizeof(struct sev_data_range_list)) > PAGE_SIZE)
1070 case E820_TYPE_RESERVED:
1071 case E820_TYPE_PMEM:
1072 case E820_TYPE_ACPI:
1073 range->base = rs->start & PAGE_MASK;
1074 size = PAGE_ALIGN((rs->end + 1) - rs->start);
1075 range->page_count = size >> PAGE_SHIFT;
1076 range_list->num_elements++;
1085 static int __sev_snp_init_locked(int *error)
1087 struct psp_device *psp = psp_master;
1088 struct sev_data_snp_init_ex data;
1089 struct sev_device *sev;
1093 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
1096 sev = psp->sev_data;
1098 if (sev->snp_initialized)
1101 if (!sev_version_greater_or_equal(SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR)) {
1102 dev_dbg(sev->dev, "SEV-SNP support requires firmware version >= %d:%d\n",
1103 SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR);
1107 /* SNP_INIT requires MSR_VM_HSAVE_PA to be cleared on all CPUs. */
1108 on_each_cpu(snp_set_hsave_pa, NULL, 1);
1111 * Starting in SNP firmware v1.52, the SNP_INIT_EX command takes a list
1112 * of system physical address ranges to convert into HV-fixed page
1113 * states during the RMP initialization. For instance, the memory that
1114 * UEFI reserves should be included in the that list. This allows system
1115 * components that occasionally write to memory (e.g. logging to UEFI
1116 * reserved regions) to not fail due to RMP initialization and SNP
1120 if (sev_version_greater_or_equal(SNP_MIN_API_MAJOR, 52)) {
1122 * Firmware checks that the pages containing the ranges enumerated
1123 * in the RANGES structure are either in the default page state or in the
1124 * firmware page state.
1126 snp_range_list = kzalloc(PAGE_SIZE, GFP_KERNEL);
1127 if (!snp_range_list) {
1129 "SEV: SNP_INIT_EX range list memory allocation failed\n");
1134 * Retrieve all reserved memory regions from the e820 memory map
1135 * to be setup as HV-fixed pages.
1137 rc = walk_iomem_res_desc(IORES_DESC_NONE, IORESOURCE_MEM, 0, ~0,
1138 snp_range_list, snp_filter_reserved_mem_regions);
1141 "SEV: SNP_INIT_EX walk_iomem_res_desc failed rc = %d\n", rc);
1145 memset(&data, 0, sizeof(data));
1147 data.list_paddr_en = 1;
1148 data.list_paddr = __psp_pa(snp_range_list);
1149 cmd = SEV_CMD_SNP_INIT_EX;
1151 cmd = SEV_CMD_SNP_INIT;
1156 * The following sequence must be issued before launching the first SNP
1157 * guest to ensure all dirty cache lines are flushed, including from
1158 * updates to the RMP table itself via the RMPUPDATE instruction:
1160 * - WBINVD on all running CPUs
1161 * - SEV_CMD_SNP_INIT[_EX] firmware command
1162 * - WBINVD on all running CPUs
1163 * - SEV_CMD_SNP_DF_FLUSH firmware command
1165 wbinvd_on_all_cpus();
1167 rc = __sev_do_cmd_locked(cmd, arg, error);
1171 /* Prepare for first SNP guest launch after INIT. */
1172 wbinvd_on_all_cpus();
1173 rc = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, error);
1177 sev->snp_initialized = true;
1178 dev_dbg(sev->dev, "SEV-SNP firmware initialized\n");
1180 sev_es_tmr_size = SNP_TMR_SIZE;
1185 static void __sev_platform_init_handle_tmr(struct sev_device *sev)
1190 /* Obtain the TMR memory area for SEV-ES use */
1191 sev_es_tmr = sev_fw_alloc(sev_es_tmr_size);
1193 /* Must flush the cache before giving it to the firmware */
1194 if (!sev->snp_initialized)
1195 clflush_cache_range(sev_es_tmr, sev_es_tmr_size);
1197 dev_warn(sev->dev, "SEV: TMR allocation failed, SEV-ES support unavailable\n");
1202 * If an init_ex_path is provided allocate a buffer for the file and
1203 * read in the contents. Additionally, if SNP is initialized, convert
1204 * the buffer pages to firmware pages.
1206 static int __sev_platform_init_handle_init_ex_path(struct sev_device *sev)
1214 if (sev_init_ex_buffer)
1217 page = alloc_pages(GFP_KERNEL, get_order(NV_LENGTH));
1219 dev_err(sev->dev, "SEV: INIT_EX NV memory allocation failed\n");
1223 sev_init_ex_buffer = page_address(page);
1225 rc = sev_read_init_ex_file();
1229 /* If SEV-SNP is initialized, transition to firmware page. */
1230 if (sev->snp_initialized) {
1231 unsigned long npages;
1233 npages = 1UL << get_order(NV_LENGTH);
1234 if (rmp_mark_pages_firmware(__pa(sev_init_ex_buffer), npages, false)) {
1235 dev_err(sev->dev, "SEV: INIT_EX NV memory page state change failed.\n");
1243 static int __sev_platform_init_locked(int *error)
1245 int rc, psp_ret = SEV_RET_NO_FW_CALL;
1246 struct sev_device *sev;
1248 if (!psp_master || !psp_master->sev_data)
1251 sev = psp_master->sev_data;
1253 if (sev->state == SEV_STATE_INIT)
1256 __sev_platform_init_handle_tmr(sev);
1258 rc = __sev_platform_init_handle_init_ex_path(sev);
1262 rc = __sev_do_init_locked(&psp_ret);
1263 if (rc && psp_ret == SEV_RET_SECURE_DATA_INVALID) {
1265 * Initialization command returned an integrity check failure
1266 * status code, meaning that firmware load and validation of SEV
1267 * related persistent data has failed. Retrying the
1268 * initialization function should succeed by replacing the state
1269 * with a reset state.
1272 "SEV: retrying INIT command because of SECURE_DATA_INVALID error. Retrying once to reset PSP SEV state.");
1273 rc = __sev_do_init_locked(&psp_ret);
1282 sev->state = SEV_STATE_INIT;
1284 /* Prepare for first SEV guest launch after INIT */
1285 wbinvd_on_all_cpus();
1286 rc = __sev_do_cmd_locked(SEV_CMD_DF_FLUSH, NULL, error);
1290 dev_dbg(sev->dev, "SEV firmware initialized\n");
1292 dev_info(sev->dev, "SEV API:%d.%d build:%d\n", sev->api_major,
1293 sev->api_minor, sev->build);
1298 static int _sev_platform_init_locked(struct sev_platform_init_args *args)
1300 struct sev_device *sev;
1303 if (!psp_master || !psp_master->sev_data)
1306 sev = psp_master->sev_data;
1308 if (sev->state == SEV_STATE_INIT)
1312 * Legacy guests cannot be running while SNP_INIT(_EX) is executing,
1313 * so perform SEV-SNP initialization at probe time.
1315 rc = __sev_snp_init_locked(&args->error);
1316 if (rc && rc != -ENODEV) {
1318 * Don't abort the probe if SNP INIT failed,
1319 * continue to initialize the legacy SEV firmware.
1321 dev_err(sev->dev, "SEV-SNP: failed to INIT rc %d, error %#x\n",
1325 /* Defer legacy SEV/SEV-ES support if allowed by caller/module. */
1326 if (args->probe && !psp_init_on_probe)
1329 return __sev_platform_init_locked(&args->error);
1332 int sev_platform_init(struct sev_platform_init_args *args)
1336 mutex_lock(&sev_cmd_mutex);
1337 rc = _sev_platform_init_locked(args);
1338 mutex_unlock(&sev_cmd_mutex);
1342 EXPORT_SYMBOL_GPL(sev_platform_init);
1344 static int __sev_platform_shutdown_locked(int *error)
1346 struct psp_device *psp = psp_master;
1347 struct sev_device *sev;
1350 if (!psp || !psp->sev_data)
1353 sev = psp->sev_data;
1355 if (sev->state == SEV_STATE_UNINIT)
1358 ret = __sev_do_cmd_locked(SEV_CMD_SHUTDOWN, NULL, error);
1362 sev->state = SEV_STATE_UNINIT;
1363 dev_dbg(sev->dev, "SEV firmware shutdown\n");
1368 static int sev_get_platform_state(int *state, int *error)
1370 struct sev_user_data_status data;
1373 rc = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, error);
1377 *state = data.state;
1381 static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable)
1389 * The SEV spec requires that FACTORY_RESET must be issued in
1390 * UNINIT state. Before we go further lets check if any guest is
1393 * If FW is in WORKING state then deny the request otherwise issue
1394 * SHUTDOWN command do INIT -> UNINIT before issuing the FACTORY_RESET.
1397 rc = sev_get_platform_state(&state, &argp->error);
1401 if (state == SEV_STATE_WORKING)
1404 if (state == SEV_STATE_INIT) {
1405 rc = __sev_platform_shutdown_locked(&argp->error);
1410 return __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error);
1413 static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp)
1415 struct sev_user_data_status data;
1418 memset(&data, 0, sizeof(data));
1420 ret = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, &argp->error);
1424 if (copy_to_user((void __user *)argp->data, &data, sizeof(data)))
1430 static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool writable)
1432 struct sev_device *sev = psp_master->sev_data;
1438 if (sev->state == SEV_STATE_UNINIT) {
1439 rc = __sev_platform_init_locked(&argp->error);
1444 return __sev_do_cmd_locked(cmd, NULL, &argp->error);
1447 static int sev_ioctl_do_pek_csr(struct sev_issue_cmd *argp, bool writable)
1449 struct sev_device *sev = psp_master->sev_data;
1450 struct sev_user_data_pek_csr input;
1451 struct sev_data_pek_csr data;
1452 void __user *input_address;
1459 if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1462 memset(&data, 0, sizeof(data));
1464 /* userspace wants to query CSR length */
1465 if (!input.address || !input.length)
1468 /* allocate a physically contiguous buffer to store the CSR blob */
1469 input_address = (void __user *)input.address;
1470 if (input.length > SEV_FW_BLOB_MAX_SIZE)
1473 blob = kzalloc(input.length, GFP_KERNEL);
1477 data.address = __psp_pa(blob);
1478 data.len = input.length;
1481 if (sev->state == SEV_STATE_UNINIT) {
1482 ret = __sev_platform_init_locked(&argp->error);
1487 ret = __sev_do_cmd_locked(SEV_CMD_PEK_CSR, &data, &argp->error);
1489 /* If we query the CSR length, FW responded with expected data. */
1490 input.length = data.len;
1492 if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1498 if (copy_to_user(input_address, blob, input.length))
1507 void *psp_copy_user_blob(u64 uaddr, u32 len)
1510 return ERR_PTR(-EINVAL);
1512 /* verify that blob length does not exceed our limit */
1513 if (len > SEV_FW_BLOB_MAX_SIZE)
1514 return ERR_PTR(-EINVAL);
1516 return memdup_user((void __user *)uaddr, len);
1518 EXPORT_SYMBOL_GPL(psp_copy_user_blob);
1520 static int sev_get_api_version(void)
1522 struct sev_device *sev = psp_master->sev_data;
1523 struct sev_user_data_status status;
1526 ret = sev_platform_status(&status, &error);
1529 "SEV: failed to get status. Error: %#x\n", error);
1533 sev->api_major = status.api_major;
1534 sev->api_minor = status.api_minor;
1535 sev->build = status.build;
1536 sev->state = status.state;
1541 static int sev_get_firmware(struct device *dev,
1542 const struct firmware **firmware)
1544 char fw_name_specific[SEV_FW_NAME_SIZE];
1545 char fw_name_subset[SEV_FW_NAME_SIZE];
1547 snprintf(fw_name_specific, sizeof(fw_name_specific),
1548 "amd/amd_sev_fam%.2xh_model%.2xh.sbin",
1549 boot_cpu_data.x86, boot_cpu_data.x86_model);
1551 snprintf(fw_name_subset, sizeof(fw_name_subset),
1552 "amd/amd_sev_fam%.2xh_model%.1xxh.sbin",
1553 boot_cpu_data.x86, (boot_cpu_data.x86_model & 0xf0) >> 4);
1555 /* Check for SEV FW for a particular model.
1556 * Ex. amd_sev_fam17h_model00h.sbin for Family 17h Model 00h
1560 * Check for SEV FW common to a subset of models.
1561 * Ex. amd_sev_fam17h_model0xh.sbin for
1562 * Family 17h Model 00h -- Family 17h Model 0Fh
1566 * Fall-back to using generic name: sev.fw
1568 if ((firmware_request_nowarn(firmware, fw_name_specific, dev) >= 0) ||
1569 (firmware_request_nowarn(firmware, fw_name_subset, dev) >= 0) ||
1570 (firmware_request_nowarn(firmware, SEV_FW_FILE, dev) >= 0))
1576 /* Don't fail if SEV FW couldn't be updated. Continue with existing SEV FW */
1577 static int sev_update_firmware(struct device *dev)
1579 struct sev_data_download_firmware *data;
1580 const struct firmware *firmware;
1581 int ret, error, order;
1585 if (!sev_version_greater_or_equal(0, 15)) {
1586 dev_dbg(dev, "DOWNLOAD_FIRMWARE not supported\n");
1590 if (sev_get_firmware(dev, &firmware) == -ENOENT) {
1591 dev_dbg(dev, "No SEV firmware file present\n");
1596 * SEV FW expects the physical address given to it to be 32
1597 * byte aligned. Memory allocated has structure placed at the
1598 * beginning followed by the firmware being passed to the SEV
1599 * FW. Allocate enough memory for data structure + alignment
1602 data_size = ALIGN(sizeof(struct sev_data_download_firmware), 32);
1604 order = get_order(firmware->size + data_size);
1605 p = alloc_pages(GFP_KERNEL, order);
1612 * Copy firmware data to a kernel allocated contiguous
1615 data = page_address(p);
1616 memcpy(page_address(p) + data_size, firmware->data, firmware->size);
1618 data->address = __psp_pa(page_address(p) + data_size);
1619 data->len = firmware->size;
1621 ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, data, &error);
1624 * A quirk for fixing the committed TCB version, when upgrading from
1625 * earlier firmware version than 1.50.
1627 if (!ret && !sev_version_greater_or_equal(1, 50))
1628 ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, data, &error);
1631 dev_dbg(dev, "Failed to update SEV firmware: %#x\n", error);
1633 dev_info(dev, "SEV firmware update successful\n");
1635 __free_pages(p, order);
1638 release_firmware(firmware);
1643 static int __sev_snp_shutdown_locked(int *error, bool panic)
1645 struct sev_device *sev = psp_master->sev_data;
1646 struct sev_data_snp_shutdown_ex data;
1649 if (!sev->snp_initialized)
1652 memset(&data, 0, sizeof(data));
1653 data.len = sizeof(data);
1654 data.iommu_snp_shutdown = 1;
1657 * If invoked during panic handling, local interrupts are disabled
1658 * and all CPUs are stopped, so wbinvd_on_all_cpus() can't be called.
1659 * In that case, a wbinvd() is done on remote CPUs via the NMI
1660 * callback, so only a local wbinvd() is needed here.
1663 wbinvd_on_all_cpus();
1667 ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data, error);
1668 /* SHUTDOWN may require DF_FLUSH */
1669 if (*error == SEV_RET_DFFLUSH_REQUIRED) {
1670 ret = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, NULL);
1672 dev_err(sev->dev, "SEV-SNP DF_FLUSH failed\n");
1675 /* reissue the shutdown command */
1676 ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data,
1680 dev_err(sev->dev, "SEV-SNP firmware shutdown failed\n");
1685 * SNP_SHUTDOWN_EX with IOMMU_SNP_SHUTDOWN set to 1 disables SNP
1686 * enforcement by the IOMMU and also transitions all pages
1687 * associated with the IOMMU to the Reclaim state.
1688 * Firmware was transitioning the IOMMU pages to Hypervisor state
1689 * before version 1.53. But, accounting for the number of assigned
1690 * 4kB pages in a 2M page was done incorrectly by not transitioning
1691 * to the Reclaim state. This resulted in RMP #PF when later accessing
1692 * the 2M page containing those pages during kexec boot. Hence, the
1693 * firmware now transitions these pages to Reclaim state and hypervisor
1694 * needs to transition these pages to shared state. SNP Firmware
1695 * version 1.53 and above are needed for kexec boot.
1697 ret = amd_iommu_snp_disable();
1699 dev_err(sev->dev, "SNP IOMMU shutdown failed\n");
1703 sev->snp_initialized = false;
1704 dev_dbg(sev->dev, "SEV-SNP firmware shutdown\n");
1709 static int sev_ioctl_do_pek_import(struct sev_issue_cmd *argp, bool writable)
1711 struct sev_device *sev = psp_master->sev_data;
1712 struct sev_user_data_pek_cert_import input;
1713 struct sev_data_pek_cert_import data;
1714 void *pek_blob, *oca_blob;
1720 if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1723 /* copy PEK certificate blobs from userspace */
1724 pek_blob = psp_copy_user_blob(input.pek_cert_address, input.pek_cert_len);
1725 if (IS_ERR(pek_blob))
1726 return PTR_ERR(pek_blob);
1729 data.pek_cert_address = __psp_pa(pek_blob);
1730 data.pek_cert_len = input.pek_cert_len;
1732 /* copy PEK certificate blobs from userspace */
1733 oca_blob = psp_copy_user_blob(input.oca_cert_address, input.oca_cert_len);
1734 if (IS_ERR(oca_blob)) {
1735 ret = PTR_ERR(oca_blob);
1739 data.oca_cert_address = __psp_pa(oca_blob);
1740 data.oca_cert_len = input.oca_cert_len;
1742 /* If platform is not in INIT state then transition it to INIT */
1743 if (sev->state != SEV_STATE_INIT) {
1744 ret = __sev_platform_init_locked(&argp->error);
1749 ret = __sev_do_cmd_locked(SEV_CMD_PEK_CERT_IMPORT, &data, &argp->error);
1758 static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp)
1760 struct sev_user_data_get_id2 input;
1761 struct sev_data_get_id data;
1762 void __user *input_address;
1763 void *id_blob = NULL;
1766 /* SEV GET_ID is available from SEV API v0.16 and up */
1767 if (!sev_version_greater_or_equal(0, 16))
1770 if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1773 input_address = (void __user *)input.address;
1775 if (input.address && input.length) {
1777 * The length of the ID shouldn't be assumed by software since
1778 * it may change in the future. The allocation size is limited
1779 * to 1 << (PAGE_SHIFT + MAX_PAGE_ORDER) by the page allocator.
1780 * If the allocation fails, simply return ENOMEM rather than
1781 * warning in the kernel log.
1783 id_blob = kzalloc(input.length, GFP_KERNEL | __GFP_NOWARN);
1787 data.address = __psp_pa(id_blob);
1788 data.len = input.length;
1794 ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, &data, &argp->error);
1797 * Firmware will return the length of the ID value (either the minimum
1798 * required length or the actual length written), return it to the user.
1800 input.length = data.len;
1802 if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1808 if (copy_to_user(input_address, id_blob, data.len)) {
1820 static int sev_ioctl_do_get_id(struct sev_issue_cmd *argp)
1822 struct sev_data_get_id *data;
1823 u64 data_size, user_size;
1824 void *id_blob, *mem;
1827 /* SEV GET_ID available from SEV API v0.16 and up */
1828 if (!sev_version_greater_or_equal(0, 16))
1831 /* SEV FW expects the buffer it fills with the ID to be
1832 * 8-byte aligned. Memory allocated should be enough to
1833 * hold data structure + alignment padding + memory
1834 * where SEV FW writes the ID.
1836 data_size = ALIGN(sizeof(struct sev_data_get_id), 8);
1837 user_size = sizeof(struct sev_user_data_get_id);
1839 mem = kzalloc(data_size + user_size, GFP_KERNEL);
1844 id_blob = mem + data_size;
1846 data->address = __psp_pa(id_blob);
1847 data->len = user_size;
1849 ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, data, &argp->error);
1851 if (copy_to_user((void __user *)argp->data, id_blob, data->len))
1860 static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable)
1862 struct sev_device *sev = psp_master->sev_data;
1863 struct sev_user_data_pdh_cert_export input;
1864 void *pdh_blob = NULL, *cert_blob = NULL;
1865 struct sev_data_pdh_cert_export data;
1866 void __user *input_cert_chain_address;
1867 void __user *input_pdh_cert_address;
1870 /* If platform is not in INIT state then transition it to INIT. */
1871 if (sev->state != SEV_STATE_INIT) {
1875 ret = __sev_platform_init_locked(&argp->error);
1880 if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1883 memset(&data, 0, sizeof(data));
1885 /* Userspace wants to query the certificate length. */
1886 if (!input.pdh_cert_address ||
1887 !input.pdh_cert_len ||
1888 !input.cert_chain_address)
1891 input_pdh_cert_address = (void __user *)input.pdh_cert_address;
1892 input_cert_chain_address = (void __user *)input.cert_chain_address;
1894 /* Allocate a physically contiguous buffer to store the PDH blob. */
1895 if (input.pdh_cert_len > SEV_FW_BLOB_MAX_SIZE)
1898 /* Allocate a physically contiguous buffer to store the cert chain blob. */
1899 if (input.cert_chain_len > SEV_FW_BLOB_MAX_SIZE)
1902 pdh_blob = kzalloc(input.pdh_cert_len, GFP_KERNEL);
1906 data.pdh_cert_address = __psp_pa(pdh_blob);
1907 data.pdh_cert_len = input.pdh_cert_len;
1909 cert_blob = kzalloc(input.cert_chain_len, GFP_KERNEL);
1915 data.cert_chain_address = __psp_pa(cert_blob);
1916 data.cert_chain_len = input.cert_chain_len;
1919 ret = __sev_do_cmd_locked(SEV_CMD_PDH_CERT_EXPORT, &data, &argp->error);
1921 /* If we query the length, FW responded with expected data. */
1922 input.cert_chain_len = data.cert_chain_len;
1923 input.pdh_cert_len = data.pdh_cert_len;
1925 if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1931 if (copy_to_user(input_pdh_cert_address,
1932 pdh_blob, input.pdh_cert_len)) {
1939 if (copy_to_user(input_cert_chain_address,
1940 cert_blob, input.cert_chain_len))
1951 static int sev_ioctl_do_snp_platform_status(struct sev_issue_cmd *argp)
1953 struct sev_device *sev = psp_master->sev_data;
1954 struct sev_data_snp_addr buf;
1955 struct page *status_page;
1959 if (!sev->snp_initialized || !argp->data)
1962 status_page = alloc_page(GFP_KERNEL_ACCOUNT);
1966 data = page_address(status_page);
1969 * Firmware expects status page to be in firmware-owned state, otherwise
1970 * it will report firmware error code INVALID_PAGE_STATE (0x1A).
1972 if (rmp_mark_pages_firmware(__pa(data), 1, true)) {
1977 buf.address = __psp_pa(data);
1978 ret = __sev_do_cmd_locked(SEV_CMD_SNP_PLATFORM_STATUS, &buf, &argp->error);
1981 * Status page will be transitioned to Reclaim state upon success, or
1982 * left in Firmware state in failure. Use snp_reclaim_pages() to
1983 * transition either case back to Hypervisor-owned state.
1985 if (snp_reclaim_pages(__pa(data), 1, true))
1991 if (copy_to_user((void __user *)argp->data, data,
1992 sizeof(struct sev_user_data_snp_status)))
1996 __free_pages(status_page, 0);
2000 static int sev_ioctl_do_snp_commit(struct sev_issue_cmd *argp)
2002 struct sev_device *sev = psp_master->sev_data;
2003 struct sev_data_snp_commit buf;
2005 if (!sev->snp_initialized)
2008 buf.len = sizeof(buf);
2010 return __sev_do_cmd_locked(SEV_CMD_SNP_COMMIT, &buf, &argp->error);
2013 static int sev_ioctl_do_snp_set_config(struct sev_issue_cmd *argp, bool writable)
2015 struct sev_device *sev = psp_master->sev_data;
2016 struct sev_user_data_snp_config config;
2018 if (!sev->snp_initialized || !argp->data)
2024 if (copy_from_user(&config, (void __user *)argp->data, sizeof(config)))
2027 return __sev_do_cmd_locked(SEV_CMD_SNP_CONFIG, &config, &argp->error);
2030 static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)
2032 void __user *argp = (void __user *)arg;
2033 struct sev_issue_cmd input;
2035 bool writable = file->f_mode & FMODE_WRITE;
2037 if (!psp_master || !psp_master->sev_data)
2040 if (ioctl != SEV_ISSUE_CMD)
2043 if (copy_from_user(&input, argp, sizeof(struct sev_issue_cmd)))
2046 if (input.cmd > SEV_MAX)
2049 mutex_lock(&sev_cmd_mutex);
2051 switch (input.cmd) {
2053 case SEV_FACTORY_RESET:
2054 ret = sev_ioctl_do_reset(&input, writable);
2056 case SEV_PLATFORM_STATUS:
2057 ret = sev_ioctl_do_platform_status(&input);
2060 ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PEK_GEN, &input, writable);
2063 ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PDH_GEN, &input, writable);
2066 ret = sev_ioctl_do_pek_csr(&input, writable);
2068 case SEV_PEK_CERT_IMPORT:
2069 ret = sev_ioctl_do_pek_import(&input, writable);
2071 case SEV_PDH_CERT_EXPORT:
2072 ret = sev_ioctl_do_pdh_export(&input, writable);
2075 pr_warn_once("SEV_GET_ID command is deprecated, use SEV_GET_ID2\n");
2076 ret = sev_ioctl_do_get_id(&input);
2079 ret = sev_ioctl_do_get_id2(&input);
2081 case SNP_PLATFORM_STATUS:
2082 ret = sev_ioctl_do_snp_platform_status(&input);
2085 ret = sev_ioctl_do_snp_commit(&input);
2087 case SNP_SET_CONFIG:
2088 ret = sev_ioctl_do_snp_set_config(&input, writable);
2095 if (copy_to_user(argp, &input, sizeof(struct sev_issue_cmd)))
2098 mutex_unlock(&sev_cmd_mutex);
2103 static const struct file_operations sev_fops = {
2104 .owner = THIS_MODULE,
2105 .unlocked_ioctl = sev_ioctl,
2108 int sev_platform_status(struct sev_user_data_status *data, int *error)
2110 return sev_do_cmd(SEV_CMD_PLATFORM_STATUS, data, error);
2112 EXPORT_SYMBOL_GPL(sev_platform_status);
2114 int sev_guest_deactivate(struct sev_data_deactivate *data, int *error)
2116 return sev_do_cmd(SEV_CMD_DEACTIVATE, data, error);
2118 EXPORT_SYMBOL_GPL(sev_guest_deactivate);
2120 int sev_guest_activate(struct sev_data_activate *data, int *error)
2122 return sev_do_cmd(SEV_CMD_ACTIVATE, data, error);
2124 EXPORT_SYMBOL_GPL(sev_guest_activate);
2126 int sev_guest_decommission(struct sev_data_decommission *data, int *error)
2128 return sev_do_cmd(SEV_CMD_DECOMMISSION, data, error);
2130 EXPORT_SYMBOL_GPL(sev_guest_decommission);
2132 int sev_guest_df_flush(int *error)
2134 return sev_do_cmd(SEV_CMD_DF_FLUSH, NULL, error);
2136 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
2138 static void sev_exit(struct kref *ref)
2140 misc_deregister(&misc_dev->misc);
2145 static int sev_misc_init(struct sev_device *sev)
2147 struct device *dev = sev->dev;
2151 * SEV feature support can be detected on multiple devices but the SEV
2152 * FW commands must be issued on the master. During probe, we do not
2153 * know the master hence we create /dev/sev on the first device probe.
2154 * sev_do_cmd() finds the right master device to which to issue the
2155 * command to the firmware.
2158 struct miscdevice *misc;
2160 misc_dev = kzalloc(sizeof(*misc_dev), GFP_KERNEL);
2164 misc = &misc_dev->misc;
2165 misc->minor = MISC_DYNAMIC_MINOR;
2166 misc->name = DEVICE_NAME;
2167 misc->fops = &sev_fops;
2169 ret = misc_register(misc);
2173 kref_init(&misc_dev->refcount);
2175 kref_get(&misc_dev->refcount);
2178 init_waitqueue_head(&sev->int_queue);
2179 sev->misc = misc_dev;
2180 dev_dbg(dev, "registered SEV device\n");
2185 int sev_dev_init(struct psp_device *psp)
2187 struct device *dev = psp->dev;
2188 struct sev_device *sev;
2191 if (!boot_cpu_has(X86_FEATURE_SEV)) {
2192 dev_info_once(dev, "SEV: memory encryption not enabled by BIOS\n");
2196 sev = devm_kzalloc(dev, sizeof(*sev), GFP_KERNEL);
2200 sev->cmd_buf = (void *)devm_get_free_pages(dev, GFP_KERNEL, 1);
2204 sev->cmd_buf_backup = (uint8_t *)sev->cmd_buf + PAGE_SIZE;
2206 psp->sev_data = sev;
2211 sev->io_regs = psp->io_regs;
2213 sev->vdata = (struct sev_vdata *)psp->vdata->sev;
2216 dev_err(dev, "sev: missing driver data\n");
2220 psp_set_sev_irq_handler(psp, sev_irq_handler, sev);
2222 ret = sev_misc_init(sev);
2226 dev_notice(dev, "sev enabled\n");
2231 psp_clear_sev_irq_handler(psp);
2233 devm_free_pages(dev, (unsigned long)sev->cmd_buf);
2235 devm_kfree(dev, sev);
2237 psp->sev_data = NULL;
2239 dev_notice(dev, "sev initialization failed\n");
2244 static void __sev_firmware_shutdown(struct sev_device *sev, bool panic)
2248 __sev_platform_shutdown_locked(NULL);
2252 * The TMR area was encrypted, flush it from the cache.
2254 * If invoked during panic handling, local interrupts are
2255 * disabled and all CPUs are stopped, so wbinvd_on_all_cpus()
2256 * can't be used. In that case, wbinvd() is done on remote CPUs
2257 * via the NMI callback, and done for this CPU later during
2258 * SNP shutdown, so wbinvd_on_all_cpus() can be skipped.
2261 wbinvd_on_all_cpus();
2263 __snp_free_firmware_pages(virt_to_page(sev_es_tmr),
2264 get_order(sev_es_tmr_size),
2269 if (sev_init_ex_buffer) {
2270 __snp_free_firmware_pages(virt_to_page(sev_init_ex_buffer),
2271 get_order(NV_LENGTH),
2273 sev_init_ex_buffer = NULL;
2276 if (snp_range_list) {
2277 kfree(snp_range_list);
2278 snp_range_list = NULL;
2281 __sev_snp_shutdown_locked(&error, panic);
2284 static void sev_firmware_shutdown(struct sev_device *sev)
2286 mutex_lock(&sev_cmd_mutex);
2287 __sev_firmware_shutdown(sev, false);
2288 mutex_unlock(&sev_cmd_mutex);
2291 void sev_dev_destroy(struct psp_device *psp)
2293 struct sev_device *sev = psp->sev_data;
2298 sev_firmware_shutdown(sev);
2301 kref_put(&misc_dev->refcount, sev_exit);
2303 psp_clear_sev_irq_handler(psp);
2306 static int snp_shutdown_on_panic(struct notifier_block *nb,
2307 unsigned long reason, void *arg)
2309 struct sev_device *sev = psp_master->sev_data;
2312 * If sev_cmd_mutex is already acquired, then it's likely
2313 * another PSP command is in flight and issuing a shutdown
2314 * would fail in unexpected ways. Rather than create even
2315 * more confusion during a panic, just bail out here.
2317 if (mutex_is_locked(&sev_cmd_mutex))
2320 __sev_firmware_shutdown(sev, true);
2325 static struct notifier_block snp_panic_notifier = {
2326 .notifier_call = snp_shutdown_on_panic,
2329 int sev_issue_cmd_external_user(struct file *filep, unsigned int cmd,
2330 void *data, int *error)
2332 if (!filep || filep->f_op != &sev_fops)
2335 return sev_do_cmd(cmd, data, error);
2337 EXPORT_SYMBOL_GPL(sev_issue_cmd_external_user);
2339 void sev_pci_init(void)
2341 struct sev_device *sev = psp_master->sev_data;
2342 struct sev_platform_init_args args = {0};
2348 psp_timeout = psp_probe_timeout;
2350 if (sev_get_api_version())
2353 if (sev_update_firmware(sev->dev) == 0)
2354 sev_get_api_version();
2356 /* Initialize the platform */
2358 rc = sev_platform_init(&args);
2360 dev_err(sev->dev, "SEV: failed to INIT error %#x, rc %d\n",
2363 dev_info(sev->dev, "SEV%s API:%d.%d build:%d\n", sev->snp_initialized ?
2364 "-SNP" : "", sev->api_major, sev->api_minor, sev->build);
2366 atomic_notifier_chain_register(&panic_notifier_list,
2367 &snp_panic_notifier);
2371 psp_master->sev_data = NULL;
2374 void sev_pci_exit(void)
2376 struct sev_device *sev = psp_master->sev_data;
2381 sev_firmware_shutdown(sev);
2383 atomic_notifier_chain_unregister(&panic_notifier_list,
2384 &snp_panic_notifier);