xref: /linux/drivers/crypto/ccp/sev-dev.c (revision c32dd3367b975ac2c59e0fec6a8c100522f51c1c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AMD Secure Encrypted Virtualization (SEV) interface
4  *
5  * Copyright (C) 2016,2019 Advanced Micro Devices, Inc.
6  *
7  * Author: Brijesh Singh <brijesh.singh@amd.com>
8  */
9 
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>
27 #include <linux/fs.h>
28 #include <linux/fs_struct.h>
29 #include <linux/psp.h>
30 #include <linux/amd-iommu.h>
31 #include <linux/crash_dump.h>
32 
33 #include <asm/smp.h>
34 #include <asm/cacheflush.h>
35 #include <asm/e820/types.h>
36 #include <asm/sev.h>
37 #include <asm/msr.h>
38 
39 #include "psp-dev.h"
40 #include "sev-dev.h"
41 
42 #define DEVICE_NAME		"sev"
43 #define SEV_FW_FILE		"amd/sev.fw"
44 #define SEV_FW_NAME_SIZE	64
45 
46 /* Minimum firmware version required for the SEV-SNP support */
47 #define SNP_MIN_API_MAJOR	1
48 #define SNP_MIN_API_MINOR	51
49 
50 /*
51  * Maximum number of firmware-writable buffers that might be specified
52  * in the parameters of a legacy SEV command buffer.
53  */
54 #define CMD_BUF_FW_WRITABLE_MAX 2
55 
56 /* Leave room in the descriptor array for an end-of-list indicator. */
57 #define CMD_BUF_DESC_MAX (CMD_BUF_FW_WRITABLE_MAX + 1)
58 
59 static DEFINE_MUTEX(sev_cmd_mutex);
60 static struct sev_misc_dev *misc_dev;
61 
62 static int psp_cmd_timeout = 100;
63 module_param(psp_cmd_timeout, int, 0644);
64 MODULE_PARM_DESC(psp_cmd_timeout, " default timeout value, in seconds, for PSP commands");
65 
66 static int psp_probe_timeout = 5;
67 module_param(psp_probe_timeout, int, 0644);
68 MODULE_PARM_DESC(psp_probe_timeout, " default timeout value, in seconds, during PSP device probe");
69 
70 static char *init_ex_path;
71 module_param(init_ex_path, charp, 0444);
72 MODULE_PARM_DESC(init_ex_path, " Path for INIT_EX data; if set try INIT_EX");
73 
74 static bool psp_init_on_probe = true;
75 module_param(psp_init_on_probe, bool, 0444);
76 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");
77 
78 #if IS_ENABLED(CONFIG_PCI_TSM)
79 static bool sev_tio_enabled = true;
80 module_param_named(tio, sev_tio_enabled, bool, 0444);
81 MODULE_PARM_DESC(tio, "Enables TIO in SNP_INIT_EX");
82 #else
83 static const bool sev_tio_enabled = false;
84 #endif
85 
86 MODULE_FIRMWARE("amd/amd_sev_fam17h_model0xh.sbin"); /* 1st gen EPYC */
87 MODULE_FIRMWARE("amd/amd_sev_fam17h_model3xh.sbin"); /* 2nd gen EPYC */
88 MODULE_FIRMWARE("amd/amd_sev_fam19h_model0xh.sbin"); /* 3rd gen EPYC */
89 MODULE_FIRMWARE("amd/amd_sev_fam19h_model1xh.sbin"); /* 4th gen EPYC */
90 
91 static bool psp_dead;
92 static int psp_timeout;
93 
94 enum snp_hv_fixed_pages_state {
95 	ALLOCATED,
96 	HV_FIXED,
97 };
98 
99 struct snp_hv_fixed_pages_entry {
100 	struct list_head list;
101 	struct page *page;
102 	unsigned int order;
103 	bool free;
104 	enum snp_hv_fixed_pages_state page_state;
105 };
106 
107 static LIST_HEAD(snp_hv_fixed_pages);
108 
109 /* Trusted Memory Region (TMR):
110  *   The TMR is a 1MB area that must be 1MB aligned.  Use the page allocator
111  *   to allocate the memory, which will return aligned memory for the specified
112  *   allocation order.
113  *
114  * When SEV-SNP is enabled the TMR needs to be 2MB aligned and 2MB sized.
115  */
116 #define SEV_TMR_SIZE		(1024 * 1024)
117 #define SNP_TMR_SIZE		(2 * 1024 * 1024)
118 
119 static void *sev_es_tmr;
120 static size_t sev_es_tmr_size = SEV_TMR_SIZE;
121 
122 /* INIT_EX NV Storage:
123  *   The NV Storage is a 32Kb area and must be 4Kb page aligned.  Use the page
124  *   allocator to allocate the memory, which will return aligned memory for the
125  *   specified allocation order.
126  */
127 #define NV_LENGTH (32 * 1024)
128 static void *sev_init_ex_buffer;
129 
130 static void __sev_firmware_shutdown(struct sev_device *sev, bool panic);
131 
132 static int snp_shutdown_on_panic(struct notifier_block *nb,
133 				 unsigned long reason, void *arg);
134 
135 static struct notifier_block snp_panic_notifier = {
136 	.notifier_call = snp_shutdown_on_panic,
137 };
138 
139 static inline bool sev_version_greater_or_equal(u8 maj, u8 min)
140 {
141 	struct sev_device *sev = psp_master->sev_data;
142 
143 	if (sev->api_major > maj)
144 		return true;
145 
146 	if (sev->api_major == maj && sev->api_minor >= min)
147 		return true;
148 
149 	return false;
150 }
151 
152 static void sev_irq_handler(int irq, void *data, unsigned int status)
153 {
154 	struct sev_device *sev = data;
155 	int reg;
156 
157 	/* Check if it is command completion: */
158 	if (!(status & SEV_CMD_COMPLETE))
159 		return;
160 
161 	/* Check if it is SEV command completion: */
162 	reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
163 	if (FIELD_GET(PSP_CMDRESP_RESP, reg)) {
164 		sev->int_rcvd = 1;
165 		wake_up(&sev->int_queue);
166 	}
167 }
168 
169 static int sev_wait_cmd_ioc(struct sev_device *sev,
170 			    unsigned int *reg, unsigned int timeout)
171 {
172 	int ret;
173 
174 	/*
175 	 * If invoked during panic handling, local interrupts are disabled,
176 	 * so the PSP command completion interrupt can't be used. Poll for
177 	 * PSP command completion instead.
178 	 */
179 	if (irqs_disabled()) {
180 		unsigned long timeout_usecs = (timeout * USEC_PER_SEC) / 10;
181 
182 		/* Poll for SEV command completion: */
183 		while (timeout_usecs--) {
184 			*reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
185 			if (*reg & PSP_CMDRESP_RESP)
186 				return 0;
187 
188 			udelay(10);
189 		}
190 		return -ETIMEDOUT;
191 	}
192 
193 	ret = wait_event_timeout(sev->int_queue,
194 			sev->int_rcvd, timeout * HZ);
195 	if (!ret)
196 		return -ETIMEDOUT;
197 
198 	*reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
199 
200 	return 0;
201 }
202 
203 static int sev_cmd_buffer_len(int cmd)
204 {
205 	switch (cmd) {
206 	case SEV_CMD_INIT:			return sizeof(struct sev_data_init);
207 	case SEV_CMD_INIT_EX:                   return sizeof(struct sev_data_init_ex);
208 	case SEV_CMD_SNP_SHUTDOWN_EX:		return sizeof(struct sev_data_snp_shutdown_ex);
209 	case SEV_CMD_SNP_INIT_EX:		return sizeof(struct sev_data_snp_init_ex);
210 	case SEV_CMD_PLATFORM_STATUS:		return sizeof(struct sev_user_data_status);
211 	case SEV_CMD_PEK_CSR:			return sizeof(struct sev_data_pek_csr);
212 	case SEV_CMD_PEK_CERT_IMPORT:		return sizeof(struct sev_data_pek_cert_import);
213 	case SEV_CMD_PDH_CERT_EXPORT:		return sizeof(struct sev_data_pdh_cert_export);
214 	case SEV_CMD_LAUNCH_START:		return sizeof(struct sev_data_launch_start);
215 	case SEV_CMD_LAUNCH_UPDATE_DATA:	return sizeof(struct sev_data_launch_update_data);
216 	case SEV_CMD_LAUNCH_UPDATE_VMSA:	return sizeof(struct sev_data_launch_update_vmsa);
217 	case SEV_CMD_LAUNCH_FINISH:		return sizeof(struct sev_data_launch_finish);
218 	case SEV_CMD_LAUNCH_MEASURE:		return sizeof(struct sev_data_launch_measure);
219 	case SEV_CMD_ACTIVATE:			return sizeof(struct sev_data_activate);
220 	case SEV_CMD_DEACTIVATE:		return sizeof(struct sev_data_deactivate);
221 	case SEV_CMD_DECOMMISSION:		return sizeof(struct sev_data_decommission);
222 	case SEV_CMD_GUEST_STATUS:		return sizeof(struct sev_data_guest_status);
223 	case SEV_CMD_DBG_DECRYPT:		return sizeof(struct sev_data_dbg);
224 	case SEV_CMD_DBG_ENCRYPT:		return sizeof(struct sev_data_dbg);
225 	case SEV_CMD_SEND_START:		return sizeof(struct sev_data_send_start);
226 	case SEV_CMD_SEND_UPDATE_DATA:		return sizeof(struct sev_data_send_update_data);
227 	case SEV_CMD_SEND_UPDATE_VMSA:		return sizeof(struct sev_data_send_update_vmsa);
228 	case SEV_CMD_SEND_FINISH:		return sizeof(struct sev_data_send_finish);
229 	case SEV_CMD_RECEIVE_START:		return sizeof(struct sev_data_receive_start);
230 	case SEV_CMD_RECEIVE_FINISH:		return sizeof(struct sev_data_receive_finish);
231 	case SEV_CMD_RECEIVE_UPDATE_DATA:	return sizeof(struct sev_data_receive_update_data);
232 	case SEV_CMD_RECEIVE_UPDATE_VMSA:	return sizeof(struct sev_data_receive_update_vmsa);
233 	case SEV_CMD_LAUNCH_UPDATE_SECRET:	return sizeof(struct sev_data_launch_secret);
234 	case SEV_CMD_DOWNLOAD_FIRMWARE:		return sizeof(struct sev_data_download_firmware);
235 	case SEV_CMD_GET_ID:			return sizeof(struct sev_data_get_id);
236 	case SEV_CMD_ATTESTATION_REPORT:	return sizeof(struct sev_data_attestation_report);
237 	case SEV_CMD_SEND_CANCEL:		return sizeof(struct sev_data_send_cancel);
238 	case SEV_CMD_SNP_GCTX_CREATE:		return sizeof(struct sev_data_snp_addr);
239 	case SEV_CMD_SNP_LAUNCH_START:		return sizeof(struct sev_data_snp_launch_start);
240 	case SEV_CMD_SNP_LAUNCH_UPDATE:		return sizeof(struct sev_data_snp_launch_update);
241 	case SEV_CMD_SNP_ACTIVATE:		return sizeof(struct sev_data_snp_activate);
242 	case SEV_CMD_SNP_DECOMMISSION:		return sizeof(struct sev_data_snp_addr);
243 	case SEV_CMD_SNP_PAGE_RECLAIM:		return sizeof(struct sev_data_snp_page_reclaim);
244 	case SEV_CMD_SNP_GUEST_STATUS:		return sizeof(struct sev_data_snp_guest_status);
245 	case SEV_CMD_SNP_LAUNCH_FINISH:		return sizeof(struct sev_data_snp_launch_finish);
246 	case SEV_CMD_SNP_DBG_DECRYPT:		return sizeof(struct sev_data_snp_dbg);
247 	case SEV_CMD_SNP_DBG_ENCRYPT:		return sizeof(struct sev_data_snp_dbg);
248 	case SEV_CMD_SNP_VERIFY_MITIGATION:	return sizeof(struct sev_data_snp_verify_mitigation);
249 	case SEV_CMD_SNP_PAGE_UNSMASH:		return sizeof(struct sev_data_snp_page_unsmash);
250 	case SEV_CMD_SNP_PLATFORM_STATUS:	return sizeof(struct sev_data_snp_addr);
251 	case SEV_CMD_SNP_GUEST_REQUEST:		return sizeof(struct sev_data_snp_guest_request);
252 	case SEV_CMD_SNP_CONFIG:		return sizeof(struct sev_user_data_snp_config);
253 	case SEV_CMD_SNP_COMMIT:		return sizeof(struct sev_data_snp_commit);
254 	case SEV_CMD_SNP_FEATURE_INFO:		return sizeof(struct sev_data_snp_feature_info);
255 	case SEV_CMD_SNP_VLEK_LOAD:		return sizeof(struct sev_user_data_snp_vlek_load);
256 	default:				return sev_tio_cmd_buffer_len(cmd);
257 	}
258 
259 	return 0;
260 }
261 
262 static struct file *open_file_as_root(const char *filename, int flags, umode_t mode)
263 {
264 	struct path root __free(path_put) = {};
265 
266 	task_lock(&init_task);
267 	get_fs_root(init_task.fs, &root);
268 	task_unlock(&init_task);
269 
270 	CLASS(prepare_creds, cred)();
271 	if (!cred)
272 		return ERR_PTR(-ENOMEM);
273 
274 	cred->fsuid = GLOBAL_ROOT_UID;
275 
276 	scoped_with_creds(cred)
277 		return file_open_root(&root, filename, flags, mode);
278 }
279 
280 static int sev_read_init_ex_file(void)
281 {
282 	struct sev_device *sev = psp_master->sev_data;
283 	struct file *fp;
284 	ssize_t nread;
285 
286 	lockdep_assert_held(&sev_cmd_mutex);
287 
288 	if (!sev_init_ex_buffer)
289 		return -EOPNOTSUPP;
290 
291 	fp = open_file_as_root(init_ex_path, O_RDONLY, 0);
292 	if (IS_ERR(fp)) {
293 		int ret = PTR_ERR(fp);
294 
295 		if (ret == -ENOENT) {
296 			dev_info(sev->dev,
297 				"SEV: %s does not exist and will be created later.\n",
298 				init_ex_path);
299 			ret = 0;
300 		} else {
301 			dev_err(sev->dev,
302 				"SEV: could not open %s for read, error %d\n",
303 				init_ex_path, ret);
304 		}
305 		return ret;
306 	}
307 
308 	nread = kernel_read(fp, sev_init_ex_buffer, NV_LENGTH, NULL);
309 	if (nread != NV_LENGTH) {
310 		dev_info(sev->dev,
311 			"SEV: could not read %u bytes to non volatile memory area, ret %ld\n",
312 			NV_LENGTH, nread);
313 	}
314 
315 	dev_dbg(sev->dev, "SEV: read %ld bytes from NV file\n", nread);
316 	filp_close(fp, NULL);
317 
318 	return 0;
319 }
320 
321 static int sev_write_init_ex_file(void)
322 {
323 	struct sev_device *sev = psp_master->sev_data;
324 	struct file *fp;
325 	loff_t offset = 0;
326 	ssize_t nwrite;
327 
328 	lockdep_assert_held(&sev_cmd_mutex);
329 
330 	if (!sev_init_ex_buffer)
331 		return 0;
332 
333 	fp = open_file_as_root(init_ex_path, O_CREAT | O_WRONLY, 0600);
334 	if (IS_ERR(fp)) {
335 		int ret = PTR_ERR(fp);
336 
337 		dev_err(sev->dev,
338 			"SEV: could not open file for write, error %d\n",
339 			ret);
340 		return ret;
341 	}
342 
343 	nwrite = kernel_write(fp, sev_init_ex_buffer, NV_LENGTH, &offset);
344 	vfs_fsync(fp, 0);
345 	filp_close(fp, NULL);
346 
347 	if (nwrite != NV_LENGTH) {
348 		dev_err(sev->dev,
349 			"SEV: failed to write %u bytes to non volatile memory area, ret %ld\n",
350 			NV_LENGTH, nwrite);
351 		return -EIO;
352 	}
353 
354 	dev_dbg(sev->dev, "SEV: write successful to NV file\n");
355 
356 	return 0;
357 }
358 
359 static int sev_write_init_ex_file_if_required(int cmd_id)
360 {
361 	lockdep_assert_held(&sev_cmd_mutex);
362 
363 	if (!sev_init_ex_buffer)
364 		return 0;
365 
366 	/*
367 	 * Only a few platform commands modify the SPI/NV area, but none of the
368 	 * non-platform commands do. Only INIT(_EX), PLATFORM_RESET, PEK_GEN,
369 	 * PEK_CERT_IMPORT, and PDH_GEN do.
370 	 */
371 	switch (cmd_id) {
372 	case SEV_CMD_FACTORY_RESET:
373 	case SEV_CMD_INIT_EX:
374 	case SEV_CMD_PDH_GEN:
375 	case SEV_CMD_PEK_CERT_IMPORT:
376 	case SEV_CMD_PEK_GEN:
377 		break;
378 	default:
379 		return 0;
380 	}
381 
382 	return sev_write_init_ex_file();
383 }
384 
385 int snp_reclaim_pages(unsigned long paddr, unsigned int npages, bool locked)
386 {
387 	int ret, err, i;
388 
389 	paddr = __sme_clr(ALIGN_DOWN(paddr, PAGE_SIZE));
390 
391 	for (i = 0; i < npages; i++, paddr += PAGE_SIZE) {
392 		struct sev_data_snp_page_reclaim data = {0};
393 
394 		data.paddr = paddr;
395 
396 		if (locked)
397 			ret = __sev_do_cmd_locked(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
398 		else
399 			ret = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
400 
401 		if (ret)
402 			goto cleanup;
403 
404 		ret = rmp_make_shared(__phys_to_pfn(paddr), PG_LEVEL_4K);
405 		if (ret)
406 			goto cleanup;
407 	}
408 
409 	return 0;
410 
411 cleanup:
412 	/*
413 	 * If there was a failure reclaiming the page then it is no longer safe
414 	 * to release it back to the system; leak it instead.
415 	 */
416 	snp_leak_pages(__phys_to_pfn(paddr), npages - i);
417 	return ret;
418 }
419 EXPORT_SYMBOL_GPL(snp_reclaim_pages);
420 
421 static int rmp_mark_pages_firmware(unsigned long paddr, unsigned int npages, bool locked)
422 {
423 	unsigned long pfn = __sme_clr(paddr) >> PAGE_SHIFT;
424 	int rc, i;
425 
426 	for (i = 0; i < npages; i++, pfn++) {
427 		rc = rmp_make_private(pfn, 0, PG_LEVEL_4K, 0, true);
428 		if (rc)
429 			goto cleanup;
430 	}
431 
432 	return 0;
433 
434 cleanup:
435 	/*
436 	 * Try unrolling the firmware state changes by
437 	 * reclaiming the pages which were already changed to the
438 	 * firmware state.
439 	 */
440 	snp_reclaim_pages(paddr, i, locked);
441 
442 	return rc;
443 }
444 
445 static struct page *__snp_alloc_firmware_pages(gfp_t gfp_mask, int order, bool locked)
446 {
447 	unsigned long npages = 1ul << order, paddr;
448 	struct sev_device *sev;
449 	struct page *page;
450 
451 	if (!psp_master || !psp_master->sev_data)
452 		return NULL;
453 
454 	page = alloc_pages(gfp_mask, order);
455 	if (!page)
456 		return NULL;
457 
458 	/* If SEV-SNP is initialized then add the page in RMP table. */
459 	sev = psp_master->sev_data;
460 	if (!sev->snp_initialized)
461 		return page;
462 
463 	paddr = __pa((unsigned long)page_address(page));
464 	if (rmp_mark_pages_firmware(paddr, npages, locked))
465 		return NULL;
466 
467 	return page;
468 }
469 
470 void *snp_alloc_firmware_page(gfp_t gfp_mask)
471 {
472 	struct page *page;
473 
474 	page = __snp_alloc_firmware_pages(gfp_mask, 0, false);
475 
476 	return page ? page_address(page) : NULL;
477 }
478 EXPORT_SYMBOL_GPL(snp_alloc_firmware_page);
479 
480 static void __snp_free_firmware_pages(struct page *page, int order, bool locked)
481 {
482 	struct sev_device *sev = psp_master->sev_data;
483 	unsigned long paddr, npages = 1ul << order;
484 
485 	if (!page)
486 		return;
487 
488 	paddr = __pa((unsigned long)page_address(page));
489 	if (sev->snp_initialized &&
490 	    snp_reclaim_pages(paddr, npages, locked))
491 		return;
492 
493 	__free_pages(page, order);
494 }
495 
496 void snp_free_firmware_page(void *addr)
497 {
498 	if (!addr)
499 		return;
500 
501 	__snp_free_firmware_pages(virt_to_page(addr), 0, false);
502 }
503 EXPORT_SYMBOL_GPL(snp_free_firmware_page);
504 
505 static void *sev_fw_alloc(unsigned long len)
506 {
507 	struct page *page;
508 
509 	page = __snp_alloc_firmware_pages(GFP_KERNEL, get_order(len), true);
510 	if (!page)
511 		return NULL;
512 
513 	return page_address(page);
514 }
515 
516 /**
517  * struct cmd_buf_desc - descriptors for managing legacy SEV command address
518  * parameters corresponding to buffers that may be written to by firmware.
519  *
520  * @paddr_ptr:  pointer to the address parameter in the command buffer which may
521  *              need to be saved/restored depending on whether a bounce buffer
522  *              is used. In the case of a bounce buffer, the command buffer
523  *              needs to be updated with the address of the new bounce buffer
524  *              snp_map_cmd_buf_desc() has allocated specifically for it. Must
525  *              be NULL if this descriptor is only an end-of-list indicator.
526  *
527  * @paddr_orig: storage for the original address parameter, which can be used to
528  *              restore the original value in @paddr_ptr in cases where it is
529  *              replaced with the address of a bounce buffer.
530  *
531  * @len: length of buffer located at the address originally stored at @paddr_ptr
532  *
533  * @guest_owned: true if the address corresponds to guest-owned pages, in which
534  *               case bounce buffers are not needed.
535  */
536 struct cmd_buf_desc {
537 	u64 *paddr_ptr;
538 	u64 paddr_orig;
539 	u32 len;
540 	bool guest_owned;
541 };
542 
543 /*
544  * If a legacy SEV command parameter is a memory address, those pages in
545  * turn need to be transitioned to/from firmware-owned before/after
546  * executing the firmware command.
547  *
548  * Additionally, in cases where those pages are not guest-owned, a bounce
549  * buffer is needed in place of the original memory address parameter.
550  *
551  * A set of descriptors are used to keep track of this handling, and
552  * initialized here based on the specific commands being executed.
553  */
554 static void snp_populate_cmd_buf_desc_list(int cmd, void *cmd_buf,
555 					   struct cmd_buf_desc *desc_list)
556 {
557 	switch (cmd) {
558 	case SEV_CMD_PDH_CERT_EXPORT: {
559 		struct sev_data_pdh_cert_export *data = cmd_buf;
560 
561 		desc_list[0].paddr_ptr = &data->pdh_cert_address;
562 		desc_list[0].len = data->pdh_cert_len;
563 		desc_list[1].paddr_ptr = &data->cert_chain_address;
564 		desc_list[1].len = data->cert_chain_len;
565 		break;
566 	}
567 	case SEV_CMD_GET_ID: {
568 		struct sev_data_get_id *data = cmd_buf;
569 
570 		desc_list[0].paddr_ptr = &data->address;
571 		desc_list[0].len = data->len;
572 		break;
573 	}
574 	case SEV_CMD_PEK_CSR: {
575 		struct sev_data_pek_csr *data = cmd_buf;
576 
577 		desc_list[0].paddr_ptr = &data->address;
578 		desc_list[0].len = data->len;
579 		break;
580 	}
581 	case SEV_CMD_LAUNCH_UPDATE_DATA: {
582 		struct sev_data_launch_update_data *data = cmd_buf;
583 
584 		desc_list[0].paddr_ptr = &data->address;
585 		desc_list[0].len = data->len;
586 		desc_list[0].guest_owned = true;
587 		break;
588 	}
589 	case SEV_CMD_LAUNCH_UPDATE_VMSA: {
590 		struct sev_data_launch_update_vmsa *data = cmd_buf;
591 
592 		desc_list[0].paddr_ptr = &data->address;
593 		desc_list[0].len = data->len;
594 		desc_list[0].guest_owned = true;
595 		break;
596 	}
597 	case SEV_CMD_LAUNCH_MEASURE: {
598 		struct sev_data_launch_measure *data = cmd_buf;
599 
600 		desc_list[0].paddr_ptr = &data->address;
601 		desc_list[0].len = data->len;
602 		break;
603 	}
604 	case SEV_CMD_LAUNCH_UPDATE_SECRET: {
605 		struct sev_data_launch_secret *data = cmd_buf;
606 
607 		desc_list[0].paddr_ptr = &data->guest_address;
608 		desc_list[0].len = data->guest_len;
609 		desc_list[0].guest_owned = true;
610 		break;
611 	}
612 	case SEV_CMD_DBG_DECRYPT: {
613 		struct sev_data_dbg *data = cmd_buf;
614 
615 		desc_list[0].paddr_ptr = &data->dst_addr;
616 		desc_list[0].len = data->len;
617 		desc_list[0].guest_owned = true;
618 		break;
619 	}
620 	case SEV_CMD_DBG_ENCRYPT: {
621 		struct sev_data_dbg *data = cmd_buf;
622 
623 		desc_list[0].paddr_ptr = &data->dst_addr;
624 		desc_list[0].len = data->len;
625 		desc_list[0].guest_owned = true;
626 		break;
627 	}
628 	case SEV_CMD_ATTESTATION_REPORT: {
629 		struct sev_data_attestation_report *data = cmd_buf;
630 
631 		desc_list[0].paddr_ptr = &data->address;
632 		desc_list[0].len = data->len;
633 		break;
634 	}
635 	case SEV_CMD_SEND_START: {
636 		struct sev_data_send_start *data = cmd_buf;
637 
638 		desc_list[0].paddr_ptr = &data->session_address;
639 		desc_list[0].len = data->session_len;
640 		break;
641 	}
642 	case SEV_CMD_SEND_UPDATE_DATA: {
643 		struct sev_data_send_update_data *data = cmd_buf;
644 
645 		desc_list[0].paddr_ptr = &data->hdr_address;
646 		desc_list[0].len = data->hdr_len;
647 		desc_list[1].paddr_ptr = &data->trans_address;
648 		desc_list[1].len = data->trans_len;
649 		break;
650 	}
651 	case SEV_CMD_SEND_UPDATE_VMSA: {
652 		struct sev_data_send_update_vmsa *data = cmd_buf;
653 
654 		desc_list[0].paddr_ptr = &data->hdr_address;
655 		desc_list[0].len = data->hdr_len;
656 		desc_list[1].paddr_ptr = &data->trans_address;
657 		desc_list[1].len = data->trans_len;
658 		break;
659 	}
660 	case SEV_CMD_RECEIVE_UPDATE_DATA: {
661 		struct sev_data_receive_update_data *data = cmd_buf;
662 
663 		desc_list[0].paddr_ptr = &data->guest_address;
664 		desc_list[0].len = data->guest_len;
665 		desc_list[0].guest_owned = true;
666 		break;
667 	}
668 	case SEV_CMD_RECEIVE_UPDATE_VMSA: {
669 		struct sev_data_receive_update_vmsa *data = cmd_buf;
670 
671 		desc_list[0].paddr_ptr = &data->guest_address;
672 		desc_list[0].len = data->guest_len;
673 		desc_list[0].guest_owned = true;
674 		break;
675 	}
676 	default:
677 		break;
678 	}
679 }
680 
681 static int snp_map_cmd_buf_desc(struct cmd_buf_desc *desc)
682 {
683 	unsigned int npages;
684 
685 	if (!desc->len)
686 		return 0;
687 
688 	/* Allocate a bounce buffer if this isn't a guest owned page. */
689 	if (!desc->guest_owned) {
690 		struct page *page;
691 
692 		page = alloc_pages(GFP_KERNEL_ACCOUNT, get_order(desc->len));
693 		if (!page) {
694 			pr_warn("Failed to allocate bounce buffer for SEV legacy command.\n");
695 			return -ENOMEM;
696 		}
697 
698 		desc->paddr_orig = *desc->paddr_ptr;
699 		*desc->paddr_ptr = __psp_pa(page_to_virt(page));
700 	}
701 
702 	npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
703 
704 	/* Transition the buffer to firmware-owned. */
705 	if (rmp_mark_pages_firmware(*desc->paddr_ptr, npages, true)) {
706 		pr_warn("Error moving pages to firmware-owned state for SEV legacy command.\n");
707 		return -EFAULT;
708 	}
709 
710 	return 0;
711 }
712 
713 static int snp_unmap_cmd_buf_desc(struct cmd_buf_desc *desc)
714 {
715 	unsigned int npages;
716 
717 	if (!desc->len)
718 		return 0;
719 
720 	npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
721 
722 	/* Transition the buffers back to hypervisor-owned. */
723 	if (snp_reclaim_pages(*desc->paddr_ptr, npages, true)) {
724 		pr_warn("Failed to reclaim firmware-owned pages while issuing SEV legacy command.\n");
725 		return -EFAULT;
726 	}
727 
728 	/* Copy data from bounce buffer and then free it. */
729 	if (!desc->guest_owned) {
730 		void *bounce_buf = __va(__sme_clr(*desc->paddr_ptr));
731 		void *dst_buf = __va(__sme_clr(desc->paddr_orig));
732 
733 		memcpy(dst_buf, bounce_buf, desc->len);
734 		__free_pages(virt_to_page(bounce_buf), get_order(desc->len));
735 
736 		/* Restore the original address in the command buffer. */
737 		*desc->paddr_ptr = desc->paddr_orig;
738 	}
739 
740 	return 0;
741 }
742 
743 static int snp_map_cmd_buf_desc_list(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
744 {
745 	int i;
746 
747 	snp_populate_cmd_buf_desc_list(cmd, cmd_buf, desc_list);
748 
749 	for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
750 		struct cmd_buf_desc *desc = &desc_list[i];
751 
752 		if (!desc->paddr_ptr)
753 			break;
754 
755 		if (snp_map_cmd_buf_desc(desc))
756 			goto err_unmap;
757 	}
758 
759 	return 0;
760 
761 err_unmap:
762 	for (i--; i >= 0; i--)
763 		snp_unmap_cmd_buf_desc(&desc_list[i]);
764 
765 	return -EFAULT;
766 }
767 
768 static int snp_unmap_cmd_buf_desc_list(struct cmd_buf_desc *desc_list)
769 {
770 	int i, ret = 0;
771 
772 	for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
773 		struct cmd_buf_desc *desc = &desc_list[i];
774 
775 		if (!desc->paddr_ptr)
776 			break;
777 
778 		if (snp_unmap_cmd_buf_desc(&desc_list[i]))
779 			ret = -EFAULT;
780 	}
781 
782 	return ret;
783 }
784 
785 static bool sev_cmd_buf_writable(int cmd)
786 {
787 	switch (cmd) {
788 	case SEV_CMD_PLATFORM_STATUS:
789 	case SEV_CMD_GUEST_STATUS:
790 	case SEV_CMD_LAUNCH_START:
791 	case SEV_CMD_RECEIVE_START:
792 	case SEV_CMD_LAUNCH_MEASURE:
793 	case SEV_CMD_SEND_START:
794 	case SEV_CMD_SEND_UPDATE_DATA:
795 	case SEV_CMD_SEND_UPDATE_VMSA:
796 	case SEV_CMD_PEK_CSR:
797 	case SEV_CMD_PDH_CERT_EXPORT:
798 	case SEV_CMD_GET_ID:
799 	case SEV_CMD_ATTESTATION_REPORT:
800 		return true;
801 	default:
802 		return false;
803 	}
804 }
805 
806 /* After SNP is INIT'ed, the behavior of legacy SEV commands is changed. */
807 static bool snp_legacy_handling_needed(int cmd)
808 {
809 	struct sev_device *sev = psp_master->sev_data;
810 
811 	return cmd < SEV_CMD_SNP_INIT && sev->snp_initialized;
812 }
813 
814 static int snp_prep_cmd_buf(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
815 {
816 	if (!snp_legacy_handling_needed(cmd))
817 		return 0;
818 
819 	if (snp_map_cmd_buf_desc_list(cmd, cmd_buf, desc_list))
820 		return -EFAULT;
821 
822 	/*
823 	 * Before command execution, the command buffer needs to be put into
824 	 * the firmware-owned state.
825 	 */
826 	if (sev_cmd_buf_writable(cmd)) {
827 		if (rmp_mark_pages_firmware(__pa(cmd_buf), 1, true))
828 			return -EFAULT;
829 	}
830 
831 	return 0;
832 }
833 
834 static int snp_reclaim_cmd_buf(int cmd, void *cmd_buf)
835 {
836 	if (!snp_legacy_handling_needed(cmd))
837 		return 0;
838 
839 	/*
840 	 * After command completion, the command buffer needs to be put back
841 	 * into the hypervisor-owned state.
842 	 */
843 	if (sev_cmd_buf_writable(cmd))
844 		if (snp_reclaim_pages(__pa(cmd_buf), 1, true))
845 			return -EFAULT;
846 
847 	return 0;
848 }
849 
850 int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret)
851 {
852 	struct cmd_buf_desc desc_list[CMD_BUF_DESC_MAX] = {0};
853 	struct psp_device *psp = psp_master;
854 	struct sev_device *sev;
855 	unsigned int cmdbuff_hi, cmdbuff_lo;
856 	unsigned int phys_lsb, phys_msb;
857 	unsigned int reg;
858 	void *cmd_buf;
859 	int buf_len;
860 	int ret = 0;
861 
862 	if (!psp || !psp->sev_data)
863 		return -ENODEV;
864 
865 	if (psp_dead)
866 		return -EBUSY;
867 
868 	sev = psp->sev_data;
869 
870 	buf_len = sev_cmd_buffer_len(cmd);
871 	if (WARN_ON_ONCE(!data != !buf_len))
872 		return -EINVAL;
873 
874 	/*
875 	 * Copy the incoming data to driver's scratch buffer as __pa() will not
876 	 * work for some memory, e.g. vmalloc'd addresses, and @data may not be
877 	 * physically contiguous.
878 	 */
879 	if (data) {
880 		/*
881 		 * Commands are generally issued one at a time and require the
882 		 * sev_cmd_mutex, but there could be recursive firmware requests
883 		 * due to SEV_CMD_SNP_PAGE_RECLAIM needing to be issued while
884 		 * preparing buffers for another command. This is the only known
885 		 * case of nesting in the current code, so exactly one
886 		 * additional command buffer is available for that purpose.
887 		 */
888 		if (!sev->cmd_buf_active) {
889 			cmd_buf = sev->cmd_buf;
890 			sev->cmd_buf_active = true;
891 		} else if (!sev->cmd_buf_backup_active) {
892 			cmd_buf = sev->cmd_buf_backup;
893 			sev->cmd_buf_backup_active = true;
894 		} else {
895 			dev_err(sev->dev,
896 				"SEV: too many firmware commands in progress, no command buffers available.\n");
897 			return -EBUSY;
898 		}
899 
900 		memcpy(cmd_buf, data, buf_len);
901 
902 		/*
903 		 * The behavior of the SEV-legacy commands is altered when the
904 		 * SNP firmware is in the INIT state.
905 		 */
906 		ret = snp_prep_cmd_buf(cmd, cmd_buf, desc_list);
907 		if (ret) {
908 			dev_err(sev->dev,
909 				"SEV: failed to prepare buffer for legacy command 0x%x. Error: %d\n",
910 				cmd, ret);
911 			return ret;
912 		}
913 	} else {
914 		cmd_buf = sev->cmd_buf;
915 	}
916 
917 	/* Get the physical address of the command buffer */
918 	phys_lsb = data ? lower_32_bits(__psp_pa(cmd_buf)) : 0;
919 	phys_msb = data ? upper_32_bits(__psp_pa(cmd_buf)) : 0;
920 
921 	dev_dbg(sev->dev, "sev command id %#x buffer 0x%08x%08x timeout %us\n",
922 		cmd, phys_msb, phys_lsb, psp_timeout);
923 
924 	print_hex_dump_debug("(in):  ", DUMP_PREFIX_OFFSET, 16, 2, data,
925 			     buf_len, false);
926 
927 	iowrite32(phys_lsb, sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
928 	iowrite32(phys_msb, sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
929 
930 	sev->int_rcvd = 0;
931 
932 	reg = FIELD_PREP(SEV_CMDRESP_CMD, cmd);
933 
934 	/*
935 	 * If invoked during panic handling, local interrupts are disabled so
936 	 * the PSP command completion interrupt can't be used.
937 	 * sev_wait_cmd_ioc() already checks for interrupts disabled and
938 	 * polls for PSP command completion.  Ensure we do not request an
939 	 * interrupt from the PSP if irqs disabled.
940 	 */
941 	if (!irqs_disabled())
942 		reg |= SEV_CMDRESP_IOC;
943 
944 	iowrite32(reg, sev->io_regs + sev->vdata->cmdresp_reg);
945 
946 	/* wait for command completion */
947 	ret = sev_wait_cmd_ioc(sev, &reg, psp_timeout);
948 	if (ret) {
949 		if (psp_ret)
950 			*psp_ret = 0;
951 
952 		dev_err(sev->dev, "sev command %#x timed out, disabling PSP\n", cmd);
953 		psp_dead = true;
954 
955 		return ret;
956 	}
957 
958 	psp_timeout = psp_cmd_timeout;
959 
960 	if (psp_ret)
961 		*psp_ret = FIELD_GET(PSP_CMDRESP_STS, reg);
962 
963 	if (FIELD_GET(PSP_CMDRESP_STS, reg)) {
964 		dev_dbg(sev->dev, "sev command %#x failed (%#010lx)\n",
965 			cmd, FIELD_GET(PSP_CMDRESP_STS, reg));
966 
967 		/*
968 		 * PSP firmware may report additional error information in the
969 		 * command buffer registers on error. Print contents of command
970 		 * buffer registers if they changed.
971 		 */
972 		cmdbuff_hi = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
973 		cmdbuff_lo = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
974 		if (cmdbuff_hi != phys_msb || cmdbuff_lo != phys_lsb) {
975 			dev_dbg(sev->dev, "Additional error information reported in cmdbuff:");
976 			dev_dbg(sev->dev, "  cmdbuff hi: %#010x\n", cmdbuff_hi);
977 			dev_dbg(sev->dev, "  cmdbuff lo: %#010x\n", cmdbuff_lo);
978 		}
979 		ret = -EIO;
980 	} else {
981 		ret = sev_write_init_ex_file_if_required(cmd);
982 	}
983 
984 	/*
985 	 * Copy potential output from the PSP back to data.  Do this even on
986 	 * failure in case the caller wants to glean something from the error.
987 	 */
988 	if (data) {
989 		int ret_reclaim;
990 		/*
991 		 * Restore the page state after the command completes.
992 		 */
993 		ret_reclaim = snp_reclaim_cmd_buf(cmd, cmd_buf);
994 		if (ret_reclaim) {
995 			dev_err(sev->dev,
996 				"SEV: failed to reclaim buffer for legacy command %#x. Error: %d\n",
997 				cmd, ret_reclaim);
998 			return ret_reclaim;
999 		}
1000 
1001 		memcpy(data, cmd_buf, buf_len);
1002 
1003 		if (sev->cmd_buf_backup_active)
1004 			sev->cmd_buf_backup_active = false;
1005 		else
1006 			sev->cmd_buf_active = false;
1007 
1008 		if (snp_unmap_cmd_buf_desc_list(desc_list))
1009 			return -EFAULT;
1010 	}
1011 
1012 	print_hex_dump_debug("(out): ", DUMP_PREFIX_OFFSET, 16, 2, data,
1013 			     buf_len, false);
1014 
1015 	return ret;
1016 }
1017 
1018 int sev_do_cmd(int cmd, void *data, int *psp_ret)
1019 {
1020 	int rc;
1021 
1022 	mutex_lock(&sev_cmd_mutex);
1023 	rc = __sev_do_cmd_locked(cmd, data, psp_ret);
1024 	mutex_unlock(&sev_cmd_mutex);
1025 
1026 	return rc;
1027 }
1028 EXPORT_SYMBOL_GPL(sev_do_cmd);
1029 
1030 static int __sev_init_locked(int *error)
1031 {
1032 	struct sev_data_init data;
1033 
1034 	memset(&data, 0, sizeof(data));
1035 	if (sev_es_tmr) {
1036 		/*
1037 		 * Do not include the encryption mask on the physical
1038 		 * address of the TMR (firmware should clear it anyway).
1039 		 */
1040 		data.tmr_address = __pa(sev_es_tmr);
1041 
1042 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
1043 		data.tmr_len = sev_es_tmr_size;
1044 	}
1045 
1046 	return __sev_do_cmd_locked(SEV_CMD_INIT, &data, error);
1047 }
1048 
1049 static int __sev_init_ex_locked(int *error)
1050 {
1051 	struct sev_data_init_ex data;
1052 
1053 	memset(&data, 0, sizeof(data));
1054 	data.length = sizeof(data);
1055 	data.nv_address = __psp_pa(sev_init_ex_buffer);
1056 	data.nv_len = NV_LENGTH;
1057 
1058 	if (sev_es_tmr) {
1059 		/*
1060 		 * Do not include the encryption mask on the physical
1061 		 * address of the TMR (firmware should clear it anyway).
1062 		 */
1063 		data.tmr_address = __pa(sev_es_tmr);
1064 
1065 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
1066 		data.tmr_len = sev_es_tmr_size;
1067 	}
1068 
1069 	return __sev_do_cmd_locked(SEV_CMD_INIT_EX, &data, error);
1070 }
1071 
1072 static inline int __sev_do_init_locked(int *psp_ret)
1073 {
1074 	if (sev_init_ex_buffer)
1075 		return __sev_init_ex_locked(psp_ret);
1076 	else
1077 		return __sev_init_locked(psp_ret);
1078 }
1079 
1080 /* Hypervisor Fixed pages API interface */
1081 static void snp_hv_fixed_pages_state_update(struct sev_device *sev,
1082 					    enum snp_hv_fixed_pages_state page_state)
1083 {
1084 	struct snp_hv_fixed_pages_entry *entry;
1085 
1086 	/* List is protected by sev_cmd_mutex */
1087 	lockdep_assert_held(&sev_cmd_mutex);
1088 
1089 	if (list_empty(&snp_hv_fixed_pages))
1090 		return;
1091 
1092 	list_for_each_entry(entry, &snp_hv_fixed_pages, list)
1093 		entry->page_state = page_state;
1094 }
1095 
1096 /*
1097  * Allocate HV_FIXED pages in 2MB aligned sizes to ensure the whole
1098  * 2MB pages are marked as HV_FIXED.
1099  */
1100 struct page *snp_alloc_hv_fixed_pages(unsigned int num_2mb_pages)
1101 {
1102 	struct psp_device *psp_master = psp_get_master_device();
1103 	struct snp_hv_fixed_pages_entry *entry;
1104 	unsigned int order;
1105 	struct page *page;
1106 
1107 	if (!psp_master)
1108 		return NULL;
1109 
1110 	order = get_order(PMD_SIZE * num_2mb_pages);
1111 
1112 	/*
1113 	 * SNP_INIT_EX is protected by sev_cmd_mutex, therefore this list
1114 	 * also needs to be protected using the same mutex.
1115 	 */
1116 	guard(mutex)(&sev_cmd_mutex);
1117 
1118 	/*
1119 	 * This API uses SNP_INIT_EX to transition allocated pages to HV_Fixed
1120 	 * page state, fail if SNP is already initialized.
1121 	 */
1122 	if (psp_master->sev_data &&
1123 	    ((struct sev_device *)psp_master->sev_data)->snp_initialized)
1124 		return NULL;
1125 
1126 	/* Re-use freed pages that match the request */
1127 	list_for_each_entry(entry, &snp_hv_fixed_pages, list) {
1128 		/* Hypervisor fixed page allocator implements exact fit policy */
1129 		if (entry->order == order && entry->free) {
1130 			entry->free = false;
1131 			memset(page_address(entry->page), 0,
1132 			       (1 << entry->order) * PAGE_SIZE);
1133 			return entry->page;
1134 		}
1135 	}
1136 
1137 	page = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1138 	if (!page)
1139 		return NULL;
1140 
1141 	entry = kzalloc_obj(*entry);
1142 	if (!entry) {
1143 		__free_pages(page, order);
1144 		return NULL;
1145 	}
1146 
1147 	entry->page = page;
1148 	entry->order = order;
1149 	list_add_tail(&entry->list, &snp_hv_fixed_pages);
1150 
1151 	return page;
1152 }
1153 
1154 void snp_free_hv_fixed_pages(struct page *page)
1155 {
1156 	struct psp_device *psp_master = psp_get_master_device();
1157 	struct snp_hv_fixed_pages_entry *entry, *nentry;
1158 
1159 	if (!psp_master)
1160 		return;
1161 
1162 	/*
1163 	 * SNP_INIT_EX is protected by sev_cmd_mutex, therefore this list
1164 	 * also needs to be protected using the same mutex.
1165 	 */
1166 	guard(mutex)(&sev_cmd_mutex);
1167 
1168 	list_for_each_entry_safe(entry, nentry, &snp_hv_fixed_pages, list) {
1169 		if (entry->page != page)
1170 			continue;
1171 
1172 		/*
1173 		 * HV_FIXED page state cannot be changed until reboot
1174 		 * and they cannot be used by an SNP guest, so they cannot
1175 		 * be returned back to the page allocator.
1176 		 * Mark the pages as free internally to allow possible re-use.
1177 		 */
1178 		if (entry->page_state == HV_FIXED) {
1179 			entry->free = true;
1180 		} else {
1181 			__free_pages(page, entry->order);
1182 			list_del(&entry->list);
1183 			kfree(entry);
1184 		}
1185 		return;
1186 	}
1187 }
1188 
1189 static void snp_add_hv_fixed_pages(struct sev_device *sev, struct sev_data_range_list *range_list)
1190 {
1191 	struct snp_hv_fixed_pages_entry *entry;
1192 	struct sev_data_range *range;
1193 	int num_elements;
1194 
1195 	lockdep_assert_held(&sev_cmd_mutex);
1196 
1197 	if (list_empty(&snp_hv_fixed_pages))
1198 		return;
1199 
1200 	num_elements = list_count_nodes(&snp_hv_fixed_pages) +
1201 		       range_list->num_elements;
1202 
1203 	/*
1204 	 * Ensure the list of HV_FIXED pages that will be passed to firmware
1205 	 * do not exceed the page-sized argument buffer.
1206 	 */
1207 	if (num_elements * sizeof(*range) + sizeof(*range_list) > PAGE_SIZE) {
1208 		dev_warn(sev->dev, "Additional HV_Fixed pages cannot be accommodated, omitting\n");
1209 		return;
1210 	}
1211 
1212 	range = &range_list->ranges[range_list->num_elements];
1213 	list_for_each_entry(entry, &snp_hv_fixed_pages, list) {
1214 		range->base = page_to_pfn(entry->page) << PAGE_SHIFT;
1215 		range->page_count = 1 << entry->order;
1216 		range++;
1217 	}
1218 	range_list->num_elements = num_elements;
1219 }
1220 
1221 static void snp_leak_hv_fixed_pages(void)
1222 {
1223 	struct snp_hv_fixed_pages_entry *entry, *nentry;
1224 
1225 	/* List is protected by sev_cmd_mutex */
1226 	lockdep_assert_held(&sev_cmd_mutex);
1227 
1228 	if (list_empty(&snp_hv_fixed_pages))
1229 		return;
1230 
1231 	list_for_each_entry_safe(entry, nentry, &snp_hv_fixed_pages, list) {
1232 		if (entry->free && entry->page_state != HV_FIXED)
1233 			__free_pages(entry->page, entry->order);
1234 		else
1235 			__snp_leak_pages(page_to_pfn(entry->page),
1236 					 1 << entry->order, false);
1237 
1238 		list_del(&entry->list);
1239 		kfree(entry);
1240 	}
1241 }
1242 
1243 bool sev_is_snp_ciphertext_hiding_supported(void)
1244 {
1245 	struct psp_device *psp = psp_master;
1246 	struct sev_device *sev;
1247 
1248 	if (!psp || !psp->sev_data)
1249 		return false;
1250 
1251 	sev = psp->sev_data;
1252 
1253 	/*
1254 	 * Feature information indicates if CipherTextHiding feature is
1255 	 * supported by the SEV firmware and additionally platform status
1256 	 * indicates if CipherTextHiding feature is enabled in the
1257 	 * Platform BIOS.
1258 	 */
1259 	return ((sev->snp_feat_info_0.ecx & SNP_CIPHER_TEXT_HIDING_SUPPORTED) &&
1260 		 sev->snp_plat_status.ciphertext_hiding_cap);
1261 }
1262 EXPORT_SYMBOL_GPL(sev_is_snp_ciphertext_hiding_supported);
1263 
1264 static int snp_get_platform_data(struct sev_device *sev, int *error)
1265 {
1266 	struct sev_data_snp_feature_info snp_feat_info;
1267 	struct snp_feature_info *feat_info;
1268 	struct sev_data_snp_addr buf;
1269 	struct page *page;
1270 	int rc;
1271 
1272 	/*
1273 	 * This function is expected to be called before SNP is
1274 	 * initialized.
1275 	 */
1276 	if (sev->snp_initialized)
1277 		return -EINVAL;
1278 
1279 	buf.address = __psp_pa(&sev->snp_plat_status);
1280 	rc = sev_do_cmd(SEV_CMD_SNP_PLATFORM_STATUS, &buf, error);
1281 	if (rc) {
1282 		dev_err(sev->dev, "SNP PLATFORM_STATUS command failed, ret = %d, error = %#x\n",
1283 			rc, *error);
1284 		return rc;
1285 	}
1286 
1287 	sev->api_major = sev->snp_plat_status.api_major;
1288 	sev->api_minor = sev->snp_plat_status.api_minor;
1289 	sev->build = sev->snp_plat_status.build_id;
1290 
1291 	/*
1292 	 * Do feature discovery of the currently loaded firmware,
1293 	 * and cache feature information from CPUID 0x8000_0024,
1294 	 * sub-function 0.
1295 	 */
1296 	if (!sev->snp_plat_status.feature_info)
1297 		return 0;
1298 
1299 	/*
1300 	 * Use dynamically allocated structure for the SNP_FEATURE_INFO
1301 	 * command to ensure structure is 8-byte aligned, and does not
1302 	 * cross a page boundary.
1303 	 */
1304 	page = alloc_page(GFP_KERNEL);
1305 	if (!page)
1306 		return -ENOMEM;
1307 
1308 	feat_info = page_address(page);
1309 	snp_feat_info.length = sizeof(snp_feat_info);
1310 	snp_feat_info.ecx_in = 0;
1311 	snp_feat_info.feature_info_paddr = __psp_pa(feat_info);
1312 
1313 	rc = sev_do_cmd(SEV_CMD_SNP_FEATURE_INFO, &snp_feat_info, error);
1314 	if (!rc)
1315 		sev->snp_feat_info_0 = *feat_info;
1316 	else
1317 		dev_err(sev->dev, "SNP FEATURE_INFO command failed, ret = %d, error = %#x\n",
1318 			rc, *error);
1319 
1320 	__free_page(page);
1321 
1322 	return rc;
1323 }
1324 
1325 static int snp_filter_reserved_mem_regions(struct resource *rs, void *arg)
1326 {
1327 	struct sev_data_range_list *range_list = arg;
1328 	struct sev_data_range *range = &range_list->ranges[range_list->num_elements];
1329 	size_t size;
1330 
1331 	/*
1332 	 * Ensure the list of HV_FIXED pages passed to the firmware including
1333 	 * the one about to be written to do not exceed the page-sized argument
1334 	 * buffer.
1335 	 */
1336 	if (((range_list->num_elements + 1) * sizeof(struct sev_data_range) +
1337 	     sizeof(struct sev_data_range_list)) > PAGE_SIZE)
1338 		return -E2BIG;
1339 
1340 	switch (rs->desc) {
1341 	case E820_TYPE_RESERVED:
1342 	case E820_TYPE_PMEM:
1343 	case E820_TYPE_ACPI:
1344 		range->base = rs->start & PAGE_MASK;
1345 		size = PAGE_ALIGN((rs->end + 1) - rs->start);
1346 		range->page_count = size >> PAGE_SHIFT;
1347 		range_list->num_elements++;
1348 		break;
1349 	default:
1350 		break;
1351 	}
1352 
1353 	return 0;
1354 }
1355 
1356 #ifdef CONFIG_SYSFS
1357 static int snp_verify_mitigation(u16 command, u64 vector,
1358 				 struct sev_data_snp_verify_mitigation_dst *dst)
1359 {
1360 	struct sev_data_snp_verify_mitigation_dst *mit_dst = NULL;
1361 	struct sev_data_snp_verify_mitigation data = {0};
1362 	struct sev_device *sev = psp_master->sev_data;
1363 	int ret, error = 0;
1364 
1365 	mit_dst = snp_alloc_firmware_page(GFP_KERNEL | __GFP_ZERO);
1366 	if (!mit_dst)
1367 		return -ENOMEM;
1368 
1369 	data.length = sizeof(data);
1370 	data.subcommand = command;
1371 	data.vector = vector;
1372 	data.dst_paddr = __psp_pa(mit_dst);
1373 	data.dst_paddr_en = true;
1374 
1375 	ret = sev_do_cmd(SEV_CMD_SNP_VERIFY_MITIGATION, &data, &error);
1376 	if (!ret)
1377 		memcpy(dst, mit_dst, sizeof(*mit_dst));
1378 	else
1379 		dev_err(sev->dev, "SNP_VERIFY_MITIGATION command failed, ret = %d, error = %#x\n",
1380 			ret, error);
1381 
1382 	snp_free_firmware_page(mit_dst);
1383 
1384 	return ret;
1385 }
1386 
1387 static ssize_t supported_mitigations_show(struct kobject *kobj,
1388 					  struct kobj_attribute *attr, char *buf)
1389 {
1390 	struct sev_data_snp_verify_mitigation_dst dst;
1391 	int ret;
1392 
1393 	ret = snp_verify_mitigation(SNP_MIT_SUBCMD_REQ_STATUS, 0, &dst);
1394 	if (ret)
1395 		return ret;
1396 
1397 	return sysfs_emit(buf, "0x%llx\n", dst.mit_supported_vector);
1398 }
1399 
1400 static struct kobj_attribute supported_attr =
1401 		__ATTR_RO_MODE(supported_mitigations, 0400);
1402 
1403 static ssize_t verified_mitigations_show(struct kobject *kobj,
1404 					 struct kobj_attribute *attr, char *buf)
1405 {
1406 	struct sev_data_snp_verify_mitigation_dst dst;
1407 	int ret;
1408 
1409 	ret = snp_verify_mitigation(SNP_MIT_SUBCMD_REQ_STATUS, 0, &dst);
1410 	if (ret)
1411 		return ret;
1412 
1413 	return sysfs_emit(buf, "0x%llx\n", dst.mit_verified_vector);
1414 }
1415 
1416 static ssize_t verified_mitigations_store(struct kobject *kobj,
1417 					  struct kobj_attribute *attr,
1418 					  const char *buf, size_t count)
1419 {
1420 	struct sev_data_snp_verify_mitigation_dst dst;
1421 	struct sev_device *sev = psp_master->sev_data;
1422 	u64 vector;
1423 	int ret;
1424 
1425 	ret = kstrtoull(buf, 0, &vector);
1426 	if (ret)
1427 		return ret;
1428 
1429 	/*
1430 	 * The firmware verifies a single mitigation per call. Reject vectors
1431 	 * with more than one bit set early to avoid a guaranteed-to-fail call
1432 	 */
1433 	if (hweight64(vector) != 1)
1434 		return -EINVAL;
1435 
1436 	ret = snp_verify_mitigation(SNP_MIT_SUBCMD_REQ_VERIFY, vector, &dst);
1437 	if (ret)
1438 		return ret;
1439 
1440 	if (dst.mit_failure_status) {
1441 		dev_err(sev->dev, "Verify Mitigation - failure status: 0x%x\n",
1442 			dst.mit_failure_status);
1443 		return -EINVAL;
1444 	}
1445 
1446 	return count;
1447 }
1448 
1449 static struct kobj_attribute verified_attr =
1450 		__ATTR_RW_MODE(verified_mitigations, 0600);
1451 
1452 static struct attribute *mitigation_attrs[] = {
1453 	&supported_attr.attr,
1454 	&verified_attr.attr,
1455 	NULL
1456 };
1457 
1458 static const struct attribute_group mit_attr_group = {
1459 	.attrs = mitigation_attrs,
1460 };
1461 
1462 static void sev_snp_register_verify_mitigation(struct sev_device *sev)
1463 {
1464 	int rc;
1465 
1466 	if (!(sev->snp_feat_info_0.ecx & SNP_VERIFY_MITIGATION_SUPPORTED) ||
1467 	    sev->verify_mit)
1468 		return;
1469 
1470 	if (!sev->sev_kobj) {
1471 		sev->sev_kobj = kobject_create_and_add("sev", firmware_kobj);
1472 		if (!sev->sev_kobj)
1473 			return;
1474 	}
1475 
1476 	sev->verify_mit = kobject_create_and_add("vulnerabilities", sev->sev_kobj);
1477 	if (!sev->verify_mit)
1478 		goto err_sev_kobj;
1479 
1480 	rc = sysfs_create_group(sev->verify_mit, &mit_attr_group);
1481 	if (rc)
1482 		goto err_verify_mit;
1483 
1484 	return;
1485 
1486 err_verify_mit:
1487 	kobject_put(sev->verify_mit);
1488 	sev->verify_mit = NULL;
1489 err_sev_kobj:
1490 	kobject_put(sev->sev_kobj);
1491 	sev->sev_kobj = NULL;
1492 }
1493 
1494 static void sev_snp_unregister_verify_mitigation(struct sev_device *sev)
1495 {
1496 	if (sev->verify_mit) {
1497 		sysfs_remove_group(sev->verify_mit, &mit_attr_group);
1498 		kobject_put(sev->verify_mit);
1499 		sev->verify_mit = NULL;
1500 	}
1501 
1502 	if (sev->sev_kobj) {
1503 		kobject_put(sev->sev_kobj);
1504 		sev->sev_kobj = NULL;
1505 	}
1506 }
1507 #else	// CONFIG_SYSFS
1508 static void sev_snp_register_verify_mitigation(struct sev_device *sev) { }
1509 static void sev_snp_unregister_verify_mitigation(struct sev_device *sev) { }
1510 #endif	// CONFIG_SYSFS
1511 
1512 static int __sev_snp_init_locked(int *error, unsigned int max_snp_asid)
1513 {
1514 	struct sev_data_range_list *snp_range_list __free(kfree) = NULL;
1515 	struct psp_device *psp = psp_master;
1516 	struct sev_data_snp_init_ex data = {};
1517 	struct sev_device *sev;
1518 	void *arg = &data;
1519 	int cmd, rc = 0;
1520 
1521 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
1522 		return -ENODEV;
1523 
1524 	sev = psp->sev_data;
1525 
1526 	if (sev->snp_initialized)
1527 		return 0;
1528 
1529 	if (!sev_version_greater_or_equal(SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR)) {
1530 		dev_dbg(sev->dev, "SEV-SNP support requires firmware version >= %d:%d\n",
1531 			SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR);
1532 		return -EOPNOTSUPP;
1533 	}
1534 
1535 	rc = snp_prepare();
1536 	if (rc)
1537 		return rc;
1538 
1539 	/*
1540 	 * Starting in SNP firmware v1.52, the SNP_INIT_EX command takes a list
1541 	 * of system physical address ranges to convert into HV-fixed page
1542 	 * states during the RMP initialization.  For instance, the memory that
1543 	 * UEFI reserves should be included in the that list. This allows system
1544 	 * components that occasionally write to memory (e.g. logging to UEFI
1545 	 * reserved regions) to not fail due to RMP initialization and SNP
1546 	 * enablement.
1547 	 *
1548 	 */
1549 	if (sev_version_greater_or_equal(SNP_MIN_API_MAJOR, 52)) {
1550 		bool tio_supp = !!(sev->snp_feat_info_0.ebx & SNP_SEV_TIO_SUPPORTED);
1551 
1552 		/*
1553 		 * Firmware checks that the pages containing the ranges enumerated
1554 		 * in the RANGES structure are either in the default page state or in the
1555 		 * firmware page state.
1556 		 */
1557 		snp_range_list = kzalloc(PAGE_SIZE, GFP_KERNEL);
1558 		if (!snp_range_list) {
1559 			dev_err(sev->dev,
1560 				"SEV: SNP_INIT_EX range list memory allocation failed\n");
1561 			return -ENOMEM;
1562 		}
1563 
1564 		/*
1565 		 * Retrieve all reserved memory regions from the e820 memory map
1566 		 * to be setup as HV-fixed pages.
1567 		 */
1568 		rc = walk_iomem_res_desc(IORES_DESC_NONE, IORESOURCE_MEM, 0, ~0,
1569 					 snp_range_list, snp_filter_reserved_mem_regions);
1570 		if (rc) {
1571 			dev_err(sev->dev,
1572 				"SEV: SNP_INIT_EX walk_iomem_res_desc failed rc = %d\n", rc);
1573 			return rc;
1574 		}
1575 
1576 		/*
1577 		 * Add HV_Fixed pages from other PSP sub-devices, such as SFS to the
1578 		 * HV_Fixed page list.
1579 		 */
1580 		snp_add_hv_fixed_pages(sev, snp_range_list);
1581 
1582 		if (max_snp_asid) {
1583 			data.ciphertext_hiding_en = 1;
1584 			data.max_snp_asid = max_snp_asid;
1585 		}
1586 
1587 		data.init_rmp = 1;
1588 		data.list_paddr_en = 1;
1589 		data.list_paddr = __psp_pa(snp_range_list);
1590 
1591 		data.tio_en = tio_supp && sev_tio_enabled && amd_iommu_sev_tio_supported();
1592 
1593 		/*
1594 		 * When psp_init_on_probe is disabled, the userspace calling
1595 		 * SEV ioctl can inadvertently shut down SNP and SEV-TIO causing
1596 		 * unexpected state loss.
1597 		 */
1598 		if (data.tio_en && !psp_init_on_probe)
1599 			dev_warn(sev->dev, "SEV-TIO as incompatible with psp_init_on_probe=0\n");
1600 
1601 		cmd = SEV_CMD_SNP_INIT_EX;
1602 	} else {
1603 		cmd = SEV_CMD_SNP_INIT;
1604 		arg = NULL;
1605 	}
1606 
1607 	/*
1608 	 * The following sequence must be issued before launching the first SNP
1609 	 * guest to ensure all dirty cache lines are flushed, including from
1610 	 * updates to the RMP table itself via the RMPUPDATE instruction:
1611 	 *
1612 	 * - WBINVD on all running CPUs
1613 	 * - SEV_CMD_SNP_INIT[_EX] firmware command
1614 	 * - WBINVD on all running CPUs
1615 	 * - SEV_CMD_SNP_DF_FLUSH firmware command
1616 	 */
1617 	wbinvd_on_all_cpus();
1618 
1619 	rc = __sev_do_cmd_locked(cmd, arg, error);
1620 	if (rc) {
1621 		dev_err(sev->dev, "SEV-SNP: %s failed rc %d, error %#x\n",
1622 			cmd == SEV_CMD_SNP_INIT_EX ? "SNP_INIT_EX" : "SNP_INIT",
1623 			rc, *error);
1624 		return rc;
1625 	}
1626 
1627 	/* Prepare for first SNP guest launch after INIT. */
1628 	wbinvd_on_all_cpus();
1629 	rc = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, error);
1630 	if (rc) {
1631 		dev_err(sev->dev, "SEV-SNP: SNP_DF_FLUSH failed rc %d, error %#x\n",
1632 			rc, *error);
1633 		return rc;
1634 	}
1635 
1636 	snp_hv_fixed_pages_state_update(sev, HV_FIXED);
1637 	sev->snp_initialized = true;
1638 	dev_dbg(sev->dev, "SEV-SNP firmware initialized, SEV-TIO is %s\n",
1639 		data.tio_en ? "enabled" : "disabled");
1640 
1641 	dev_info(sev->dev, "SEV-SNP API:%d.%d build:%d\n", sev->api_major,
1642 		 sev->api_minor, sev->build);
1643 
1644 	atomic_notifier_chain_register(&panic_notifier_list,
1645 				       &snp_panic_notifier);
1646 
1647 	if (data.tio_en) {
1648 		struct page *page;
1649 
1650 		/*
1651 		 * This executes with the sev_cmd_mutex held so down the stack
1652 		 * snp_reclaim_pages(locked=false) might be needed (which is extremely
1653 		 * unlikely) but will cause a deadlock.
1654 		 * Instead of exporting __snp_alloc_firmware_pages(), allocate a page
1655 		 * for this one call here.
1656 		 */
1657 		page = __snp_alloc_firmware_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1658 						  0, true);
1659 		if (page) {
1660 			void *tio_status = page_address(page);
1661 
1662 			sev_tsm_init_locked(sev, tio_status);
1663 
1664 			__snp_free_firmware_pages(page, 0, true);
1665 		}
1666 	}
1667 
1668 	sev_es_tmr_size = SNP_TMR_SIZE;
1669 
1670 	return 0;
1671 }
1672 
1673 static void __sev_platform_init_handle_tmr(struct sev_device *sev)
1674 {
1675 	if (sev_es_tmr)
1676 		return;
1677 
1678 	/* Obtain the TMR memory area for SEV-ES use */
1679 	sev_es_tmr = sev_fw_alloc(sev_es_tmr_size);
1680 	if (sev_es_tmr) {
1681 		/* Must flush the cache before giving it to the firmware */
1682 		if (!sev->snp_initialized)
1683 			clflush_cache_range(sev_es_tmr, sev_es_tmr_size);
1684 	} else {
1685 			dev_warn(sev->dev, "SEV: TMR allocation failed, SEV-ES support unavailable\n");
1686 	}
1687 }
1688 
1689 /*
1690  * If an init_ex_path is provided allocate a buffer for the file and
1691  * read in the contents. Additionally, if SNP is initialized, convert
1692  * the buffer pages to firmware pages.
1693  */
1694 static int __sev_platform_init_handle_init_ex_path(struct sev_device *sev)
1695 {
1696 	struct page *page;
1697 	int rc;
1698 
1699 	if (!init_ex_path)
1700 		return 0;
1701 
1702 	if (sev_init_ex_buffer)
1703 		return 0;
1704 
1705 	page = alloc_pages(GFP_KERNEL | __GFP_ZERO, get_order(NV_LENGTH));
1706 	if (!page) {
1707 		dev_err(sev->dev, "SEV: INIT_EX NV memory allocation failed\n");
1708 		return -ENOMEM;
1709 	}
1710 
1711 	sev_init_ex_buffer = page_address(page);
1712 
1713 	rc = sev_read_init_ex_file();
1714 	if (rc)
1715 		goto err_free;
1716 
1717 	/* If SEV-SNP is initialized, transition to firmware page. */
1718 	if (sev->snp_initialized) {
1719 		unsigned long npages;
1720 
1721 		npages = 1UL << get_order(NV_LENGTH);
1722 		if (rmp_mark_pages_firmware(__pa(sev_init_ex_buffer), npages, true)) {
1723 			dev_err(sev->dev, "SEV: INIT_EX NV memory page state change failed.\n");
1724 			rc = -ENOMEM;
1725 			/*
1726 			 * Pages can be in an inconsistent state, don't release them back to the
1727 			 * system.
1728 			 */
1729 			goto err_reset;
1730 		}
1731 	}
1732 
1733 	return 0;
1734 
1735 err_free:
1736 	__free_pages(page, get_order(NV_LENGTH));
1737 err_reset:
1738 	sev_init_ex_buffer = NULL;
1739 	return rc;
1740 }
1741 
1742 static int __sev_platform_init_locked(int *error)
1743 {
1744 	int rc, psp_ret, dfflush_error;
1745 	struct sev_device *sev;
1746 
1747 	psp_ret = dfflush_error = SEV_RET_NO_FW_CALL;
1748 
1749 	if (!psp_master || !psp_master->sev_data)
1750 		return -ENODEV;
1751 
1752 	sev = psp_master->sev_data;
1753 
1754 	if (sev->sev_plat_status.state == SEV_STATE_INIT)
1755 		return 0;
1756 
1757 	__sev_platform_init_handle_tmr(sev);
1758 
1759 	rc = __sev_platform_init_handle_init_ex_path(sev);
1760 	if (rc)
1761 		return rc;
1762 
1763 	rc = __sev_do_init_locked(&psp_ret);
1764 	if (rc && psp_ret == SEV_RET_SECURE_DATA_INVALID) {
1765 		/*
1766 		 * Initialization command returned an integrity check failure
1767 		 * status code, meaning that firmware load and validation of SEV
1768 		 * related persistent data has failed. Retrying the
1769 		 * initialization function should succeed by replacing the state
1770 		 * with a reset state.
1771 		 */
1772 		dev_err(sev->dev,
1773 "SEV: retrying INIT command because of SECURE_DATA_INVALID error. Retrying once to reset PSP SEV state.");
1774 		rc = __sev_do_init_locked(&psp_ret);
1775 	}
1776 
1777 	if (error)
1778 		*error = psp_ret;
1779 
1780 	if (rc) {
1781 		dev_err(sev->dev, "SEV: %s failed %#x, rc %d\n",
1782 			sev_init_ex_buffer ? "INIT_EX" : "INIT", psp_ret, rc);
1783 		return rc;
1784 	}
1785 
1786 	sev->sev_plat_status.state = SEV_STATE_INIT;
1787 
1788 	/* Prepare for first SEV guest launch after INIT */
1789 	wbinvd_on_all_cpus();
1790 	rc = __sev_do_cmd_locked(SEV_CMD_DF_FLUSH, NULL, &dfflush_error);
1791 	if (rc) {
1792 		dev_err(sev->dev, "SEV: DF_FLUSH failed %#x, rc %d\n",
1793 			dfflush_error, rc);
1794 		return rc;
1795 	}
1796 
1797 	dev_dbg(sev->dev, "SEV firmware initialized\n");
1798 
1799 	dev_info(sev->dev, "SEV API:%d.%d build:%d\n", sev->api_major,
1800 		 sev->api_minor, sev->build);
1801 
1802 	return 0;
1803 }
1804 
1805 static int _sev_platform_init_locked(struct sev_platform_init_args *args)
1806 {
1807 	struct sev_device *sev;
1808 	int rc;
1809 
1810 	if (!psp_master || !psp_master->sev_data)
1811 		return -ENODEV;
1812 
1813 	/*
1814 	 * Skip SNP/SEV initialization under a kdump kernel as SEV/SNP
1815 	 * may already be initialized in the previous kernel. Since no
1816 	 * SNP/SEV guests are run under a kdump kernel, there is no
1817 	 * need to initialize SNP or SEV during kdump boot.
1818 	 */
1819 	if (is_kdump_kernel())
1820 		return 0;
1821 
1822 	sev = psp_master->sev_data;
1823 
1824 	if (sev->sev_plat_status.state == SEV_STATE_INIT)
1825 		return 0;
1826 
1827 	rc = __sev_snp_init_locked(&args->error, args->max_snp_asid);
1828 	if (rc && rc != -ENODEV)
1829 		return rc;
1830 
1831 	/* Defer legacy SEV/SEV-ES support if allowed by caller/module. */
1832 	if (args->probe && !psp_init_on_probe)
1833 		return 0;
1834 
1835 	return __sev_platform_init_locked(&args->error);
1836 }
1837 
1838 int sev_platform_init(struct sev_platform_init_args *args)
1839 {
1840 	int rc;
1841 
1842 	mutex_lock(&sev_cmd_mutex);
1843 	rc = _sev_platform_init_locked(args);
1844 	mutex_unlock(&sev_cmd_mutex);
1845 
1846 	/*
1847 	 * Register the sysfs interface outside the sev_cmd_mutex. The
1848 	 * _show()/_store() handlers issue SEV commands that acquire the
1849 	 * sev_cmd_mutex, so creating (and on the shutdown path, removing) the
1850 	 * sysfs group must stay outside that lock. sysfs provides its own
1851 	 * synchronization between group creation/removal and concurrent
1852 	 * attribute access.
1853 	 */
1854 	if (!rc)
1855 		sev_snp_register_verify_mitigation(psp_master->sev_data);
1856 
1857 	return rc;
1858 }
1859 EXPORT_SYMBOL_GPL(sev_platform_init);
1860 
1861 static int __sev_platform_shutdown_locked(int *error)
1862 {
1863 	struct psp_device *psp = psp_master;
1864 	struct sev_device *sev;
1865 	int ret;
1866 
1867 	if (!psp || !psp->sev_data)
1868 		return 0;
1869 
1870 	sev = psp->sev_data;
1871 
1872 	if (sev->sev_plat_status.state == SEV_STATE_UNINIT)
1873 		return 0;
1874 
1875 	ret = __sev_do_cmd_locked(SEV_CMD_SHUTDOWN, NULL, error);
1876 	if (ret) {
1877 		dev_err(sev->dev, "SEV: failed to SHUTDOWN error %#x, rc %d\n",
1878 			*error, ret);
1879 		return ret;
1880 	}
1881 
1882 	sev->sev_plat_status.state = SEV_STATE_UNINIT;
1883 	dev_dbg(sev->dev, "SEV firmware shutdown\n");
1884 
1885 	return ret;
1886 }
1887 
1888 static int sev_get_platform_state(int *state, int *error)
1889 {
1890 	struct sev_user_data_status data;
1891 	int rc;
1892 
1893 	rc = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, error);
1894 	if (rc)
1895 		return rc;
1896 
1897 	*state = data.state;
1898 	return rc;
1899 }
1900 
1901 static int sev_move_to_init_state(struct sev_issue_cmd *argp, bool *shutdown_required)
1902 {
1903 	int rc;
1904 
1905 	rc = __sev_platform_init_locked(&argp->error);
1906 	if (rc)
1907 		return rc;
1908 
1909 	*shutdown_required = true;
1910 
1911 	return 0;
1912 }
1913 
1914 static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable)
1915 {
1916 	int state, rc;
1917 
1918 	if (!writable)
1919 		return -EPERM;
1920 
1921 	/*
1922 	 * The SEV spec requires that FACTORY_RESET must be issued in
1923 	 * UNINIT state. Before we go further lets check if any guest is
1924 	 * active.
1925 	 *
1926 	 * If FW is in WORKING state then deny the request otherwise issue
1927 	 * SHUTDOWN command do INIT -> UNINIT before issuing the FACTORY_RESET.
1928 	 *
1929 	 */
1930 	rc = sev_get_platform_state(&state, &argp->error);
1931 	if (rc)
1932 		return rc;
1933 
1934 	if (state == SEV_STATE_WORKING)
1935 		return -EBUSY;
1936 
1937 	if (state == SEV_STATE_INIT) {
1938 		rc = __sev_platform_shutdown_locked(&argp->error);
1939 		if (rc)
1940 			return rc;
1941 	}
1942 
1943 	return __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error);
1944 }
1945 
1946 static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp)
1947 {
1948 	struct sev_user_data_status data;
1949 	int ret;
1950 
1951 	memset(&data, 0, sizeof(data));
1952 
1953 	ret = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, &argp->error);
1954 	if (ret)
1955 		return ret;
1956 
1957 	if (copy_to_user((void __user *)argp->data, &data, sizeof(data)))
1958 		ret = -EFAULT;
1959 
1960 	return ret;
1961 }
1962 
1963 static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool writable)
1964 {
1965 	struct sev_device *sev = psp_master->sev_data;
1966 	bool shutdown_required = false;
1967 	int rc;
1968 
1969 	if (!writable)
1970 		return -EPERM;
1971 
1972 	if (sev->sev_plat_status.state == SEV_STATE_UNINIT) {
1973 		rc = sev_move_to_init_state(argp, &shutdown_required);
1974 		if (rc)
1975 			return rc;
1976 	}
1977 
1978 	rc = __sev_do_cmd_locked(cmd, NULL, &argp->error);
1979 
1980 	if (shutdown_required)
1981 		__sev_firmware_shutdown(sev, false);
1982 
1983 	return rc;
1984 }
1985 
1986 static int sev_ioctl_do_pek_csr(struct sev_issue_cmd *argp, bool writable)
1987 {
1988 	struct sev_device *sev = psp_master->sev_data;
1989 	struct sev_user_data_pek_csr input;
1990 	bool shutdown_required = false;
1991 	struct sev_data_pek_csr data;
1992 	void __user *input_address;
1993 	void *blob = NULL;
1994 	int ret;
1995 
1996 	if (!writable)
1997 		return -EPERM;
1998 
1999 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
2000 		return -EFAULT;
2001 
2002 	memset(&data, 0, sizeof(data));
2003 
2004 	/* userspace wants to query CSR length */
2005 	if (!input.address || !input.length)
2006 		goto cmd;
2007 
2008 	/* allocate a physically contiguous buffer to store the CSR blob */
2009 	input_address = (void __user *)input.address;
2010 	if (input.length > SEV_FW_BLOB_MAX_SIZE)
2011 		return -EFAULT;
2012 
2013 	blob = kzalloc(input.length, GFP_KERNEL);
2014 	if (!blob)
2015 		return -ENOMEM;
2016 
2017 	data.address = __psp_pa(blob);
2018 	data.len = input.length;
2019 
2020 cmd:
2021 	if (sev->sev_plat_status.state == SEV_STATE_UNINIT) {
2022 		ret = sev_move_to_init_state(argp, &shutdown_required);
2023 		if (ret)
2024 			goto e_free_blob;
2025 	}
2026 
2027 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CSR, &data, &argp->error);
2028 
2029 	/*
2030 	 * Firmware will returns the length of the CSR blob (either the minimum
2031 	 * required length or the actual length written), return it to the user.
2032 	 */
2033 	input.length = data.len;
2034 
2035 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
2036 		ret = -EFAULT;
2037 		goto e_free_blob;
2038 	}
2039 
2040 	if (ret || WARN_ON_ONCE(argp->error))
2041 		goto e_free_blob;
2042 
2043 	if (blob) {
2044 		if (copy_to_user(input_address, blob, input.length))
2045 			ret = -EFAULT;
2046 	}
2047 
2048 e_free_blob:
2049 	if (shutdown_required)
2050 		__sev_firmware_shutdown(sev, false);
2051 
2052 	kfree(blob);
2053 	return ret;
2054 }
2055 
2056 void *psp_copy_user_blob(u64 uaddr, u32 len)
2057 {
2058 	if (!uaddr || !len)
2059 		return ERR_PTR(-EINVAL);
2060 
2061 	/* verify that blob length does not exceed our limit */
2062 	if (len > SEV_FW_BLOB_MAX_SIZE)
2063 		return ERR_PTR(-EINVAL);
2064 
2065 	return memdup_user((void __user *)uaddr, len);
2066 }
2067 EXPORT_SYMBOL_GPL(psp_copy_user_blob);
2068 
2069 static int sev_get_api_version(void)
2070 {
2071 	struct sev_device *sev = psp_master->sev_data;
2072 	struct sev_user_data_status status;
2073 	int error = 0, ret;
2074 
2075 	/*
2076 	 * Cache SNP platform status and SNP feature information
2077 	 * if SNP is available.
2078 	 */
2079 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP)) {
2080 		ret = snp_get_platform_data(sev, &error);
2081 		if (ret)
2082 			return 1;
2083 	}
2084 
2085 	ret = sev_platform_status(&status, &error);
2086 	if (ret) {
2087 		dev_err(sev->dev,
2088 			"SEV: failed to get status. Error: %#x\n", error);
2089 		return 1;
2090 	}
2091 
2092 	/* Cache SEV platform status */
2093 	sev->sev_plat_status = status;
2094 
2095 	sev->api_major = status.api_major;
2096 	sev->api_minor = status.api_minor;
2097 	sev->build = status.build;
2098 
2099 	return 0;
2100 }
2101 
2102 static int sev_get_firmware(struct device *dev,
2103 			    const struct firmware **firmware)
2104 {
2105 	char fw_name_specific[SEV_FW_NAME_SIZE];
2106 	char fw_name_subset[SEV_FW_NAME_SIZE];
2107 
2108 	snprintf(fw_name_specific, sizeof(fw_name_specific),
2109 		 "amd/amd_sev_fam%.2xh_model%.2xh.sbin",
2110 		 boot_cpu_data.x86, boot_cpu_data.x86_model);
2111 
2112 	snprintf(fw_name_subset, sizeof(fw_name_subset),
2113 		 "amd/amd_sev_fam%.2xh_model%.1xxh.sbin",
2114 		 boot_cpu_data.x86, (boot_cpu_data.x86_model & 0xf0) >> 4);
2115 
2116 	/* Check for SEV FW for a particular model.
2117 	 * Ex. amd_sev_fam17h_model00h.sbin for Family 17h Model 00h
2118 	 *
2119 	 * or
2120 	 *
2121 	 * Check for SEV FW common to a subset of models.
2122 	 * Ex. amd_sev_fam17h_model0xh.sbin for
2123 	 *     Family 17h Model 00h -- Family 17h Model 0Fh
2124 	 *
2125 	 * or
2126 	 *
2127 	 * Fall-back to using generic name: sev.fw
2128 	 */
2129 	if ((firmware_request_nowarn(firmware, fw_name_specific, dev) >= 0) ||
2130 	    (firmware_request_nowarn(firmware, fw_name_subset, dev) >= 0) ||
2131 	    (firmware_request_nowarn(firmware, SEV_FW_FILE, dev) >= 0))
2132 		return 0;
2133 
2134 	return -ENOENT;
2135 }
2136 
2137 /* Don't fail if SEV FW couldn't be updated. Continue with existing SEV FW */
2138 static int sev_update_firmware(struct device *dev)
2139 {
2140 	struct sev_data_download_firmware data;
2141 	const struct firmware *firmware;
2142 	int ret, error, order;
2143 	struct page *p;
2144 	void *fw_blob;
2145 
2146 	if (!sev_version_greater_or_equal(0, 15)) {
2147 		dev_dbg(dev, "DOWNLOAD_FIRMWARE not supported\n");
2148 		return -1;
2149 	}
2150 
2151 	if (sev_get_firmware(dev, &firmware) == -ENOENT) {
2152 		dev_dbg(dev, "No SEV firmware file present\n");
2153 		return -1;
2154 	}
2155 
2156 	order = get_order(firmware->size);
2157 	p = alloc_pages(GFP_KERNEL, order);
2158 	if (!p) {
2159 		ret = -1;
2160 		goto fw_err;
2161 	}
2162 
2163 	/*
2164 	 * Copy firmware data to a kernel allocated contiguous
2165 	 * memory region.
2166 	 */
2167 	fw_blob = page_address(p);
2168 	memcpy(fw_blob, firmware->data, firmware->size);
2169 
2170 	data.address = __psp_pa(fw_blob);
2171 	data.len = firmware->size;
2172 
2173 	ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, &data, &error);
2174 
2175 	/*
2176 	 * A quirk for fixing the committed TCB version, when upgrading from
2177 	 * earlier firmware version than 1.50.
2178 	 */
2179 	if (!ret && !sev_version_greater_or_equal(1, 50))
2180 		ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, &data, &error);
2181 
2182 	if (ret)
2183 		dev_dbg(dev, "Failed to update SEV firmware: %#x\n", error);
2184 
2185 	__free_pages(p, order);
2186 
2187 fw_err:
2188 	release_firmware(firmware);
2189 
2190 	return ret;
2191 }
2192 
2193 static int __sev_snp_shutdown_locked(int *error, bool panic)
2194 {
2195 	struct psp_device *psp = psp_master;
2196 	struct sev_device *sev;
2197 	struct sev_data_snp_shutdown_ex data;
2198 	int ret;
2199 
2200 	if (!psp || !psp->sev_data)
2201 		return 0;
2202 
2203 	sev = psp->sev_data;
2204 
2205 	if (!sev->snp_initialized)
2206 		return 0;
2207 
2208 	memset(&data, 0, sizeof(data));
2209 	data.len = sizeof(data);
2210 	data.iommu_snp_shutdown = 1;
2211 	if (sev->snp_feat_info_0.ecx & SNP_X86_SHUTDOWN_SUPPORTED)
2212 		data.x86_snp_shutdown = 1;
2213 
2214 	/*
2215 	 * If invoked during panic handling, local interrupts are disabled
2216 	 * and all CPUs are stopped, so wbinvd_on_all_cpus() can't be called.
2217 	 * In that case, a wbinvd() is done on remote CPUs via the NMI
2218 	 * callback, so only a local wbinvd() is needed here.
2219 	 */
2220 	if (!panic)
2221 		wbinvd_on_all_cpus();
2222 	else
2223 		wbinvd();
2224 
2225 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data, error);
2226 	/* SHUTDOWN may require DF_FLUSH */
2227 	if (*error == SEV_RET_DFFLUSH_REQUIRED) {
2228 		int dfflush_error = SEV_RET_NO_FW_CALL;
2229 
2230 		ret = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, &dfflush_error);
2231 		if (ret) {
2232 			dev_err(sev->dev, "SEV-SNP DF_FLUSH failed, ret = %d, error = %#x\n",
2233 				ret, dfflush_error);
2234 			return ret;
2235 		}
2236 		/* reissue the shutdown command */
2237 		ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data,
2238 					  error);
2239 	}
2240 	if (ret) {
2241 		dev_err(sev->dev, "SEV-SNP firmware shutdown failed, rc %d, error %#x\n",
2242 			ret, *error);
2243 		return ret;
2244 	}
2245 
2246 	if (data.x86_snp_shutdown) {
2247 		if (!panic)
2248 			snp_shutdown();
2249 		snp_hv_fixed_pages_state_update(sev, ALLOCATED);
2250 	} else {
2251 		/*
2252 		 * SNP_SHUTDOWN_EX with IOMMU_SNP_SHUTDOWN set to 1 disables SNP
2253 		 * enforcement by the IOMMU and also transitions all pages
2254 		 * associated with the IOMMU to the Reclaim state.
2255 		 * Firmware was transitioning the IOMMU pages to Hypervisor state
2256 		 * before version 1.53. But, accounting for the number of assigned
2257 		 * 4kB pages in a 2M page was done incorrectly by not transitioning
2258 		 * to the Reclaim state. This resulted in RMP #PF when later accessing
2259 		 * the 2M page containing those pages during kexec boot. Hence, the
2260 		 * firmware now transitions these pages to Reclaim state and hypervisor
2261 		 * needs to transition these pages to shared state. SNP Firmware
2262 		 * version 1.53 and above are needed for kexec boot.
2263 		 */
2264 		ret = amd_iommu_snp_disable();
2265 		if (ret) {
2266 			dev_err(sev->dev, "SNP IOMMU shutdown failed\n");
2267 			return ret;
2268 		}
2269 	}
2270 
2271 	snp_leak_hv_fixed_pages();
2272 	sev->snp_initialized = false;
2273 	dev_dbg(sev->dev, "SEV-SNP firmware shutdown\n");
2274 
2275 	/*
2276 	 * __sev_snp_shutdown_locked() deadlocks when it tries to unregister
2277 	 * itself during panic as the panic notifier is called with RCU read
2278 	 * lock held and notifier unregistration does RCU synchronization.
2279 	 */
2280 	if (!panic)
2281 		atomic_notifier_chain_unregister(&panic_notifier_list,
2282 						 &snp_panic_notifier);
2283 
2284 	/* Reset TMR size back to default */
2285 	sev_es_tmr_size = SEV_TMR_SIZE;
2286 
2287 	return ret;
2288 }
2289 
2290 static int sev_ioctl_do_pek_import(struct sev_issue_cmd *argp, bool writable)
2291 {
2292 	struct sev_device *sev = psp_master->sev_data;
2293 	struct sev_user_data_pek_cert_import input;
2294 	struct sev_data_pek_cert_import data;
2295 	bool shutdown_required = false;
2296 	void *pek_blob, *oca_blob;
2297 	int ret;
2298 
2299 	if (!writable)
2300 		return -EPERM;
2301 
2302 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
2303 		return -EFAULT;
2304 
2305 	/* copy PEK certificate blobs from userspace */
2306 	pek_blob = psp_copy_user_blob(input.pek_cert_address, input.pek_cert_len);
2307 	if (IS_ERR(pek_blob))
2308 		return PTR_ERR(pek_blob);
2309 
2310 	data.reserved = 0;
2311 	data.pek_cert_address = __psp_pa(pek_blob);
2312 	data.pek_cert_len = input.pek_cert_len;
2313 
2314 	/* copy PEK certificate blobs from userspace */
2315 	oca_blob = psp_copy_user_blob(input.oca_cert_address, input.oca_cert_len);
2316 	if (IS_ERR(oca_blob)) {
2317 		ret = PTR_ERR(oca_blob);
2318 		goto e_free_pek;
2319 	}
2320 
2321 	data.oca_cert_address = __psp_pa(oca_blob);
2322 	data.oca_cert_len = input.oca_cert_len;
2323 
2324 	/* If platform is not in INIT state then transition it to INIT */
2325 	if (sev->sev_plat_status.state != SEV_STATE_INIT) {
2326 		ret = sev_move_to_init_state(argp, &shutdown_required);
2327 		if (ret)
2328 			goto e_free_oca;
2329 	}
2330 
2331 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CERT_IMPORT, &data, &argp->error);
2332 
2333 e_free_oca:
2334 	if (shutdown_required)
2335 		__sev_firmware_shutdown(sev, false);
2336 
2337 	kfree(oca_blob);
2338 e_free_pek:
2339 	kfree(pek_blob);
2340 	return ret;
2341 }
2342 
2343 static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp)
2344 {
2345 	struct sev_user_data_get_id2 input;
2346 	struct sev_data_get_id data;
2347 	void __user *input_address;
2348 	void *id_blob = NULL;
2349 	int ret;
2350 
2351 	/* SEV GET_ID is available from SEV API v0.16 and up */
2352 	if (!sev_version_greater_or_equal(0, 16))
2353 		return -ENOTSUPP;
2354 
2355 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
2356 		return -EFAULT;
2357 
2358 	input_address = (void __user *)input.address;
2359 
2360 	if (input.address && input.length) {
2361 		/*
2362 		 * The length of the ID shouldn't be assumed by software since
2363 		 * it may change in the future.  The allocation size is limited
2364 		 * to 1 << (PAGE_SHIFT + MAX_PAGE_ORDER) by the page allocator.
2365 		 * If the allocation fails, simply return ENOMEM rather than
2366 		 * warning in the kernel log.
2367 		 */
2368 		id_blob = kzalloc(input.length, GFP_KERNEL | __GFP_NOWARN);
2369 		if (!id_blob)
2370 			return -ENOMEM;
2371 
2372 		data.address = __psp_pa(id_blob);
2373 		data.len = input.length;
2374 	} else {
2375 		data.address = 0;
2376 		data.len = 0;
2377 	}
2378 
2379 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, &data, &argp->error);
2380 
2381 	/*
2382 	 * Firmware will return the length of the ID value (either the minimum
2383 	 * required length or the actual length written), return it to the user.
2384 	 */
2385 	input.length = data.len;
2386 
2387 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
2388 		ret = -EFAULT;
2389 		goto e_free;
2390 	}
2391 
2392 	if (ret || WARN_ON_ONCE(argp->error))
2393 		goto e_free;
2394 
2395 	if (id_blob) {
2396 		if (copy_to_user(input_address, id_blob, data.len)) {
2397 			ret = -EFAULT;
2398 			goto e_free;
2399 		}
2400 	}
2401 
2402 e_free:
2403 	kfree(id_blob);
2404 
2405 	return ret;
2406 }
2407 
2408 static int sev_ioctl_do_get_id(struct sev_issue_cmd *argp)
2409 {
2410 	struct sev_data_get_id *data;
2411 	u64 data_size, user_size;
2412 	void *id_blob, *mem;
2413 	int ret;
2414 
2415 	/* SEV GET_ID available from SEV API v0.16 and up */
2416 	if (!sev_version_greater_or_equal(0, 16))
2417 		return -ENOTSUPP;
2418 
2419 	/* SEV FW expects the buffer it fills with the ID to be
2420 	 * 8-byte aligned. Memory allocated should be enough to
2421 	 * hold data structure + alignment padding + memory
2422 	 * where SEV FW writes the ID.
2423 	 */
2424 	data_size = ALIGN(sizeof(struct sev_data_get_id), 8);
2425 	user_size = sizeof(struct sev_user_data_get_id);
2426 
2427 	mem = kzalloc(data_size + user_size, GFP_KERNEL);
2428 	if (!mem)
2429 		return -ENOMEM;
2430 
2431 	data = mem;
2432 	id_blob = mem + data_size;
2433 
2434 	data->address = __psp_pa(id_blob);
2435 	data->len = user_size;
2436 
2437 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, data, &argp->error);
2438 	if (!ret) {
2439 		if (copy_to_user((void __user *)argp->data, id_blob, data->len))
2440 			ret = -EFAULT;
2441 	}
2442 
2443 	kfree(mem);
2444 
2445 	return ret;
2446 }
2447 
2448 static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable)
2449 {
2450 	struct sev_device *sev = psp_master->sev_data;
2451 	struct sev_user_data_pdh_cert_export input;
2452 	void *pdh_blob = NULL, *cert_blob = NULL;
2453 	struct sev_data_pdh_cert_export data;
2454 	void __user *input_cert_chain_address;
2455 	void __user *input_pdh_cert_address;
2456 	bool shutdown_required = false;
2457 	int ret;
2458 
2459 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
2460 		return -EFAULT;
2461 
2462 	memset(&data, 0, sizeof(data));
2463 
2464 	input_pdh_cert_address = (void __user *)input.pdh_cert_address;
2465 	input_cert_chain_address = (void __user *)input.cert_chain_address;
2466 
2467 	/* Userspace wants to query the certificate length. */
2468 	if (!input.pdh_cert_address ||
2469 	    !input.pdh_cert_len ||
2470 	    !input.cert_chain_address ||
2471 	    !input.cert_chain_len)
2472 		goto cmd;
2473 
2474 	/* Allocate a physically contiguous buffer to store the PDH blob. */
2475 	if (input.pdh_cert_len > SEV_FW_BLOB_MAX_SIZE)
2476 		return -EFAULT;
2477 
2478 	/* Allocate a physically contiguous buffer to store the cert chain blob. */
2479 	if (input.cert_chain_len > SEV_FW_BLOB_MAX_SIZE)
2480 		return -EFAULT;
2481 
2482 	pdh_blob = kzalloc(input.pdh_cert_len, GFP_KERNEL);
2483 	if (!pdh_blob)
2484 		return -ENOMEM;
2485 
2486 	data.pdh_cert_address = __psp_pa(pdh_blob);
2487 	data.pdh_cert_len = input.pdh_cert_len;
2488 
2489 	cert_blob = kzalloc(input.cert_chain_len, GFP_KERNEL);
2490 	if (!cert_blob) {
2491 		ret = -ENOMEM;
2492 		goto e_free_pdh;
2493 	}
2494 
2495 	data.cert_chain_address = __psp_pa(cert_blob);
2496 	data.cert_chain_len = input.cert_chain_len;
2497 
2498 cmd:
2499 	/* If platform is not in INIT state then transition it to INIT. */
2500 	if (sev->sev_plat_status.state != SEV_STATE_INIT) {
2501 		if (!writable) {
2502 			ret = -EPERM;
2503 			goto e_free_cert;
2504 		}
2505 		ret = sev_move_to_init_state(argp, &shutdown_required);
2506 		if (ret)
2507 			goto e_free_cert;
2508 	}
2509 
2510 	ret = __sev_do_cmd_locked(SEV_CMD_PDH_CERT_EXPORT, &data, &argp->error);
2511 
2512 	/*
2513 	 * Firmware will return the length of the blobs (either the minimum
2514 	 * required length or the actual length written), return 'em to the user.
2515 	 */
2516 	input.cert_chain_len = data.cert_chain_len;
2517 	input.pdh_cert_len = data.pdh_cert_len;
2518 
2519 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
2520 		ret = -EFAULT;
2521 		goto e_free_cert;
2522 	}
2523 
2524 	if (ret || WARN_ON_ONCE(argp->error))
2525 		goto e_free_cert;
2526 
2527 	if (pdh_blob) {
2528 		if (copy_to_user(input_pdh_cert_address,
2529 				 pdh_blob, input.pdh_cert_len)) {
2530 			ret = -EFAULT;
2531 			goto e_free_cert;
2532 		}
2533 	}
2534 
2535 	if (cert_blob) {
2536 		if (copy_to_user(input_cert_chain_address,
2537 				 cert_blob, input.cert_chain_len))
2538 			ret = -EFAULT;
2539 	}
2540 
2541 e_free_cert:
2542 	if (shutdown_required)
2543 		__sev_firmware_shutdown(sev, false);
2544 
2545 	kfree(cert_blob);
2546 e_free_pdh:
2547 	kfree(pdh_blob);
2548 	return ret;
2549 }
2550 
2551 static int __sev_do_snp_platform_status(struct sev_user_data_snp_status *status,
2552 					int *error)
2553 {
2554 	struct sev_device *sev = psp_master->sev_data;
2555 	struct sev_data_snp_addr buf;
2556 	struct page *status_page;
2557 	void *data;
2558 	int ret;
2559 
2560 	status_page = alloc_page(GFP_KERNEL_ACCOUNT);
2561 	if (!status_page)
2562 		return -ENOMEM;
2563 
2564 	data = page_address(status_page);
2565 
2566 	/*
2567 	 * SNP_PLATFORM_STATUS can be executed in any SNP state. But if executed
2568 	 * when SNP has been initialized, the status page must be firmware-owned.
2569 	 */
2570 	if (sev->snp_initialized) {
2571 		/*
2572 		 * Firmware expects the status page to be in Firmware state,
2573 		 * otherwise it will report an error INVALID_PAGE_STATE.
2574 		 */
2575 		if (rmp_mark_pages_firmware(__pa(data), 1, true)) {
2576 			ret = -EFAULT;
2577 			goto cleanup;
2578 		}
2579 	}
2580 
2581 	buf.address = __psp_pa(data);
2582 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_PLATFORM_STATUS, &buf, error);
2583 
2584 	if (sev->snp_initialized) {
2585 		/*
2586 		 * The status page will be in Reclaim state on success, or left
2587 		 * in Firmware state on failure. Use snp_reclaim_pages() to
2588 		 * transition either case back to Hypervisor-owned state.
2589 		 */
2590 		if (snp_reclaim_pages(__pa(data), 1, true))
2591 			return -EFAULT;
2592 	}
2593 
2594 	if (ret)
2595 		goto cleanup;
2596 
2597 	memcpy(status, data, sizeof(*status));
2598 
2599 cleanup:
2600 	__free_pages(status_page, 0);
2601 	return ret;
2602 }
2603 
2604 static int sev_ioctl_do_snp_platform_status(struct sev_issue_cmd *argp)
2605 {
2606 	struct sev_user_data_snp_status status;
2607 	int ret;
2608 
2609 	if (!argp->data)
2610 		return -EINVAL;
2611 
2612 	ret = __sev_do_snp_platform_status(&status, &argp->error);
2613 	if (ret < 0)
2614 		return ret;
2615 
2616 	if (copy_to_user((void __user *)argp->data, &status,
2617 			 sizeof(struct sev_user_data_snp_status)))
2618 		ret = -EFAULT;
2619 
2620 	return ret;
2621 }
2622 
2623 static int sev_ioctl_do_snp_commit(struct sev_issue_cmd *argp)
2624 {
2625 	struct sev_data_snp_commit buf;
2626 	int ret;
2627 
2628 	buf.len = sizeof(buf);
2629 
2630 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_COMMIT, &buf, &argp->error);
2631 
2632 	return ret;
2633 }
2634 
2635 static int sev_ioctl_do_snp_set_config(struct sev_issue_cmd *argp, bool writable)
2636 {
2637 	struct sev_device *sev = psp_master->sev_data;
2638 	struct sev_user_data_snp_config config;
2639 
2640 	if (!argp->data)
2641 		return -EINVAL;
2642 
2643 	if (!writable)
2644 		return -EPERM;
2645 
2646 	if (!sev->snp_initialized)
2647 		return -ENODEV;
2648 
2649 	if (copy_from_user(&config, (void __user *)argp->data, sizeof(config)))
2650 		return -EFAULT;
2651 
2652 	return __sev_do_cmd_locked(SEV_CMD_SNP_CONFIG, &config, &argp->error);
2653 }
2654 
2655 static int sev_ioctl_do_snp_vlek_load(struct sev_issue_cmd *argp, bool writable)
2656 {
2657 	struct sev_device *sev = psp_master->sev_data;
2658 	struct sev_user_data_snp_vlek_load input;
2659 	void *blob;
2660 	int ret;
2661 
2662 	if (!argp->data)
2663 		return -EINVAL;
2664 
2665 	if (!writable)
2666 		return -EPERM;
2667 
2668 	if (!sev->snp_initialized)
2669 		return -ENODEV;
2670 
2671 	if (copy_from_user(&input, u64_to_user_ptr(argp->data), sizeof(input)))
2672 		return -EFAULT;
2673 
2674 	if (input.len != sizeof(input) || input.vlek_wrapped_version != 0)
2675 		return -EINVAL;
2676 
2677 	blob = psp_copy_user_blob(input.vlek_wrapped_address,
2678 				  sizeof(struct sev_user_data_snp_wrapped_vlek_hashstick));
2679 	if (IS_ERR(blob))
2680 		return PTR_ERR(blob);
2681 
2682 	input.vlek_wrapped_address = __psp_pa(blob);
2683 
2684 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_VLEK_LOAD, &input, &argp->error);
2685 	kfree(blob);
2686 
2687 	return ret;
2688 }
2689 
2690 static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)
2691 {
2692 	void __user *argp = (void __user *)arg;
2693 	struct sev_issue_cmd input;
2694 	int ret = -EFAULT;
2695 	bool writable = file->f_mode & FMODE_WRITE;
2696 
2697 	if (!psp_master || !psp_master->sev_data)
2698 		return -ENODEV;
2699 
2700 	if (ioctl != SEV_ISSUE_CMD)
2701 		return -EINVAL;
2702 
2703 	if (copy_from_user(&input, argp, sizeof(struct sev_issue_cmd)))
2704 		return -EFAULT;
2705 
2706 	if (input.cmd > SEV_MAX)
2707 		return -EINVAL;
2708 
2709 	mutex_lock(&sev_cmd_mutex);
2710 
2711 	switch (input.cmd) {
2712 
2713 	case SEV_FACTORY_RESET:
2714 		ret = sev_ioctl_do_reset(&input, writable);
2715 		break;
2716 	case SEV_PLATFORM_STATUS:
2717 		ret = sev_ioctl_do_platform_status(&input);
2718 		break;
2719 	case SEV_PEK_GEN:
2720 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PEK_GEN, &input, writable);
2721 		break;
2722 	case SEV_PDH_GEN:
2723 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PDH_GEN, &input, writable);
2724 		break;
2725 	case SEV_PEK_CSR:
2726 		ret = sev_ioctl_do_pek_csr(&input, writable);
2727 		break;
2728 	case SEV_PEK_CERT_IMPORT:
2729 		ret = sev_ioctl_do_pek_import(&input, writable);
2730 		break;
2731 	case SEV_PDH_CERT_EXPORT:
2732 		ret = sev_ioctl_do_pdh_export(&input, writable);
2733 		break;
2734 	case SEV_GET_ID:
2735 		pr_warn_once("SEV_GET_ID command is deprecated, use SEV_GET_ID2\n");
2736 		ret = sev_ioctl_do_get_id(&input);
2737 		break;
2738 	case SEV_GET_ID2:
2739 		ret = sev_ioctl_do_get_id2(&input);
2740 		break;
2741 	case SNP_PLATFORM_STATUS:
2742 		ret = sev_ioctl_do_snp_platform_status(&input);
2743 		break;
2744 	case SNP_COMMIT:
2745 		ret = sev_ioctl_do_snp_commit(&input);
2746 		break;
2747 	case SNP_SET_CONFIG:
2748 		ret = sev_ioctl_do_snp_set_config(&input, writable);
2749 		break;
2750 	case SNP_VLEK_LOAD:
2751 		ret = sev_ioctl_do_snp_vlek_load(&input, writable);
2752 		break;
2753 	default:
2754 		ret = -EINVAL;
2755 		goto out;
2756 	}
2757 
2758 	if (copy_to_user(argp, &input, sizeof(struct sev_issue_cmd)))
2759 		ret = -EFAULT;
2760 out:
2761 	mutex_unlock(&sev_cmd_mutex);
2762 
2763 	return ret;
2764 }
2765 
2766 static const struct file_operations sev_fops = {
2767 	.owner	= THIS_MODULE,
2768 	.unlocked_ioctl = sev_ioctl,
2769 };
2770 
2771 int sev_platform_status(struct sev_user_data_status *data, int *error)
2772 {
2773 	return sev_do_cmd(SEV_CMD_PLATFORM_STATUS, data, error);
2774 }
2775 EXPORT_SYMBOL_GPL(sev_platform_status);
2776 
2777 int sev_guest_deactivate(struct sev_data_deactivate *data, int *error)
2778 {
2779 	return sev_do_cmd(SEV_CMD_DEACTIVATE, data, error);
2780 }
2781 EXPORT_SYMBOL_GPL(sev_guest_deactivate);
2782 
2783 int sev_guest_activate(struct sev_data_activate *data, int *error)
2784 {
2785 	return sev_do_cmd(SEV_CMD_ACTIVATE, data, error);
2786 }
2787 EXPORT_SYMBOL_GPL(sev_guest_activate);
2788 
2789 int sev_guest_decommission(struct sev_data_decommission *data, int *error)
2790 {
2791 	return sev_do_cmd(SEV_CMD_DECOMMISSION, data, error);
2792 }
2793 EXPORT_SYMBOL_GPL(sev_guest_decommission);
2794 
2795 int sev_guest_df_flush(int *error)
2796 {
2797 	return sev_do_cmd(SEV_CMD_DF_FLUSH, NULL, error);
2798 }
2799 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
2800 
2801 static void sev_exit(struct kref *ref)
2802 {
2803 	misc_deregister(&misc_dev->misc);
2804 	kfree(misc_dev);
2805 	misc_dev = NULL;
2806 }
2807 
2808 static int sev_misc_init(struct sev_device *sev)
2809 {
2810 	struct device *dev = sev->dev;
2811 	int ret;
2812 
2813 	/*
2814 	 * SEV feature support can be detected on multiple devices but the SEV
2815 	 * FW commands must be issued on the master. During probe, we do not
2816 	 * know the master hence we create /dev/sev on the first device probe.
2817 	 * sev_do_cmd() finds the right master device to which to issue the
2818 	 * command to the firmware.
2819 	 */
2820 	if (!misc_dev) {
2821 		struct miscdevice *misc;
2822 
2823 		misc_dev = kzalloc_obj(*misc_dev);
2824 		if (!misc_dev)
2825 			return -ENOMEM;
2826 
2827 		misc = &misc_dev->misc;
2828 		misc->minor = MISC_DYNAMIC_MINOR;
2829 		misc->name = DEVICE_NAME;
2830 		misc->fops = &sev_fops;
2831 
2832 		ret = misc_register(misc);
2833 		if (ret)
2834 			return ret;
2835 
2836 		kref_init(&misc_dev->refcount);
2837 	} else {
2838 		kref_get(&misc_dev->refcount);
2839 	}
2840 
2841 	init_waitqueue_head(&sev->int_queue);
2842 	sev->misc = misc_dev;
2843 	dev_dbg(dev, "registered SEV device\n");
2844 
2845 	return 0;
2846 }
2847 
2848 int sev_dev_init(struct psp_device *psp)
2849 {
2850 	struct device *dev = psp->dev;
2851 	struct sev_device *sev;
2852 	int ret = -ENOMEM;
2853 
2854 	if (!boot_cpu_has(X86_FEATURE_SEV)) {
2855 		dev_info_once(dev, "SEV: memory encryption not enabled by BIOS\n");
2856 		return 0;
2857 	}
2858 
2859 	sev = devm_kzalloc(dev, sizeof(*sev), GFP_KERNEL);
2860 	if (!sev)
2861 		goto e_err;
2862 
2863 	sev->cmd_buf = (void *)devm_get_free_pages(dev, GFP_KERNEL, 1);
2864 	if (!sev->cmd_buf)
2865 		goto e_sev;
2866 
2867 	sev->cmd_buf_backup = (uint8_t *)sev->cmd_buf + PAGE_SIZE;
2868 
2869 	psp->sev_data = sev;
2870 
2871 	sev->dev = dev;
2872 	sev->psp = psp;
2873 
2874 	sev->io_regs = psp->io_regs;
2875 
2876 	sev->vdata = (struct sev_vdata *)psp->vdata->sev;
2877 	if (!sev->vdata) {
2878 		ret = -ENODEV;
2879 		dev_err(dev, "sev: missing driver data\n");
2880 		goto e_buf;
2881 	}
2882 
2883 	psp_set_sev_irq_handler(psp, sev_irq_handler, sev);
2884 
2885 	ret = sev_misc_init(sev);
2886 	if (ret)
2887 		goto e_irq;
2888 
2889 	dev_notice(dev, "sev enabled\n");
2890 
2891 	return 0;
2892 
2893 e_irq:
2894 	psp_clear_sev_irq_handler(psp);
2895 e_buf:
2896 	devm_free_pages(dev, (unsigned long)sev->cmd_buf);
2897 e_sev:
2898 	devm_kfree(dev, sev);
2899 e_err:
2900 	psp->sev_data = NULL;
2901 
2902 	dev_notice(dev, "sev initialization failed\n");
2903 
2904 	return ret;
2905 }
2906 
2907 static void __sev_firmware_shutdown(struct sev_device *sev, bool panic)
2908 {
2909 	int error;
2910 
2911 	__sev_platform_shutdown_locked(&error);
2912 
2913 	if (sev_es_tmr) {
2914 		/*
2915 		 * The TMR area was encrypted, flush it from the cache.
2916 		 *
2917 		 * If invoked during panic handling, local interrupts are
2918 		 * disabled and all CPUs are stopped, so wbinvd_on_all_cpus()
2919 		 * can't be used. In that case, wbinvd() is done on remote CPUs
2920 		 * via the NMI callback, and done for this CPU later during
2921 		 * SNP shutdown, so wbinvd_on_all_cpus() can be skipped.
2922 		 */
2923 		if (!panic)
2924 			wbinvd_on_all_cpus();
2925 
2926 		__snp_free_firmware_pages(virt_to_page(sev_es_tmr),
2927 					  get_order(sev_es_tmr_size),
2928 					  true);
2929 		sev_es_tmr = NULL;
2930 	}
2931 
2932 	if (sev_init_ex_buffer) {
2933 		__snp_free_firmware_pages(virt_to_page(sev_init_ex_buffer),
2934 					  get_order(NV_LENGTH),
2935 					  true);
2936 		sev_init_ex_buffer = NULL;
2937 	}
2938 
2939 	__sev_snp_shutdown_locked(&error, panic);
2940 }
2941 
2942 static void sev_firmware_shutdown(struct sev_device *sev)
2943 {
2944 	/*
2945 	 * Calling without sev_cmd_mutex held as TSM will likely try disconnecting
2946 	 * IDE and this ends up calling sev_do_cmd() which locks sev_cmd_mutex.
2947 	 */
2948 	if (sev->tio_status)
2949 		sev_tsm_uninit(sev);
2950 
2951 	/*
2952 	 * Remove the sysfs interface before taking the sev_cmd_mutex.
2953 	 * sysfs_remove_group() waits for in-flight _show()/_store() handlers
2954 	 * to drain, and those handlers issue SNP_VERIFY_MITIGATION via
2955 	 * sev_do_cmd() which acquires the sev_cmd_mutex. Removing the group
2956 	 * while holding the mutex could therefore deadlock.
2957 	 */
2958 	sev_snp_unregister_verify_mitigation(sev);
2959 
2960 	mutex_lock(&sev_cmd_mutex);
2961 
2962 	__sev_firmware_shutdown(sev, false);
2963 
2964 	kfree(sev->tio_status);
2965 	sev->tio_status = NULL;
2966 
2967 	mutex_unlock(&sev_cmd_mutex);
2968 }
2969 
2970 void sev_platform_shutdown(void)
2971 {
2972 	if (!psp_master || !psp_master->sev_data)
2973 		return;
2974 
2975 	sev_firmware_shutdown(psp_master->sev_data);
2976 }
2977 EXPORT_SYMBOL_GPL(sev_platform_shutdown);
2978 
2979 u64 sev_get_snp_policy_bits(void)
2980 {
2981 	struct psp_device *psp = psp_master;
2982 	struct sev_device *sev;
2983 	u64 policy_bits;
2984 
2985 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
2986 		return 0;
2987 
2988 	if (!psp || !psp->sev_data)
2989 		return 0;
2990 
2991 	sev = psp->sev_data;
2992 
2993 	policy_bits = SNP_POLICY_MASK_BASE;
2994 
2995 	if (sev->snp_plat_status.feature_info) {
2996 		if (sev->snp_feat_info_0.ecx & SNP_RAPL_DISABLE_SUPPORTED)
2997 			policy_bits |= SNP_POLICY_MASK_RAPL_DIS;
2998 
2999 		if (sev->snp_feat_info_0.ecx & SNP_CIPHER_TEXT_HIDING_SUPPORTED)
3000 			policy_bits |= SNP_POLICY_MASK_CIPHERTEXT_HIDING_DRAM;
3001 
3002 		if (sev->snp_feat_info_0.ecx & SNP_AES_256_XTS_POLICY_SUPPORTED)
3003 			policy_bits |= SNP_POLICY_MASK_MEM_AES_256_XTS;
3004 
3005 		if (sev->snp_feat_info_0.ecx & SNP_CXL_ALLOW_POLICY_SUPPORTED)
3006 			policy_bits |= SNP_POLICY_MASK_CXL_ALLOW;
3007 
3008 		if (sev_version_greater_or_equal(1, 58))
3009 			policy_bits |= SNP_POLICY_MASK_PAGE_SWAP_DISABLE;
3010 	}
3011 
3012 	return policy_bits;
3013 }
3014 EXPORT_SYMBOL_GPL(sev_get_snp_policy_bits);
3015 
3016 void sev_dev_destroy(struct psp_device *psp)
3017 {
3018 	struct sev_device *sev = psp->sev_data;
3019 
3020 	if (!sev)
3021 		return;
3022 
3023 	sev_firmware_shutdown(sev);
3024 
3025 	if (sev->misc)
3026 		kref_put(&misc_dev->refcount, sev_exit);
3027 
3028 	psp_clear_sev_irq_handler(psp);
3029 }
3030 
3031 static int snp_shutdown_on_panic(struct notifier_block *nb,
3032 				 unsigned long reason, void *arg)
3033 {
3034 	struct sev_device *sev = psp_master->sev_data;
3035 
3036 	/*
3037 	 * If sev_cmd_mutex is already acquired, then it's likely
3038 	 * another PSP command is in flight and issuing a shutdown
3039 	 * would fail in unexpected ways. Rather than create even
3040 	 * more confusion during a panic, just bail out here.
3041 	 */
3042 	if (mutex_is_locked(&sev_cmd_mutex))
3043 		return NOTIFY_DONE;
3044 
3045 	__sev_firmware_shutdown(sev, true);
3046 
3047 	return NOTIFY_DONE;
3048 }
3049 
3050 int sev_issue_cmd_external_user(struct file *filep, unsigned int cmd,
3051 				void *data, int *error)
3052 {
3053 	if (!filep || filep->f_op != &sev_fops)
3054 		return -EBADF;
3055 
3056 	return sev_do_cmd(cmd, data, error);
3057 }
3058 EXPORT_SYMBOL_GPL(sev_issue_cmd_external_user);
3059 
3060 void sev_pci_init(void)
3061 {
3062 	struct sev_device *sev = psp_master->sev_data;
3063 	u8 api_major, api_minor, build;
3064 
3065 	if (!sev)
3066 		return;
3067 
3068 	psp_timeout = psp_probe_timeout;
3069 
3070 	if (sev_get_api_version())
3071 		goto err;
3072 
3073 	api_major = sev->api_major;
3074 	api_minor = sev->api_minor;
3075 	build     = sev->build;
3076 
3077 	if (sev_update_firmware(sev->dev) == 0)
3078 		sev_get_api_version();
3079 
3080 	if (api_major != sev->api_major || api_minor != sev->api_minor ||
3081 	    build != sev->build)
3082 		dev_info(sev->dev, "SEV firmware updated from %d.%d.%d to %d.%d.%d\n",
3083 			 api_major, api_minor, build,
3084 			 sev->api_major, sev->api_minor, sev->build);
3085 
3086 	return;
3087 
3088 err:
3089 	sev_dev_destroy(psp_master);
3090 
3091 	psp_master->sev_data = NULL;
3092 }
3093 
3094 void sev_pci_exit(void)
3095 {
3096 	struct sev_device *sev = psp_master->sev_data;
3097 
3098 	if (!sev)
3099 		return;
3100 
3101 	sev_firmware_shutdown(sev);
3102 }
3103 
3104 static int get_v1_svn(struct sev_device *sev)
3105 {
3106 	struct sev_snp_tcb_version_genoa_milan *tcb;
3107 	struct sev_user_data_snp_status status;
3108 	int ret, error = 0;
3109 
3110 	mutex_lock(&sev_cmd_mutex);
3111 	ret = __sev_do_snp_platform_status(&status, &error);
3112 	mutex_unlock(&sev_cmd_mutex);
3113 	if (ret < 0)
3114 		return ret;
3115 
3116 	tcb = (struct sev_snp_tcb_version_genoa_milan *)&status
3117 		      .current_tcb_version;
3118 	return tcb->snp;
3119 }
3120 
3121 static int get_v2_svn(struct sev_device *sev)
3122 {
3123 	struct sev_user_data_snp_status status;
3124 	struct sev_snp_tcb_version_turin *tcb;
3125 	int ret, error = 0;
3126 
3127 	mutex_lock(&sev_cmd_mutex);
3128 	ret = __sev_do_snp_platform_status(&status, &error);
3129 	mutex_unlock(&sev_cmd_mutex);
3130 	if (ret < 0)
3131 		return ret;
3132 
3133 	tcb = (struct sev_snp_tcb_version_turin *)&status
3134 		      .current_tcb_version;
3135 	return tcb->snp;
3136 }
3137 
3138 static bool sev_firmware_allows_es(struct sev_device *sev)
3139 {
3140 	/* Documented in AMD-SB-3023 */
3141 	if (boot_cpu_has(X86_FEATURE_ZEN4) || boot_cpu_has(X86_FEATURE_ZEN3))
3142 		return get_v1_svn(sev) < 0x1b;
3143 	else if (boot_cpu_has(X86_FEATURE_ZEN5))
3144 		return get_v2_svn(sev) < 0x4;
3145 	else
3146 		return true;
3147 }
3148 
3149 int sev_firmware_supported_vm_types(void)
3150 {
3151 	int supported_vm_types = 0;
3152 	struct sev_device *sev;
3153 
3154 	if (!psp_master || !psp_master->sev_data)
3155 		return supported_vm_types;
3156 	sev = psp_master->sev_data;
3157 
3158 	supported_vm_types |= BIT(KVM_X86_SEV_VM);
3159 	supported_vm_types |= BIT(KVM_X86_SEV_ES_VM);
3160 
3161 	if (!sev->snp_initialized)
3162 		return supported_vm_types;
3163 
3164 	supported_vm_types |= BIT(KVM_X86_SNP_VM);
3165 
3166 	if (!sev_firmware_allows_es(sev))
3167 		supported_vm_types &= ~BIT(KVM_X86_SEV_ES_VM);
3168 
3169 	return supported_vm_types;
3170 
3171 }
3172 EXPORT_SYMBOL_FOR_MODULES(sev_firmware_supported_vm_types, "kvm-amd");
3173