xref: /linux/drivers/crypto/ccp/sev-dev.c (revision 36ec807b627b4c0a0a382f0ae48eac7187d14b2b)
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 
32 #include <asm/smp.h>
33 #include <asm/cacheflush.h>
34 #include <asm/e820/types.h>
35 #include <asm/sev.h>
36 
37 #include "psp-dev.h"
38 #include "sev-dev.h"
39 
40 #define DEVICE_NAME		"sev"
41 #define SEV_FW_FILE		"amd/sev.fw"
42 #define SEV_FW_NAME_SIZE	64
43 
44 /* Minimum firmware version required for the SEV-SNP support */
45 #define SNP_MIN_API_MAJOR	1
46 #define SNP_MIN_API_MINOR	51
47 
48 /*
49  * Maximum number of firmware-writable buffers that might be specified
50  * in the parameters of a legacy SEV command buffer.
51  */
52 #define CMD_BUF_FW_WRITABLE_MAX 2
53 
54 /* Leave room in the descriptor array for an end-of-list indicator. */
55 #define CMD_BUF_DESC_MAX (CMD_BUF_FW_WRITABLE_MAX + 1)
56 
57 static DEFINE_MUTEX(sev_cmd_mutex);
58 static struct sev_misc_dev *misc_dev;
59 
60 static int psp_cmd_timeout = 100;
61 module_param(psp_cmd_timeout, int, 0644);
62 MODULE_PARM_DESC(psp_cmd_timeout, " default timeout value, in seconds, for PSP commands");
63 
64 static int psp_probe_timeout = 5;
65 module_param(psp_probe_timeout, int, 0644);
66 MODULE_PARM_DESC(psp_probe_timeout, " default timeout value, in seconds, during PSP device probe");
67 
68 static char *init_ex_path;
69 module_param(init_ex_path, charp, 0444);
70 MODULE_PARM_DESC(init_ex_path, " Path for INIT_EX data; if set try INIT_EX");
71 
72 static bool psp_init_on_probe = true;
73 module_param(psp_init_on_probe, bool, 0444);
74 MODULE_PARM_DESC(psp_init_on_probe, "  if true, the PSP will be initialized on module init. Else the PSP will be initialized on the first command requiring it");
75 
76 MODULE_FIRMWARE("amd/amd_sev_fam17h_model0xh.sbin"); /* 1st gen EPYC */
77 MODULE_FIRMWARE("amd/amd_sev_fam17h_model3xh.sbin"); /* 2nd gen EPYC */
78 MODULE_FIRMWARE("amd/amd_sev_fam19h_model0xh.sbin"); /* 3rd gen EPYC */
79 MODULE_FIRMWARE("amd/amd_sev_fam19h_model1xh.sbin"); /* 4th gen EPYC */
80 
81 static bool psp_dead;
82 static int psp_timeout;
83 
84 /* Trusted Memory Region (TMR):
85  *   The TMR is a 1MB area that must be 1MB aligned.  Use the page allocator
86  *   to allocate the memory, which will return aligned memory for the specified
87  *   allocation order.
88  *
89  * When SEV-SNP is enabled the TMR needs to be 2MB aligned and 2MB sized.
90  */
91 #define SEV_TMR_SIZE		(1024 * 1024)
92 #define SNP_TMR_SIZE		(2 * 1024 * 1024)
93 
94 static void *sev_es_tmr;
95 static size_t sev_es_tmr_size = SEV_TMR_SIZE;
96 
97 /* INIT_EX NV Storage:
98  *   The NV Storage is a 32Kb area and must be 4Kb page aligned.  Use the page
99  *   allocator to allocate the memory, which will return aligned memory for the
100  *   specified allocation order.
101  */
102 #define NV_LENGTH (32 * 1024)
103 static void *sev_init_ex_buffer;
104 
105 /*
106  * SEV_DATA_RANGE_LIST:
107  *   Array containing range of pages that firmware transitions to HV-fixed
108  *   page state.
109  */
110 static struct sev_data_range_list *snp_range_list;
111 
112 static inline bool sev_version_greater_or_equal(u8 maj, u8 min)
113 {
114 	struct sev_device *sev = psp_master->sev_data;
115 
116 	if (sev->api_major > maj)
117 		return true;
118 
119 	if (sev->api_major == maj && sev->api_minor >= min)
120 		return true;
121 
122 	return false;
123 }
124 
125 static void sev_irq_handler(int irq, void *data, unsigned int status)
126 {
127 	struct sev_device *sev = data;
128 	int reg;
129 
130 	/* Check if it is command completion: */
131 	if (!(status & SEV_CMD_COMPLETE))
132 		return;
133 
134 	/* Check if it is SEV command completion: */
135 	reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
136 	if (FIELD_GET(PSP_CMDRESP_RESP, reg)) {
137 		sev->int_rcvd = 1;
138 		wake_up(&sev->int_queue);
139 	}
140 }
141 
142 static int sev_wait_cmd_ioc(struct sev_device *sev,
143 			    unsigned int *reg, unsigned int timeout)
144 {
145 	int ret;
146 
147 	/*
148 	 * If invoked during panic handling, local interrupts are disabled,
149 	 * so the PSP command completion interrupt can't be used. Poll for
150 	 * PSP command completion instead.
151 	 */
152 	if (irqs_disabled()) {
153 		unsigned long timeout_usecs = (timeout * USEC_PER_SEC) / 10;
154 
155 		/* Poll for SEV command completion: */
156 		while (timeout_usecs--) {
157 			*reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
158 			if (*reg & PSP_CMDRESP_RESP)
159 				return 0;
160 
161 			udelay(10);
162 		}
163 		return -ETIMEDOUT;
164 	}
165 
166 	ret = wait_event_timeout(sev->int_queue,
167 			sev->int_rcvd, timeout * HZ);
168 	if (!ret)
169 		return -ETIMEDOUT;
170 
171 	*reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
172 
173 	return 0;
174 }
175 
176 static int sev_cmd_buffer_len(int cmd)
177 {
178 	switch (cmd) {
179 	case SEV_CMD_INIT:			return sizeof(struct sev_data_init);
180 	case SEV_CMD_INIT_EX:                   return sizeof(struct sev_data_init_ex);
181 	case SEV_CMD_SNP_SHUTDOWN_EX:		return sizeof(struct sev_data_snp_shutdown_ex);
182 	case SEV_CMD_SNP_INIT_EX:		return sizeof(struct sev_data_snp_init_ex);
183 	case SEV_CMD_PLATFORM_STATUS:		return sizeof(struct sev_user_data_status);
184 	case SEV_CMD_PEK_CSR:			return sizeof(struct sev_data_pek_csr);
185 	case SEV_CMD_PEK_CERT_IMPORT:		return sizeof(struct sev_data_pek_cert_import);
186 	case SEV_CMD_PDH_CERT_EXPORT:		return sizeof(struct sev_data_pdh_cert_export);
187 	case SEV_CMD_LAUNCH_START:		return sizeof(struct sev_data_launch_start);
188 	case SEV_CMD_LAUNCH_UPDATE_DATA:	return sizeof(struct sev_data_launch_update_data);
189 	case SEV_CMD_LAUNCH_UPDATE_VMSA:	return sizeof(struct sev_data_launch_update_vmsa);
190 	case SEV_CMD_LAUNCH_FINISH:		return sizeof(struct sev_data_launch_finish);
191 	case SEV_CMD_LAUNCH_MEASURE:		return sizeof(struct sev_data_launch_measure);
192 	case SEV_CMD_ACTIVATE:			return sizeof(struct sev_data_activate);
193 	case SEV_CMD_DEACTIVATE:		return sizeof(struct sev_data_deactivate);
194 	case SEV_CMD_DECOMMISSION:		return sizeof(struct sev_data_decommission);
195 	case SEV_CMD_GUEST_STATUS:		return sizeof(struct sev_data_guest_status);
196 	case SEV_CMD_DBG_DECRYPT:		return sizeof(struct sev_data_dbg);
197 	case SEV_CMD_DBG_ENCRYPT:		return sizeof(struct sev_data_dbg);
198 	case SEV_CMD_SEND_START:		return sizeof(struct sev_data_send_start);
199 	case SEV_CMD_SEND_UPDATE_DATA:		return sizeof(struct sev_data_send_update_data);
200 	case SEV_CMD_SEND_UPDATE_VMSA:		return sizeof(struct sev_data_send_update_vmsa);
201 	case SEV_CMD_SEND_FINISH:		return sizeof(struct sev_data_send_finish);
202 	case SEV_CMD_RECEIVE_START:		return sizeof(struct sev_data_receive_start);
203 	case SEV_CMD_RECEIVE_FINISH:		return sizeof(struct sev_data_receive_finish);
204 	case SEV_CMD_RECEIVE_UPDATE_DATA:	return sizeof(struct sev_data_receive_update_data);
205 	case SEV_CMD_RECEIVE_UPDATE_VMSA:	return sizeof(struct sev_data_receive_update_vmsa);
206 	case SEV_CMD_LAUNCH_UPDATE_SECRET:	return sizeof(struct sev_data_launch_secret);
207 	case SEV_CMD_DOWNLOAD_FIRMWARE:		return sizeof(struct sev_data_download_firmware);
208 	case SEV_CMD_GET_ID:			return sizeof(struct sev_data_get_id);
209 	case SEV_CMD_ATTESTATION_REPORT:	return sizeof(struct sev_data_attestation_report);
210 	case SEV_CMD_SEND_CANCEL:		return sizeof(struct sev_data_send_cancel);
211 	case SEV_CMD_SNP_GCTX_CREATE:		return sizeof(struct sev_data_snp_addr);
212 	case SEV_CMD_SNP_LAUNCH_START:		return sizeof(struct sev_data_snp_launch_start);
213 	case SEV_CMD_SNP_LAUNCH_UPDATE:		return sizeof(struct sev_data_snp_launch_update);
214 	case SEV_CMD_SNP_ACTIVATE:		return sizeof(struct sev_data_snp_activate);
215 	case SEV_CMD_SNP_DECOMMISSION:		return sizeof(struct sev_data_snp_addr);
216 	case SEV_CMD_SNP_PAGE_RECLAIM:		return sizeof(struct sev_data_snp_page_reclaim);
217 	case SEV_CMD_SNP_GUEST_STATUS:		return sizeof(struct sev_data_snp_guest_status);
218 	case SEV_CMD_SNP_LAUNCH_FINISH:		return sizeof(struct sev_data_snp_launch_finish);
219 	case SEV_CMD_SNP_DBG_DECRYPT:		return sizeof(struct sev_data_snp_dbg);
220 	case SEV_CMD_SNP_DBG_ENCRYPT:		return sizeof(struct sev_data_snp_dbg);
221 	case SEV_CMD_SNP_PAGE_UNSMASH:		return sizeof(struct sev_data_snp_page_unsmash);
222 	case SEV_CMD_SNP_PLATFORM_STATUS:	return sizeof(struct sev_data_snp_addr);
223 	case SEV_CMD_SNP_GUEST_REQUEST:		return sizeof(struct sev_data_snp_guest_request);
224 	case SEV_CMD_SNP_CONFIG:		return sizeof(struct sev_user_data_snp_config);
225 	case SEV_CMD_SNP_COMMIT:		return sizeof(struct sev_data_snp_commit);
226 	default:				return 0;
227 	}
228 
229 	return 0;
230 }
231 
232 static struct file *open_file_as_root(const char *filename, int flags, umode_t mode)
233 {
234 	struct file *fp;
235 	struct path root;
236 	struct cred *cred;
237 	const struct cred *old_cred;
238 
239 	task_lock(&init_task);
240 	get_fs_root(init_task.fs, &root);
241 	task_unlock(&init_task);
242 
243 	cred = prepare_creds();
244 	if (!cred)
245 		return ERR_PTR(-ENOMEM);
246 	cred->fsuid = GLOBAL_ROOT_UID;
247 	old_cred = override_creds(cred);
248 
249 	fp = file_open_root(&root, filename, flags, mode);
250 	path_put(&root);
251 
252 	revert_creds(old_cred);
253 
254 	return fp;
255 }
256 
257 static int sev_read_init_ex_file(void)
258 {
259 	struct sev_device *sev = psp_master->sev_data;
260 	struct file *fp;
261 	ssize_t nread;
262 
263 	lockdep_assert_held(&sev_cmd_mutex);
264 
265 	if (!sev_init_ex_buffer)
266 		return -EOPNOTSUPP;
267 
268 	fp = open_file_as_root(init_ex_path, O_RDONLY, 0);
269 	if (IS_ERR(fp)) {
270 		int ret = PTR_ERR(fp);
271 
272 		if (ret == -ENOENT) {
273 			dev_info(sev->dev,
274 				"SEV: %s does not exist and will be created later.\n",
275 				init_ex_path);
276 			ret = 0;
277 		} else {
278 			dev_err(sev->dev,
279 				"SEV: could not open %s for read, error %d\n",
280 				init_ex_path, ret);
281 		}
282 		return ret;
283 	}
284 
285 	nread = kernel_read(fp, sev_init_ex_buffer, NV_LENGTH, NULL);
286 	if (nread != NV_LENGTH) {
287 		dev_info(sev->dev,
288 			"SEV: could not read %u bytes to non volatile memory area, ret %ld\n",
289 			NV_LENGTH, nread);
290 	}
291 
292 	dev_dbg(sev->dev, "SEV: read %ld bytes from NV file\n", nread);
293 	filp_close(fp, NULL);
294 
295 	return 0;
296 }
297 
298 static int sev_write_init_ex_file(void)
299 {
300 	struct sev_device *sev = psp_master->sev_data;
301 	struct file *fp;
302 	loff_t offset = 0;
303 	ssize_t nwrite;
304 
305 	lockdep_assert_held(&sev_cmd_mutex);
306 
307 	if (!sev_init_ex_buffer)
308 		return 0;
309 
310 	fp = open_file_as_root(init_ex_path, O_CREAT | O_WRONLY, 0600);
311 	if (IS_ERR(fp)) {
312 		int ret = PTR_ERR(fp);
313 
314 		dev_err(sev->dev,
315 			"SEV: could not open file for write, error %d\n",
316 			ret);
317 		return ret;
318 	}
319 
320 	nwrite = kernel_write(fp, sev_init_ex_buffer, NV_LENGTH, &offset);
321 	vfs_fsync(fp, 0);
322 	filp_close(fp, NULL);
323 
324 	if (nwrite != NV_LENGTH) {
325 		dev_err(sev->dev,
326 			"SEV: failed to write %u bytes to non volatile memory area, ret %ld\n",
327 			NV_LENGTH, nwrite);
328 		return -EIO;
329 	}
330 
331 	dev_dbg(sev->dev, "SEV: write successful to NV file\n");
332 
333 	return 0;
334 }
335 
336 static int sev_write_init_ex_file_if_required(int cmd_id)
337 {
338 	lockdep_assert_held(&sev_cmd_mutex);
339 
340 	if (!sev_init_ex_buffer)
341 		return 0;
342 
343 	/*
344 	 * Only a few platform commands modify the SPI/NV area, but none of the
345 	 * non-platform commands do. Only INIT(_EX), PLATFORM_RESET, PEK_GEN,
346 	 * PEK_CERT_IMPORT, and PDH_GEN do.
347 	 */
348 	switch (cmd_id) {
349 	case SEV_CMD_FACTORY_RESET:
350 	case SEV_CMD_INIT_EX:
351 	case SEV_CMD_PDH_GEN:
352 	case SEV_CMD_PEK_CERT_IMPORT:
353 	case SEV_CMD_PEK_GEN:
354 		break;
355 	default:
356 		return 0;
357 	}
358 
359 	return sev_write_init_ex_file();
360 }
361 
362 /*
363  * snp_reclaim_pages() needs __sev_do_cmd_locked(), and __sev_do_cmd_locked()
364  * needs snp_reclaim_pages(), so a forward declaration is needed.
365  */
366 static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret);
367 
368 static int snp_reclaim_pages(unsigned long paddr, unsigned int npages, bool locked)
369 {
370 	int ret, err, i;
371 
372 	paddr = __sme_clr(ALIGN_DOWN(paddr, PAGE_SIZE));
373 
374 	for (i = 0; i < npages; i++, paddr += PAGE_SIZE) {
375 		struct sev_data_snp_page_reclaim data = {0};
376 
377 		data.paddr = paddr;
378 
379 		if (locked)
380 			ret = __sev_do_cmd_locked(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
381 		else
382 			ret = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &err);
383 
384 		if (ret)
385 			goto cleanup;
386 
387 		ret = rmp_make_shared(__phys_to_pfn(paddr), PG_LEVEL_4K);
388 		if (ret)
389 			goto cleanup;
390 	}
391 
392 	return 0;
393 
394 cleanup:
395 	/*
396 	 * If there was a failure reclaiming the page then it is no longer safe
397 	 * to release it back to the system; leak it instead.
398 	 */
399 	snp_leak_pages(__phys_to_pfn(paddr), npages - i);
400 	return ret;
401 }
402 
403 static int rmp_mark_pages_firmware(unsigned long paddr, unsigned int npages, bool locked)
404 {
405 	unsigned long pfn = __sme_clr(paddr) >> PAGE_SHIFT;
406 	int rc, i;
407 
408 	for (i = 0; i < npages; i++, pfn++) {
409 		rc = rmp_make_private(pfn, 0, PG_LEVEL_4K, 0, true);
410 		if (rc)
411 			goto cleanup;
412 	}
413 
414 	return 0;
415 
416 cleanup:
417 	/*
418 	 * Try unrolling the firmware state changes by
419 	 * reclaiming the pages which were already changed to the
420 	 * firmware state.
421 	 */
422 	snp_reclaim_pages(paddr, i, locked);
423 
424 	return rc;
425 }
426 
427 static struct page *__snp_alloc_firmware_pages(gfp_t gfp_mask, int order)
428 {
429 	unsigned long npages = 1ul << order, paddr;
430 	struct sev_device *sev;
431 	struct page *page;
432 
433 	if (!psp_master || !psp_master->sev_data)
434 		return NULL;
435 
436 	page = alloc_pages(gfp_mask, order);
437 	if (!page)
438 		return NULL;
439 
440 	/* If SEV-SNP is initialized then add the page in RMP table. */
441 	sev = psp_master->sev_data;
442 	if (!sev->snp_initialized)
443 		return page;
444 
445 	paddr = __pa((unsigned long)page_address(page));
446 	if (rmp_mark_pages_firmware(paddr, npages, false))
447 		return NULL;
448 
449 	return page;
450 }
451 
452 void *snp_alloc_firmware_page(gfp_t gfp_mask)
453 {
454 	struct page *page;
455 
456 	page = __snp_alloc_firmware_pages(gfp_mask, 0);
457 
458 	return page ? page_address(page) : NULL;
459 }
460 EXPORT_SYMBOL_GPL(snp_alloc_firmware_page);
461 
462 static void __snp_free_firmware_pages(struct page *page, int order, bool locked)
463 {
464 	struct sev_device *sev = psp_master->sev_data;
465 	unsigned long paddr, npages = 1ul << order;
466 
467 	if (!page)
468 		return;
469 
470 	paddr = __pa((unsigned long)page_address(page));
471 	if (sev->snp_initialized &&
472 	    snp_reclaim_pages(paddr, npages, locked))
473 		return;
474 
475 	__free_pages(page, order);
476 }
477 
478 void snp_free_firmware_page(void *addr)
479 {
480 	if (!addr)
481 		return;
482 
483 	__snp_free_firmware_pages(virt_to_page(addr), 0, false);
484 }
485 EXPORT_SYMBOL_GPL(snp_free_firmware_page);
486 
487 static void *sev_fw_alloc(unsigned long len)
488 {
489 	struct page *page;
490 
491 	page = __snp_alloc_firmware_pages(GFP_KERNEL, get_order(len));
492 	if (!page)
493 		return NULL;
494 
495 	return page_address(page);
496 }
497 
498 /**
499  * struct cmd_buf_desc - descriptors for managing legacy SEV command address
500  * parameters corresponding to buffers that may be written to by firmware.
501  *
502  * @paddr_ptr:  pointer to the address parameter in the command buffer which may
503  *              need to be saved/restored depending on whether a bounce buffer
504  *              is used. In the case of a bounce buffer, the command buffer
505  *              needs to be updated with the address of the new bounce buffer
506  *              snp_map_cmd_buf_desc() has allocated specifically for it. Must
507  *              be NULL if this descriptor is only an end-of-list indicator.
508  *
509  * @paddr_orig: storage for the original address parameter, which can be used to
510  *              restore the original value in @paddr_ptr in cases where it is
511  *              replaced with the address of a bounce buffer.
512  *
513  * @len: length of buffer located at the address originally stored at @paddr_ptr
514  *
515  * @guest_owned: true if the address corresponds to guest-owned pages, in which
516  *               case bounce buffers are not needed.
517  */
518 struct cmd_buf_desc {
519 	u64 *paddr_ptr;
520 	u64 paddr_orig;
521 	u32 len;
522 	bool guest_owned;
523 };
524 
525 /*
526  * If a legacy SEV command parameter is a memory address, those pages in
527  * turn need to be transitioned to/from firmware-owned before/after
528  * executing the firmware command.
529  *
530  * Additionally, in cases where those pages are not guest-owned, a bounce
531  * buffer is needed in place of the original memory address parameter.
532  *
533  * A set of descriptors are used to keep track of this handling, and
534  * initialized here based on the specific commands being executed.
535  */
536 static void snp_populate_cmd_buf_desc_list(int cmd, void *cmd_buf,
537 					   struct cmd_buf_desc *desc_list)
538 {
539 	switch (cmd) {
540 	case SEV_CMD_PDH_CERT_EXPORT: {
541 		struct sev_data_pdh_cert_export *data = cmd_buf;
542 
543 		desc_list[0].paddr_ptr = &data->pdh_cert_address;
544 		desc_list[0].len = data->pdh_cert_len;
545 		desc_list[1].paddr_ptr = &data->cert_chain_address;
546 		desc_list[1].len = data->cert_chain_len;
547 		break;
548 	}
549 	case SEV_CMD_GET_ID: {
550 		struct sev_data_get_id *data = cmd_buf;
551 
552 		desc_list[0].paddr_ptr = &data->address;
553 		desc_list[0].len = data->len;
554 		break;
555 	}
556 	case SEV_CMD_PEK_CSR: {
557 		struct sev_data_pek_csr *data = cmd_buf;
558 
559 		desc_list[0].paddr_ptr = &data->address;
560 		desc_list[0].len = data->len;
561 		break;
562 	}
563 	case SEV_CMD_LAUNCH_UPDATE_DATA: {
564 		struct sev_data_launch_update_data *data = cmd_buf;
565 
566 		desc_list[0].paddr_ptr = &data->address;
567 		desc_list[0].len = data->len;
568 		desc_list[0].guest_owned = true;
569 		break;
570 	}
571 	case SEV_CMD_LAUNCH_UPDATE_VMSA: {
572 		struct sev_data_launch_update_vmsa *data = cmd_buf;
573 
574 		desc_list[0].paddr_ptr = &data->address;
575 		desc_list[0].len = data->len;
576 		desc_list[0].guest_owned = true;
577 		break;
578 	}
579 	case SEV_CMD_LAUNCH_MEASURE: {
580 		struct sev_data_launch_measure *data = cmd_buf;
581 
582 		desc_list[0].paddr_ptr = &data->address;
583 		desc_list[0].len = data->len;
584 		break;
585 	}
586 	case SEV_CMD_LAUNCH_UPDATE_SECRET: {
587 		struct sev_data_launch_secret *data = cmd_buf;
588 
589 		desc_list[0].paddr_ptr = &data->guest_address;
590 		desc_list[0].len = data->guest_len;
591 		desc_list[0].guest_owned = true;
592 		break;
593 	}
594 	case SEV_CMD_DBG_DECRYPT: {
595 		struct sev_data_dbg *data = cmd_buf;
596 
597 		desc_list[0].paddr_ptr = &data->dst_addr;
598 		desc_list[0].len = data->len;
599 		desc_list[0].guest_owned = true;
600 		break;
601 	}
602 	case SEV_CMD_DBG_ENCRYPT: {
603 		struct sev_data_dbg *data = cmd_buf;
604 
605 		desc_list[0].paddr_ptr = &data->dst_addr;
606 		desc_list[0].len = data->len;
607 		desc_list[0].guest_owned = true;
608 		break;
609 	}
610 	case SEV_CMD_ATTESTATION_REPORT: {
611 		struct sev_data_attestation_report *data = cmd_buf;
612 
613 		desc_list[0].paddr_ptr = &data->address;
614 		desc_list[0].len = data->len;
615 		break;
616 	}
617 	case SEV_CMD_SEND_START: {
618 		struct sev_data_send_start *data = cmd_buf;
619 
620 		desc_list[0].paddr_ptr = &data->session_address;
621 		desc_list[0].len = data->session_len;
622 		break;
623 	}
624 	case SEV_CMD_SEND_UPDATE_DATA: {
625 		struct sev_data_send_update_data *data = cmd_buf;
626 
627 		desc_list[0].paddr_ptr = &data->hdr_address;
628 		desc_list[0].len = data->hdr_len;
629 		desc_list[1].paddr_ptr = &data->trans_address;
630 		desc_list[1].len = data->trans_len;
631 		break;
632 	}
633 	case SEV_CMD_SEND_UPDATE_VMSA: {
634 		struct sev_data_send_update_vmsa *data = cmd_buf;
635 
636 		desc_list[0].paddr_ptr = &data->hdr_address;
637 		desc_list[0].len = data->hdr_len;
638 		desc_list[1].paddr_ptr = &data->trans_address;
639 		desc_list[1].len = data->trans_len;
640 		break;
641 	}
642 	case SEV_CMD_RECEIVE_UPDATE_DATA: {
643 		struct sev_data_receive_update_data *data = cmd_buf;
644 
645 		desc_list[0].paddr_ptr = &data->guest_address;
646 		desc_list[0].len = data->guest_len;
647 		desc_list[0].guest_owned = true;
648 		break;
649 	}
650 	case SEV_CMD_RECEIVE_UPDATE_VMSA: {
651 		struct sev_data_receive_update_vmsa *data = cmd_buf;
652 
653 		desc_list[0].paddr_ptr = &data->guest_address;
654 		desc_list[0].len = data->guest_len;
655 		desc_list[0].guest_owned = true;
656 		break;
657 	}
658 	default:
659 		break;
660 	}
661 }
662 
663 static int snp_map_cmd_buf_desc(struct cmd_buf_desc *desc)
664 {
665 	unsigned int npages;
666 
667 	if (!desc->len)
668 		return 0;
669 
670 	/* Allocate a bounce buffer if this isn't a guest owned page. */
671 	if (!desc->guest_owned) {
672 		struct page *page;
673 
674 		page = alloc_pages(GFP_KERNEL_ACCOUNT, get_order(desc->len));
675 		if (!page) {
676 			pr_warn("Failed to allocate bounce buffer for SEV legacy command.\n");
677 			return -ENOMEM;
678 		}
679 
680 		desc->paddr_orig = *desc->paddr_ptr;
681 		*desc->paddr_ptr = __psp_pa(page_to_virt(page));
682 	}
683 
684 	npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
685 
686 	/* Transition the buffer to firmware-owned. */
687 	if (rmp_mark_pages_firmware(*desc->paddr_ptr, npages, true)) {
688 		pr_warn("Error moving pages to firmware-owned state for SEV legacy command.\n");
689 		return -EFAULT;
690 	}
691 
692 	return 0;
693 }
694 
695 static int snp_unmap_cmd_buf_desc(struct cmd_buf_desc *desc)
696 {
697 	unsigned int npages;
698 
699 	if (!desc->len)
700 		return 0;
701 
702 	npages = PAGE_ALIGN(desc->len) >> PAGE_SHIFT;
703 
704 	/* Transition the buffers back to hypervisor-owned. */
705 	if (snp_reclaim_pages(*desc->paddr_ptr, npages, true)) {
706 		pr_warn("Failed to reclaim firmware-owned pages while issuing SEV legacy command.\n");
707 		return -EFAULT;
708 	}
709 
710 	/* Copy data from bounce buffer and then free it. */
711 	if (!desc->guest_owned) {
712 		void *bounce_buf = __va(__sme_clr(*desc->paddr_ptr));
713 		void *dst_buf = __va(__sme_clr(desc->paddr_orig));
714 
715 		memcpy(dst_buf, bounce_buf, desc->len);
716 		__free_pages(virt_to_page(bounce_buf), get_order(desc->len));
717 
718 		/* Restore the original address in the command buffer. */
719 		*desc->paddr_ptr = desc->paddr_orig;
720 	}
721 
722 	return 0;
723 }
724 
725 static int snp_map_cmd_buf_desc_list(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
726 {
727 	int i;
728 
729 	snp_populate_cmd_buf_desc_list(cmd, cmd_buf, desc_list);
730 
731 	for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
732 		struct cmd_buf_desc *desc = &desc_list[i];
733 
734 		if (!desc->paddr_ptr)
735 			break;
736 
737 		if (snp_map_cmd_buf_desc(desc))
738 			goto err_unmap;
739 	}
740 
741 	return 0;
742 
743 err_unmap:
744 	for (i--; i >= 0; i--)
745 		snp_unmap_cmd_buf_desc(&desc_list[i]);
746 
747 	return -EFAULT;
748 }
749 
750 static int snp_unmap_cmd_buf_desc_list(struct cmd_buf_desc *desc_list)
751 {
752 	int i, ret = 0;
753 
754 	for (i = 0; i < CMD_BUF_DESC_MAX; i++) {
755 		struct cmd_buf_desc *desc = &desc_list[i];
756 
757 		if (!desc->paddr_ptr)
758 			break;
759 
760 		if (snp_unmap_cmd_buf_desc(&desc_list[i]))
761 			ret = -EFAULT;
762 	}
763 
764 	return ret;
765 }
766 
767 static bool sev_cmd_buf_writable(int cmd)
768 {
769 	switch (cmd) {
770 	case SEV_CMD_PLATFORM_STATUS:
771 	case SEV_CMD_GUEST_STATUS:
772 	case SEV_CMD_LAUNCH_START:
773 	case SEV_CMD_RECEIVE_START:
774 	case SEV_CMD_LAUNCH_MEASURE:
775 	case SEV_CMD_SEND_START:
776 	case SEV_CMD_SEND_UPDATE_DATA:
777 	case SEV_CMD_SEND_UPDATE_VMSA:
778 	case SEV_CMD_PEK_CSR:
779 	case SEV_CMD_PDH_CERT_EXPORT:
780 	case SEV_CMD_GET_ID:
781 	case SEV_CMD_ATTESTATION_REPORT:
782 		return true;
783 	default:
784 		return false;
785 	}
786 }
787 
788 /* After SNP is INIT'ed, the behavior of legacy SEV commands is changed. */
789 static bool snp_legacy_handling_needed(int cmd)
790 {
791 	struct sev_device *sev = psp_master->sev_data;
792 
793 	return cmd < SEV_CMD_SNP_INIT && sev->snp_initialized;
794 }
795 
796 static int snp_prep_cmd_buf(int cmd, void *cmd_buf, struct cmd_buf_desc *desc_list)
797 {
798 	if (!snp_legacy_handling_needed(cmd))
799 		return 0;
800 
801 	if (snp_map_cmd_buf_desc_list(cmd, cmd_buf, desc_list))
802 		return -EFAULT;
803 
804 	/*
805 	 * Before command execution, the command buffer needs to be put into
806 	 * the firmware-owned state.
807 	 */
808 	if (sev_cmd_buf_writable(cmd)) {
809 		if (rmp_mark_pages_firmware(__pa(cmd_buf), 1, true))
810 			return -EFAULT;
811 	}
812 
813 	return 0;
814 }
815 
816 static int snp_reclaim_cmd_buf(int cmd, void *cmd_buf)
817 {
818 	if (!snp_legacy_handling_needed(cmd))
819 		return 0;
820 
821 	/*
822 	 * After command completion, the command buffer needs to be put back
823 	 * into the hypervisor-owned state.
824 	 */
825 	if (sev_cmd_buf_writable(cmd))
826 		if (snp_reclaim_pages(__pa(cmd_buf), 1, true))
827 			return -EFAULT;
828 
829 	return 0;
830 }
831 
832 static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret)
833 {
834 	struct cmd_buf_desc desc_list[CMD_BUF_DESC_MAX] = {0};
835 	struct psp_device *psp = psp_master;
836 	struct sev_device *sev;
837 	unsigned int cmdbuff_hi, cmdbuff_lo;
838 	unsigned int phys_lsb, phys_msb;
839 	unsigned int reg, ret = 0;
840 	void *cmd_buf;
841 	int buf_len;
842 
843 	if (!psp || !psp->sev_data)
844 		return -ENODEV;
845 
846 	if (psp_dead)
847 		return -EBUSY;
848 
849 	sev = psp->sev_data;
850 
851 	buf_len = sev_cmd_buffer_len(cmd);
852 	if (WARN_ON_ONCE(!data != !buf_len))
853 		return -EINVAL;
854 
855 	/*
856 	 * Copy the incoming data to driver's scratch buffer as __pa() will not
857 	 * work for some memory, e.g. vmalloc'd addresses, and @data may not be
858 	 * physically contiguous.
859 	 */
860 	if (data) {
861 		/*
862 		 * Commands are generally issued one at a time and require the
863 		 * sev_cmd_mutex, but there could be recursive firmware requests
864 		 * due to SEV_CMD_SNP_PAGE_RECLAIM needing to be issued while
865 		 * preparing buffers for another command. This is the only known
866 		 * case of nesting in the current code, so exactly one
867 		 * additional command buffer is available for that purpose.
868 		 */
869 		if (!sev->cmd_buf_active) {
870 			cmd_buf = sev->cmd_buf;
871 			sev->cmd_buf_active = true;
872 		} else if (!sev->cmd_buf_backup_active) {
873 			cmd_buf = sev->cmd_buf_backup;
874 			sev->cmd_buf_backup_active = true;
875 		} else {
876 			dev_err(sev->dev,
877 				"SEV: too many firmware commands in progress, no command buffers available.\n");
878 			return -EBUSY;
879 		}
880 
881 		memcpy(cmd_buf, data, buf_len);
882 
883 		/*
884 		 * The behavior of the SEV-legacy commands is altered when the
885 		 * SNP firmware is in the INIT state.
886 		 */
887 		ret = snp_prep_cmd_buf(cmd, cmd_buf, desc_list);
888 		if (ret) {
889 			dev_err(sev->dev,
890 				"SEV: failed to prepare buffer for legacy command 0x%x. Error: %d\n",
891 				cmd, ret);
892 			return ret;
893 		}
894 	} else {
895 		cmd_buf = sev->cmd_buf;
896 	}
897 
898 	/* Get the physical address of the command buffer */
899 	phys_lsb = data ? lower_32_bits(__psp_pa(cmd_buf)) : 0;
900 	phys_msb = data ? upper_32_bits(__psp_pa(cmd_buf)) : 0;
901 
902 	dev_dbg(sev->dev, "sev command id %#x buffer 0x%08x%08x timeout %us\n",
903 		cmd, phys_msb, phys_lsb, psp_timeout);
904 
905 	print_hex_dump_debug("(in):  ", DUMP_PREFIX_OFFSET, 16, 2, data,
906 			     buf_len, false);
907 
908 	iowrite32(phys_lsb, sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
909 	iowrite32(phys_msb, sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
910 
911 	sev->int_rcvd = 0;
912 
913 	reg = FIELD_PREP(SEV_CMDRESP_CMD, cmd) | SEV_CMDRESP_IOC;
914 	iowrite32(reg, sev->io_regs + sev->vdata->cmdresp_reg);
915 
916 	/* wait for command completion */
917 	ret = sev_wait_cmd_ioc(sev, &reg, psp_timeout);
918 	if (ret) {
919 		if (psp_ret)
920 			*psp_ret = 0;
921 
922 		dev_err(sev->dev, "sev command %#x timed out, disabling PSP\n", cmd);
923 		psp_dead = true;
924 
925 		return ret;
926 	}
927 
928 	psp_timeout = psp_cmd_timeout;
929 
930 	if (psp_ret)
931 		*psp_ret = FIELD_GET(PSP_CMDRESP_STS, reg);
932 
933 	if (FIELD_GET(PSP_CMDRESP_STS, reg)) {
934 		dev_dbg(sev->dev, "sev command %#x failed (%#010lx)\n",
935 			cmd, FIELD_GET(PSP_CMDRESP_STS, reg));
936 
937 		/*
938 		 * PSP firmware may report additional error information in the
939 		 * command buffer registers on error. Print contents of command
940 		 * buffer registers if they changed.
941 		 */
942 		cmdbuff_hi = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
943 		cmdbuff_lo = ioread32(sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
944 		if (cmdbuff_hi != phys_msb || cmdbuff_lo != phys_lsb) {
945 			dev_dbg(sev->dev, "Additional error information reported in cmdbuff:");
946 			dev_dbg(sev->dev, "  cmdbuff hi: %#010x\n", cmdbuff_hi);
947 			dev_dbg(sev->dev, "  cmdbuff lo: %#010x\n", cmdbuff_lo);
948 		}
949 		ret = -EIO;
950 	} else {
951 		ret = sev_write_init_ex_file_if_required(cmd);
952 	}
953 
954 	/*
955 	 * Copy potential output from the PSP back to data.  Do this even on
956 	 * failure in case the caller wants to glean something from the error.
957 	 */
958 	if (data) {
959 		int ret_reclaim;
960 		/*
961 		 * Restore the page state after the command completes.
962 		 */
963 		ret_reclaim = snp_reclaim_cmd_buf(cmd, cmd_buf);
964 		if (ret_reclaim) {
965 			dev_err(sev->dev,
966 				"SEV: failed to reclaim buffer for legacy command %#x. Error: %d\n",
967 				cmd, ret_reclaim);
968 			return ret_reclaim;
969 		}
970 
971 		memcpy(data, cmd_buf, buf_len);
972 
973 		if (sev->cmd_buf_backup_active)
974 			sev->cmd_buf_backup_active = false;
975 		else
976 			sev->cmd_buf_active = false;
977 
978 		if (snp_unmap_cmd_buf_desc_list(desc_list))
979 			return -EFAULT;
980 	}
981 
982 	print_hex_dump_debug("(out): ", DUMP_PREFIX_OFFSET, 16, 2, data,
983 			     buf_len, false);
984 
985 	return ret;
986 }
987 
988 int sev_do_cmd(int cmd, void *data, int *psp_ret)
989 {
990 	int rc;
991 
992 	mutex_lock(&sev_cmd_mutex);
993 	rc = __sev_do_cmd_locked(cmd, data, psp_ret);
994 	mutex_unlock(&sev_cmd_mutex);
995 
996 	return rc;
997 }
998 EXPORT_SYMBOL_GPL(sev_do_cmd);
999 
1000 static int __sev_init_locked(int *error)
1001 {
1002 	struct sev_data_init data;
1003 
1004 	memset(&data, 0, sizeof(data));
1005 	if (sev_es_tmr) {
1006 		/*
1007 		 * Do not include the encryption mask on the physical
1008 		 * address of the TMR (firmware should clear it anyway).
1009 		 */
1010 		data.tmr_address = __pa(sev_es_tmr);
1011 
1012 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
1013 		data.tmr_len = sev_es_tmr_size;
1014 	}
1015 
1016 	return __sev_do_cmd_locked(SEV_CMD_INIT, &data, error);
1017 }
1018 
1019 static int __sev_init_ex_locked(int *error)
1020 {
1021 	struct sev_data_init_ex data;
1022 
1023 	memset(&data, 0, sizeof(data));
1024 	data.length = sizeof(data);
1025 	data.nv_address = __psp_pa(sev_init_ex_buffer);
1026 	data.nv_len = NV_LENGTH;
1027 
1028 	if (sev_es_tmr) {
1029 		/*
1030 		 * Do not include the encryption mask on the physical
1031 		 * address of the TMR (firmware should clear it anyway).
1032 		 */
1033 		data.tmr_address = __pa(sev_es_tmr);
1034 
1035 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
1036 		data.tmr_len = sev_es_tmr_size;
1037 	}
1038 
1039 	return __sev_do_cmd_locked(SEV_CMD_INIT_EX, &data, error);
1040 }
1041 
1042 static inline int __sev_do_init_locked(int *psp_ret)
1043 {
1044 	if (sev_init_ex_buffer)
1045 		return __sev_init_ex_locked(psp_ret);
1046 	else
1047 		return __sev_init_locked(psp_ret);
1048 }
1049 
1050 static void snp_set_hsave_pa(void *arg)
1051 {
1052 	wrmsrl(MSR_VM_HSAVE_PA, 0);
1053 }
1054 
1055 static int snp_filter_reserved_mem_regions(struct resource *rs, void *arg)
1056 {
1057 	struct sev_data_range_list *range_list = arg;
1058 	struct sev_data_range *range = &range_list->ranges[range_list->num_elements];
1059 	size_t size;
1060 
1061 	/*
1062 	 * Ensure the list of HV_FIXED pages that will be passed to firmware
1063 	 * do not exceed the page-sized argument buffer.
1064 	 */
1065 	if ((range_list->num_elements * sizeof(struct sev_data_range) +
1066 	     sizeof(struct sev_data_range_list)) > PAGE_SIZE)
1067 		return -E2BIG;
1068 
1069 	switch (rs->desc) {
1070 	case E820_TYPE_RESERVED:
1071 	case E820_TYPE_PMEM:
1072 	case E820_TYPE_ACPI:
1073 		range->base = rs->start & PAGE_MASK;
1074 		size = PAGE_ALIGN((rs->end + 1) - rs->start);
1075 		range->page_count = size >> PAGE_SHIFT;
1076 		range_list->num_elements++;
1077 		break;
1078 	default:
1079 		break;
1080 	}
1081 
1082 	return 0;
1083 }
1084 
1085 static int __sev_snp_init_locked(int *error)
1086 {
1087 	struct psp_device *psp = psp_master;
1088 	struct sev_data_snp_init_ex data;
1089 	struct sev_device *sev;
1090 	void *arg = &data;
1091 	int cmd, rc = 0;
1092 
1093 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
1094 		return -ENODEV;
1095 
1096 	sev = psp->sev_data;
1097 
1098 	if (sev->snp_initialized)
1099 		return 0;
1100 
1101 	if (!sev_version_greater_or_equal(SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR)) {
1102 		dev_dbg(sev->dev, "SEV-SNP support requires firmware version >= %d:%d\n",
1103 			SNP_MIN_API_MAJOR, SNP_MIN_API_MINOR);
1104 		return 0;
1105 	}
1106 
1107 	/* SNP_INIT requires MSR_VM_HSAVE_PA to be cleared on all CPUs. */
1108 	on_each_cpu(snp_set_hsave_pa, NULL, 1);
1109 
1110 	/*
1111 	 * Starting in SNP firmware v1.52, the SNP_INIT_EX command takes a list
1112 	 * of system physical address ranges to convert into HV-fixed page
1113 	 * states during the RMP initialization.  For instance, the memory that
1114 	 * UEFI reserves should be included in the that list. This allows system
1115 	 * components that occasionally write to memory (e.g. logging to UEFI
1116 	 * reserved regions) to not fail due to RMP initialization and SNP
1117 	 * enablement.
1118 	 *
1119 	 */
1120 	if (sev_version_greater_or_equal(SNP_MIN_API_MAJOR, 52)) {
1121 		/*
1122 		 * Firmware checks that the pages containing the ranges enumerated
1123 		 * in the RANGES structure are either in the default page state or in the
1124 		 * firmware page state.
1125 		 */
1126 		snp_range_list = kzalloc(PAGE_SIZE, GFP_KERNEL);
1127 		if (!snp_range_list) {
1128 			dev_err(sev->dev,
1129 				"SEV: SNP_INIT_EX range list memory allocation failed\n");
1130 			return -ENOMEM;
1131 		}
1132 
1133 		/*
1134 		 * Retrieve all reserved memory regions from the e820 memory map
1135 		 * to be setup as HV-fixed pages.
1136 		 */
1137 		rc = walk_iomem_res_desc(IORES_DESC_NONE, IORESOURCE_MEM, 0, ~0,
1138 					 snp_range_list, snp_filter_reserved_mem_regions);
1139 		if (rc) {
1140 			dev_err(sev->dev,
1141 				"SEV: SNP_INIT_EX walk_iomem_res_desc failed rc = %d\n", rc);
1142 			return rc;
1143 		}
1144 
1145 		memset(&data, 0, sizeof(data));
1146 		data.init_rmp = 1;
1147 		data.list_paddr_en = 1;
1148 		data.list_paddr = __psp_pa(snp_range_list);
1149 		cmd = SEV_CMD_SNP_INIT_EX;
1150 	} else {
1151 		cmd = SEV_CMD_SNP_INIT;
1152 		arg = NULL;
1153 	}
1154 
1155 	/*
1156 	 * The following sequence must be issued before launching the first SNP
1157 	 * guest to ensure all dirty cache lines are flushed, including from
1158 	 * updates to the RMP table itself via the RMPUPDATE instruction:
1159 	 *
1160 	 * - WBINVD on all running CPUs
1161 	 * - SEV_CMD_SNP_INIT[_EX] firmware command
1162 	 * - WBINVD on all running CPUs
1163 	 * - SEV_CMD_SNP_DF_FLUSH firmware command
1164 	 */
1165 	wbinvd_on_all_cpus();
1166 
1167 	rc = __sev_do_cmd_locked(cmd, arg, error);
1168 	if (rc)
1169 		return rc;
1170 
1171 	/* Prepare for first SNP guest launch after INIT. */
1172 	wbinvd_on_all_cpus();
1173 	rc = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, error);
1174 	if (rc)
1175 		return rc;
1176 
1177 	sev->snp_initialized = true;
1178 	dev_dbg(sev->dev, "SEV-SNP firmware initialized\n");
1179 
1180 	sev_es_tmr_size = SNP_TMR_SIZE;
1181 
1182 	return rc;
1183 }
1184 
1185 static void __sev_platform_init_handle_tmr(struct sev_device *sev)
1186 {
1187 	if (sev_es_tmr)
1188 		return;
1189 
1190 	/* Obtain the TMR memory area for SEV-ES use */
1191 	sev_es_tmr = sev_fw_alloc(sev_es_tmr_size);
1192 	if (sev_es_tmr) {
1193 		/* Must flush the cache before giving it to the firmware */
1194 		if (!sev->snp_initialized)
1195 			clflush_cache_range(sev_es_tmr, sev_es_tmr_size);
1196 	} else {
1197 			dev_warn(sev->dev, "SEV: TMR allocation failed, SEV-ES support unavailable\n");
1198 	}
1199 }
1200 
1201 /*
1202  * If an init_ex_path is provided allocate a buffer for the file and
1203  * read in the contents. Additionally, if SNP is initialized, convert
1204  * the buffer pages to firmware pages.
1205  */
1206 static int __sev_platform_init_handle_init_ex_path(struct sev_device *sev)
1207 {
1208 	struct page *page;
1209 	int rc;
1210 
1211 	if (!init_ex_path)
1212 		return 0;
1213 
1214 	if (sev_init_ex_buffer)
1215 		return 0;
1216 
1217 	page = alloc_pages(GFP_KERNEL, get_order(NV_LENGTH));
1218 	if (!page) {
1219 		dev_err(sev->dev, "SEV: INIT_EX NV memory allocation failed\n");
1220 		return -ENOMEM;
1221 	}
1222 
1223 	sev_init_ex_buffer = page_address(page);
1224 
1225 	rc = sev_read_init_ex_file();
1226 	if (rc)
1227 		return rc;
1228 
1229 	/* If SEV-SNP is initialized, transition to firmware page. */
1230 	if (sev->snp_initialized) {
1231 		unsigned long npages;
1232 
1233 		npages = 1UL << get_order(NV_LENGTH);
1234 		if (rmp_mark_pages_firmware(__pa(sev_init_ex_buffer), npages, false)) {
1235 			dev_err(sev->dev, "SEV: INIT_EX NV memory page state change failed.\n");
1236 			return -ENOMEM;
1237 		}
1238 	}
1239 
1240 	return 0;
1241 }
1242 
1243 static int __sev_platform_init_locked(int *error)
1244 {
1245 	int rc, psp_ret = SEV_RET_NO_FW_CALL;
1246 	struct sev_device *sev;
1247 
1248 	if (!psp_master || !psp_master->sev_data)
1249 		return -ENODEV;
1250 
1251 	sev = psp_master->sev_data;
1252 
1253 	if (sev->state == SEV_STATE_INIT)
1254 		return 0;
1255 
1256 	__sev_platform_init_handle_tmr(sev);
1257 
1258 	rc = __sev_platform_init_handle_init_ex_path(sev);
1259 	if (rc)
1260 		return rc;
1261 
1262 	rc = __sev_do_init_locked(&psp_ret);
1263 	if (rc && psp_ret == SEV_RET_SECURE_DATA_INVALID) {
1264 		/*
1265 		 * Initialization command returned an integrity check failure
1266 		 * status code, meaning that firmware load and validation of SEV
1267 		 * related persistent data has failed. Retrying the
1268 		 * initialization function should succeed by replacing the state
1269 		 * with a reset state.
1270 		 */
1271 		dev_err(sev->dev,
1272 "SEV: retrying INIT command because of SECURE_DATA_INVALID error. Retrying once to reset PSP SEV state.");
1273 		rc = __sev_do_init_locked(&psp_ret);
1274 	}
1275 
1276 	if (error)
1277 		*error = psp_ret;
1278 
1279 	if (rc)
1280 		return rc;
1281 
1282 	sev->state = SEV_STATE_INIT;
1283 
1284 	/* Prepare for first SEV guest launch after INIT */
1285 	wbinvd_on_all_cpus();
1286 	rc = __sev_do_cmd_locked(SEV_CMD_DF_FLUSH, NULL, error);
1287 	if (rc)
1288 		return rc;
1289 
1290 	dev_dbg(sev->dev, "SEV firmware initialized\n");
1291 
1292 	dev_info(sev->dev, "SEV API:%d.%d build:%d\n", sev->api_major,
1293 		 sev->api_minor, sev->build);
1294 
1295 	return 0;
1296 }
1297 
1298 static int _sev_platform_init_locked(struct sev_platform_init_args *args)
1299 {
1300 	struct sev_device *sev;
1301 	int rc;
1302 
1303 	if (!psp_master || !psp_master->sev_data)
1304 		return -ENODEV;
1305 
1306 	sev = psp_master->sev_data;
1307 
1308 	if (sev->state == SEV_STATE_INIT)
1309 		return 0;
1310 
1311 	/*
1312 	 * Legacy guests cannot be running while SNP_INIT(_EX) is executing,
1313 	 * so perform SEV-SNP initialization at probe time.
1314 	 */
1315 	rc = __sev_snp_init_locked(&args->error);
1316 	if (rc && rc != -ENODEV) {
1317 		/*
1318 		 * Don't abort the probe if SNP INIT failed,
1319 		 * continue to initialize the legacy SEV firmware.
1320 		 */
1321 		dev_err(sev->dev, "SEV-SNP: failed to INIT rc %d, error %#x\n",
1322 			rc, args->error);
1323 	}
1324 
1325 	/* Defer legacy SEV/SEV-ES support if allowed by caller/module. */
1326 	if (args->probe && !psp_init_on_probe)
1327 		return 0;
1328 
1329 	return __sev_platform_init_locked(&args->error);
1330 }
1331 
1332 int sev_platform_init(struct sev_platform_init_args *args)
1333 {
1334 	int rc;
1335 
1336 	mutex_lock(&sev_cmd_mutex);
1337 	rc = _sev_platform_init_locked(args);
1338 	mutex_unlock(&sev_cmd_mutex);
1339 
1340 	return rc;
1341 }
1342 EXPORT_SYMBOL_GPL(sev_platform_init);
1343 
1344 static int __sev_platform_shutdown_locked(int *error)
1345 {
1346 	struct psp_device *psp = psp_master;
1347 	struct sev_device *sev;
1348 	int ret;
1349 
1350 	if (!psp || !psp->sev_data)
1351 		return 0;
1352 
1353 	sev = psp->sev_data;
1354 
1355 	if (sev->state == SEV_STATE_UNINIT)
1356 		return 0;
1357 
1358 	ret = __sev_do_cmd_locked(SEV_CMD_SHUTDOWN, NULL, error);
1359 	if (ret)
1360 		return ret;
1361 
1362 	sev->state = SEV_STATE_UNINIT;
1363 	dev_dbg(sev->dev, "SEV firmware shutdown\n");
1364 
1365 	return ret;
1366 }
1367 
1368 static int sev_get_platform_state(int *state, int *error)
1369 {
1370 	struct sev_user_data_status data;
1371 	int rc;
1372 
1373 	rc = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, error);
1374 	if (rc)
1375 		return rc;
1376 
1377 	*state = data.state;
1378 	return rc;
1379 }
1380 
1381 static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable)
1382 {
1383 	int state, rc;
1384 
1385 	if (!writable)
1386 		return -EPERM;
1387 
1388 	/*
1389 	 * The SEV spec requires that FACTORY_RESET must be issued in
1390 	 * UNINIT state. Before we go further lets check if any guest is
1391 	 * active.
1392 	 *
1393 	 * If FW is in WORKING state then deny the request otherwise issue
1394 	 * SHUTDOWN command do INIT -> UNINIT before issuing the FACTORY_RESET.
1395 	 *
1396 	 */
1397 	rc = sev_get_platform_state(&state, &argp->error);
1398 	if (rc)
1399 		return rc;
1400 
1401 	if (state == SEV_STATE_WORKING)
1402 		return -EBUSY;
1403 
1404 	if (state == SEV_STATE_INIT) {
1405 		rc = __sev_platform_shutdown_locked(&argp->error);
1406 		if (rc)
1407 			return rc;
1408 	}
1409 
1410 	return __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error);
1411 }
1412 
1413 static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp)
1414 {
1415 	struct sev_user_data_status data;
1416 	int ret;
1417 
1418 	memset(&data, 0, sizeof(data));
1419 
1420 	ret = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, &argp->error);
1421 	if (ret)
1422 		return ret;
1423 
1424 	if (copy_to_user((void __user *)argp->data, &data, sizeof(data)))
1425 		ret = -EFAULT;
1426 
1427 	return ret;
1428 }
1429 
1430 static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool writable)
1431 {
1432 	struct sev_device *sev = psp_master->sev_data;
1433 	int rc;
1434 
1435 	if (!writable)
1436 		return -EPERM;
1437 
1438 	if (sev->state == SEV_STATE_UNINIT) {
1439 		rc = __sev_platform_init_locked(&argp->error);
1440 		if (rc)
1441 			return rc;
1442 	}
1443 
1444 	return __sev_do_cmd_locked(cmd, NULL, &argp->error);
1445 }
1446 
1447 static int sev_ioctl_do_pek_csr(struct sev_issue_cmd *argp, bool writable)
1448 {
1449 	struct sev_device *sev = psp_master->sev_data;
1450 	struct sev_user_data_pek_csr input;
1451 	struct sev_data_pek_csr data;
1452 	void __user *input_address;
1453 	void *blob = NULL;
1454 	int ret;
1455 
1456 	if (!writable)
1457 		return -EPERM;
1458 
1459 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1460 		return -EFAULT;
1461 
1462 	memset(&data, 0, sizeof(data));
1463 
1464 	/* userspace wants to query CSR length */
1465 	if (!input.address || !input.length)
1466 		goto cmd;
1467 
1468 	/* allocate a physically contiguous buffer to store the CSR blob */
1469 	input_address = (void __user *)input.address;
1470 	if (input.length > SEV_FW_BLOB_MAX_SIZE)
1471 		return -EFAULT;
1472 
1473 	blob = kzalloc(input.length, GFP_KERNEL);
1474 	if (!blob)
1475 		return -ENOMEM;
1476 
1477 	data.address = __psp_pa(blob);
1478 	data.len = input.length;
1479 
1480 cmd:
1481 	if (sev->state == SEV_STATE_UNINIT) {
1482 		ret = __sev_platform_init_locked(&argp->error);
1483 		if (ret)
1484 			goto e_free_blob;
1485 	}
1486 
1487 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CSR, &data, &argp->error);
1488 
1489 	 /* If we query the CSR length, FW responded with expected data. */
1490 	input.length = data.len;
1491 
1492 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1493 		ret = -EFAULT;
1494 		goto e_free_blob;
1495 	}
1496 
1497 	if (blob) {
1498 		if (copy_to_user(input_address, blob, input.length))
1499 			ret = -EFAULT;
1500 	}
1501 
1502 e_free_blob:
1503 	kfree(blob);
1504 	return ret;
1505 }
1506 
1507 void *psp_copy_user_blob(u64 uaddr, u32 len)
1508 {
1509 	if (!uaddr || !len)
1510 		return ERR_PTR(-EINVAL);
1511 
1512 	/* verify that blob length does not exceed our limit */
1513 	if (len > SEV_FW_BLOB_MAX_SIZE)
1514 		return ERR_PTR(-EINVAL);
1515 
1516 	return memdup_user((void __user *)uaddr, len);
1517 }
1518 EXPORT_SYMBOL_GPL(psp_copy_user_blob);
1519 
1520 static int sev_get_api_version(void)
1521 {
1522 	struct sev_device *sev = psp_master->sev_data;
1523 	struct sev_user_data_status status;
1524 	int error = 0, ret;
1525 
1526 	ret = sev_platform_status(&status, &error);
1527 	if (ret) {
1528 		dev_err(sev->dev,
1529 			"SEV: failed to get status. Error: %#x\n", error);
1530 		return 1;
1531 	}
1532 
1533 	sev->api_major = status.api_major;
1534 	sev->api_minor = status.api_minor;
1535 	sev->build = status.build;
1536 	sev->state = status.state;
1537 
1538 	return 0;
1539 }
1540 
1541 static int sev_get_firmware(struct device *dev,
1542 			    const struct firmware **firmware)
1543 {
1544 	char fw_name_specific[SEV_FW_NAME_SIZE];
1545 	char fw_name_subset[SEV_FW_NAME_SIZE];
1546 
1547 	snprintf(fw_name_specific, sizeof(fw_name_specific),
1548 		 "amd/amd_sev_fam%.2xh_model%.2xh.sbin",
1549 		 boot_cpu_data.x86, boot_cpu_data.x86_model);
1550 
1551 	snprintf(fw_name_subset, sizeof(fw_name_subset),
1552 		 "amd/amd_sev_fam%.2xh_model%.1xxh.sbin",
1553 		 boot_cpu_data.x86, (boot_cpu_data.x86_model & 0xf0) >> 4);
1554 
1555 	/* Check for SEV FW for a particular model.
1556 	 * Ex. amd_sev_fam17h_model00h.sbin for Family 17h Model 00h
1557 	 *
1558 	 * or
1559 	 *
1560 	 * Check for SEV FW common to a subset of models.
1561 	 * Ex. amd_sev_fam17h_model0xh.sbin for
1562 	 *     Family 17h Model 00h -- Family 17h Model 0Fh
1563 	 *
1564 	 * or
1565 	 *
1566 	 * Fall-back to using generic name: sev.fw
1567 	 */
1568 	if ((firmware_request_nowarn(firmware, fw_name_specific, dev) >= 0) ||
1569 	    (firmware_request_nowarn(firmware, fw_name_subset, dev) >= 0) ||
1570 	    (firmware_request_nowarn(firmware, SEV_FW_FILE, dev) >= 0))
1571 		return 0;
1572 
1573 	return -ENOENT;
1574 }
1575 
1576 /* Don't fail if SEV FW couldn't be updated. Continue with existing SEV FW */
1577 static int sev_update_firmware(struct device *dev)
1578 {
1579 	struct sev_data_download_firmware *data;
1580 	const struct firmware *firmware;
1581 	int ret, error, order;
1582 	struct page *p;
1583 	u64 data_size;
1584 
1585 	if (!sev_version_greater_or_equal(0, 15)) {
1586 		dev_dbg(dev, "DOWNLOAD_FIRMWARE not supported\n");
1587 		return -1;
1588 	}
1589 
1590 	if (sev_get_firmware(dev, &firmware) == -ENOENT) {
1591 		dev_dbg(dev, "No SEV firmware file present\n");
1592 		return -1;
1593 	}
1594 
1595 	/*
1596 	 * SEV FW expects the physical address given to it to be 32
1597 	 * byte aligned. Memory allocated has structure placed at the
1598 	 * beginning followed by the firmware being passed to the SEV
1599 	 * FW. Allocate enough memory for data structure + alignment
1600 	 * padding + SEV FW.
1601 	 */
1602 	data_size = ALIGN(sizeof(struct sev_data_download_firmware), 32);
1603 
1604 	order = get_order(firmware->size + data_size);
1605 	p = alloc_pages(GFP_KERNEL, order);
1606 	if (!p) {
1607 		ret = -1;
1608 		goto fw_err;
1609 	}
1610 
1611 	/*
1612 	 * Copy firmware data to a kernel allocated contiguous
1613 	 * memory region.
1614 	 */
1615 	data = page_address(p);
1616 	memcpy(page_address(p) + data_size, firmware->data, firmware->size);
1617 
1618 	data->address = __psp_pa(page_address(p) + data_size);
1619 	data->len = firmware->size;
1620 
1621 	ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, data, &error);
1622 
1623 	/*
1624 	 * A quirk for fixing the committed TCB version, when upgrading from
1625 	 * earlier firmware version than 1.50.
1626 	 */
1627 	if (!ret && !sev_version_greater_or_equal(1, 50))
1628 		ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, data, &error);
1629 
1630 	if (ret)
1631 		dev_dbg(dev, "Failed to update SEV firmware: %#x\n", error);
1632 	else
1633 		dev_info(dev, "SEV firmware update successful\n");
1634 
1635 	__free_pages(p, order);
1636 
1637 fw_err:
1638 	release_firmware(firmware);
1639 
1640 	return ret;
1641 }
1642 
1643 static int __sev_snp_shutdown_locked(int *error, bool panic)
1644 {
1645 	struct psp_device *psp = psp_master;
1646 	struct sev_device *sev;
1647 	struct sev_data_snp_shutdown_ex data;
1648 	int ret;
1649 
1650 	if (!psp || !psp->sev_data)
1651 		return 0;
1652 
1653 	sev = psp->sev_data;
1654 
1655 	if (!sev->snp_initialized)
1656 		return 0;
1657 
1658 	memset(&data, 0, sizeof(data));
1659 	data.len = sizeof(data);
1660 	data.iommu_snp_shutdown = 1;
1661 
1662 	/*
1663 	 * If invoked during panic handling, local interrupts are disabled
1664 	 * and all CPUs are stopped, so wbinvd_on_all_cpus() can't be called.
1665 	 * In that case, a wbinvd() is done on remote CPUs via the NMI
1666 	 * callback, so only a local wbinvd() is needed here.
1667 	 */
1668 	if (!panic)
1669 		wbinvd_on_all_cpus();
1670 	else
1671 		wbinvd();
1672 
1673 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data, error);
1674 	/* SHUTDOWN may require DF_FLUSH */
1675 	if (*error == SEV_RET_DFFLUSH_REQUIRED) {
1676 		ret = __sev_do_cmd_locked(SEV_CMD_SNP_DF_FLUSH, NULL, NULL);
1677 		if (ret) {
1678 			dev_err(sev->dev, "SEV-SNP DF_FLUSH failed\n");
1679 			return ret;
1680 		}
1681 		/* reissue the shutdown command */
1682 		ret = __sev_do_cmd_locked(SEV_CMD_SNP_SHUTDOWN_EX, &data,
1683 					  error);
1684 	}
1685 	if (ret) {
1686 		dev_err(sev->dev, "SEV-SNP firmware shutdown failed\n");
1687 		return ret;
1688 	}
1689 
1690 	/*
1691 	 * SNP_SHUTDOWN_EX with IOMMU_SNP_SHUTDOWN set to 1 disables SNP
1692 	 * enforcement by the IOMMU and also transitions all pages
1693 	 * associated with the IOMMU to the Reclaim state.
1694 	 * Firmware was transitioning the IOMMU pages to Hypervisor state
1695 	 * before version 1.53. But, accounting for the number of assigned
1696 	 * 4kB pages in a 2M page was done incorrectly by not transitioning
1697 	 * to the Reclaim state. This resulted in RMP #PF when later accessing
1698 	 * the 2M page containing those pages during kexec boot. Hence, the
1699 	 * firmware now transitions these pages to Reclaim state and hypervisor
1700 	 * needs to transition these pages to shared state. SNP Firmware
1701 	 * version 1.53 and above are needed for kexec boot.
1702 	 */
1703 	ret = amd_iommu_snp_disable();
1704 	if (ret) {
1705 		dev_err(sev->dev, "SNP IOMMU shutdown failed\n");
1706 		return ret;
1707 	}
1708 
1709 	sev->snp_initialized = false;
1710 	dev_dbg(sev->dev, "SEV-SNP firmware shutdown\n");
1711 
1712 	return ret;
1713 }
1714 
1715 static int sev_ioctl_do_pek_import(struct sev_issue_cmd *argp, bool writable)
1716 {
1717 	struct sev_device *sev = psp_master->sev_data;
1718 	struct sev_user_data_pek_cert_import input;
1719 	struct sev_data_pek_cert_import data;
1720 	void *pek_blob, *oca_blob;
1721 	int ret;
1722 
1723 	if (!writable)
1724 		return -EPERM;
1725 
1726 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1727 		return -EFAULT;
1728 
1729 	/* copy PEK certificate blobs from userspace */
1730 	pek_blob = psp_copy_user_blob(input.pek_cert_address, input.pek_cert_len);
1731 	if (IS_ERR(pek_blob))
1732 		return PTR_ERR(pek_blob);
1733 
1734 	data.reserved = 0;
1735 	data.pek_cert_address = __psp_pa(pek_blob);
1736 	data.pek_cert_len = input.pek_cert_len;
1737 
1738 	/* copy PEK certificate blobs from userspace */
1739 	oca_blob = psp_copy_user_blob(input.oca_cert_address, input.oca_cert_len);
1740 	if (IS_ERR(oca_blob)) {
1741 		ret = PTR_ERR(oca_blob);
1742 		goto e_free_pek;
1743 	}
1744 
1745 	data.oca_cert_address = __psp_pa(oca_blob);
1746 	data.oca_cert_len = input.oca_cert_len;
1747 
1748 	/* If platform is not in INIT state then transition it to INIT */
1749 	if (sev->state != SEV_STATE_INIT) {
1750 		ret = __sev_platform_init_locked(&argp->error);
1751 		if (ret)
1752 			goto e_free_oca;
1753 	}
1754 
1755 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CERT_IMPORT, &data, &argp->error);
1756 
1757 e_free_oca:
1758 	kfree(oca_blob);
1759 e_free_pek:
1760 	kfree(pek_blob);
1761 	return ret;
1762 }
1763 
1764 static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp)
1765 {
1766 	struct sev_user_data_get_id2 input;
1767 	struct sev_data_get_id data;
1768 	void __user *input_address;
1769 	void *id_blob = NULL;
1770 	int ret;
1771 
1772 	/* SEV GET_ID is available from SEV API v0.16 and up */
1773 	if (!sev_version_greater_or_equal(0, 16))
1774 		return -ENOTSUPP;
1775 
1776 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1777 		return -EFAULT;
1778 
1779 	input_address = (void __user *)input.address;
1780 
1781 	if (input.address && input.length) {
1782 		/*
1783 		 * The length of the ID shouldn't be assumed by software since
1784 		 * it may change in the future.  The allocation size is limited
1785 		 * to 1 << (PAGE_SHIFT + MAX_PAGE_ORDER) by the page allocator.
1786 		 * If the allocation fails, simply return ENOMEM rather than
1787 		 * warning in the kernel log.
1788 		 */
1789 		id_blob = kzalloc(input.length, GFP_KERNEL | __GFP_NOWARN);
1790 		if (!id_blob)
1791 			return -ENOMEM;
1792 
1793 		data.address = __psp_pa(id_blob);
1794 		data.len = input.length;
1795 	} else {
1796 		data.address = 0;
1797 		data.len = 0;
1798 	}
1799 
1800 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, &data, &argp->error);
1801 
1802 	/*
1803 	 * Firmware will return the length of the ID value (either the minimum
1804 	 * required length or the actual length written), return it to the user.
1805 	 */
1806 	input.length = data.len;
1807 
1808 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1809 		ret = -EFAULT;
1810 		goto e_free;
1811 	}
1812 
1813 	if (id_blob) {
1814 		if (copy_to_user(input_address, id_blob, data.len)) {
1815 			ret = -EFAULT;
1816 			goto e_free;
1817 		}
1818 	}
1819 
1820 e_free:
1821 	kfree(id_blob);
1822 
1823 	return ret;
1824 }
1825 
1826 static int sev_ioctl_do_get_id(struct sev_issue_cmd *argp)
1827 {
1828 	struct sev_data_get_id *data;
1829 	u64 data_size, user_size;
1830 	void *id_blob, *mem;
1831 	int ret;
1832 
1833 	/* SEV GET_ID available from SEV API v0.16 and up */
1834 	if (!sev_version_greater_or_equal(0, 16))
1835 		return -ENOTSUPP;
1836 
1837 	/* SEV FW expects the buffer it fills with the ID to be
1838 	 * 8-byte aligned. Memory allocated should be enough to
1839 	 * hold data structure + alignment padding + memory
1840 	 * where SEV FW writes the ID.
1841 	 */
1842 	data_size = ALIGN(sizeof(struct sev_data_get_id), 8);
1843 	user_size = sizeof(struct sev_user_data_get_id);
1844 
1845 	mem = kzalloc(data_size + user_size, GFP_KERNEL);
1846 	if (!mem)
1847 		return -ENOMEM;
1848 
1849 	data = mem;
1850 	id_blob = mem + data_size;
1851 
1852 	data->address = __psp_pa(id_blob);
1853 	data->len = user_size;
1854 
1855 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, data, &argp->error);
1856 	if (!ret) {
1857 		if (copy_to_user((void __user *)argp->data, id_blob, data->len))
1858 			ret = -EFAULT;
1859 	}
1860 
1861 	kfree(mem);
1862 
1863 	return ret;
1864 }
1865 
1866 static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable)
1867 {
1868 	struct sev_device *sev = psp_master->sev_data;
1869 	struct sev_user_data_pdh_cert_export input;
1870 	void *pdh_blob = NULL, *cert_blob = NULL;
1871 	struct sev_data_pdh_cert_export data;
1872 	void __user *input_cert_chain_address;
1873 	void __user *input_pdh_cert_address;
1874 	int ret;
1875 
1876 	/* If platform is not in INIT state then transition it to INIT. */
1877 	if (sev->state != SEV_STATE_INIT) {
1878 		if (!writable)
1879 			return -EPERM;
1880 
1881 		ret = __sev_platform_init_locked(&argp->error);
1882 		if (ret)
1883 			return ret;
1884 	}
1885 
1886 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
1887 		return -EFAULT;
1888 
1889 	memset(&data, 0, sizeof(data));
1890 
1891 	/* Userspace wants to query the certificate length. */
1892 	if (!input.pdh_cert_address ||
1893 	    !input.pdh_cert_len ||
1894 	    !input.cert_chain_address)
1895 		goto cmd;
1896 
1897 	input_pdh_cert_address = (void __user *)input.pdh_cert_address;
1898 	input_cert_chain_address = (void __user *)input.cert_chain_address;
1899 
1900 	/* Allocate a physically contiguous buffer to store the PDH blob. */
1901 	if (input.pdh_cert_len > SEV_FW_BLOB_MAX_SIZE)
1902 		return -EFAULT;
1903 
1904 	/* Allocate a physically contiguous buffer to store the cert chain blob. */
1905 	if (input.cert_chain_len > SEV_FW_BLOB_MAX_SIZE)
1906 		return -EFAULT;
1907 
1908 	pdh_blob = kzalloc(input.pdh_cert_len, GFP_KERNEL);
1909 	if (!pdh_blob)
1910 		return -ENOMEM;
1911 
1912 	data.pdh_cert_address = __psp_pa(pdh_blob);
1913 	data.pdh_cert_len = input.pdh_cert_len;
1914 
1915 	cert_blob = kzalloc(input.cert_chain_len, GFP_KERNEL);
1916 	if (!cert_blob) {
1917 		ret = -ENOMEM;
1918 		goto e_free_pdh;
1919 	}
1920 
1921 	data.cert_chain_address = __psp_pa(cert_blob);
1922 	data.cert_chain_len = input.cert_chain_len;
1923 
1924 cmd:
1925 	ret = __sev_do_cmd_locked(SEV_CMD_PDH_CERT_EXPORT, &data, &argp->error);
1926 
1927 	/* If we query the length, FW responded with expected data. */
1928 	input.cert_chain_len = data.cert_chain_len;
1929 	input.pdh_cert_len = data.pdh_cert_len;
1930 
1931 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
1932 		ret = -EFAULT;
1933 		goto e_free_cert;
1934 	}
1935 
1936 	if (pdh_blob) {
1937 		if (copy_to_user(input_pdh_cert_address,
1938 				 pdh_blob, input.pdh_cert_len)) {
1939 			ret = -EFAULT;
1940 			goto e_free_cert;
1941 		}
1942 	}
1943 
1944 	if (cert_blob) {
1945 		if (copy_to_user(input_cert_chain_address,
1946 				 cert_blob, input.cert_chain_len))
1947 			ret = -EFAULT;
1948 	}
1949 
1950 e_free_cert:
1951 	kfree(cert_blob);
1952 e_free_pdh:
1953 	kfree(pdh_blob);
1954 	return ret;
1955 }
1956 
1957 static int sev_ioctl_do_snp_platform_status(struct sev_issue_cmd *argp)
1958 {
1959 	struct sev_device *sev = psp_master->sev_data;
1960 	struct sev_data_snp_addr buf;
1961 	struct page *status_page;
1962 	void *data;
1963 	int ret;
1964 
1965 	if (!sev->snp_initialized || !argp->data)
1966 		return -EINVAL;
1967 
1968 	status_page = alloc_page(GFP_KERNEL_ACCOUNT);
1969 	if (!status_page)
1970 		return -ENOMEM;
1971 
1972 	data = page_address(status_page);
1973 
1974 	/*
1975 	 * Firmware expects status page to be in firmware-owned state, otherwise
1976 	 * it will report firmware error code INVALID_PAGE_STATE (0x1A).
1977 	 */
1978 	if (rmp_mark_pages_firmware(__pa(data), 1, true)) {
1979 		ret = -EFAULT;
1980 		goto cleanup;
1981 	}
1982 
1983 	buf.address = __psp_pa(data);
1984 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_PLATFORM_STATUS, &buf, &argp->error);
1985 
1986 	/*
1987 	 * Status page will be transitioned to Reclaim state upon success, or
1988 	 * left in Firmware state in failure. Use snp_reclaim_pages() to
1989 	 * transition either case back to Hypervisor-owned state.
1990 	 */
1991 	if (snp_reclaim_pages(__pa(data), 1, true))
1992 		return -EFAULT;
1993 
1994 	if (ret)
1995 		goto cleanup;
1996 
1997 	if (copy_to_user((void __user *)argp->data, data,
1998 			 sizeof(struct sev_user_data_snp_status)))
1999 		ret = -EFAULT;
2000 
2001 cleanup:
2002 	__free_pages(status_page, 0);
2003 	return ret;
2004 }
2005 
2006 static int sev_ioctl_do_snp_commit(struct sev_issue_cmd *argp)
2007 {
2008 	struct sev_device *sev = psp_master->sev_data;
2009 	struct sev_data_snp_commit buf;
2010 
2011 	if (!sev->snp_initialized)
2012 		return -EINVAL;
2013 
2014 	buf.len = sizeof(buf);
2015 
2016 	return __sev_do_cmd_locked(SEV_CMD_SNP_COMMIT, &buf, &argp->error);
2017 }
2018 
2019 static int sev_ioctl_do_snp_set_config(struct sev_issue_cmd *argp, bool writable)
2020 {
2021 	struct sev_device *sev = psp_master->sev_data;
2022 	struct sev_user_data_snp_config config;
2023 
2024 	if (!sev->snp_initialized || !argp->data)
2025 		return -EINVAL;
2026 
2027 	if (!writable)
2028 		return -EPERM;
2029 
2030 	if (copy_from_user(&config, (void __user *)argp->data, sizeof(config)))
2031 		return -EFAULT;
2032 
2033 	return __sev_do_cmd_locked(SEV_CMD_SNP_CONFIG, &config, &argp->error);
2034 }
2035 
2036 static int sev_ioctl_do_snp_vlek_load(struct sev_issue_cmd *argp, bool writable)
2037 {
2038 	struct sev_device *sev = psp_master->sev_data;
2039 	struct sev_user_data_snp_vlek_load input;
2040 	void *blob;
2041 	int ret;
2042 
2043 	if (!sev->snp_initialized || !argp->data)
2044 		return -EINVAL;
2045 
2046 	if (!writable)
2047 		return -EPERM;
2048 
2049 	if (copy_from_user(&input, u64_to_user_ptr(argp->data), sizeof(input)))
2050 		return -EFAULT;
2051 
2052 	if (input.len != sizeof(input) || input.vlek_wrapped_version != 0)
2053 		return -EINVAL;
2054 
2055 	blob = psp_copy_user_blob(input.vlek_wrapped_address,
2056 				  sizeof(struct sev_user_data_snp_wrapped_vlek_hashstick));
2057 	if (IS_ERR(blob))
2058 		return PTR_ERR(blob);
2059 
2060 	input.vlek_wrapped_address = __psp_pa(blob);
2061 
2062 	ret = __sev_do_cmd_locked(SEV_CMD_SNP_VLEK_LOAD, &input, &argp->error);
2063 
2064 	kfree(blob);
2065 
2066 	return ret;
2067 }
2068 
2069 static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)
2070 {
2071 	void __user *argp = (void __user *)arg;
2072 	struct sev_issue_cmd input;
2073 	int ret = -EFAULT;
2074 	bool writable = file->f_mode & FMODE_WRITE;
2075 
2076 	if (!psp_master || !psp_master->sev_data)
2077 		return -ENODEV;
2078 
2079 	if (ioctl != SEV_ISSUE_CMD)
2080 		return -EINVAL;
2081 
2082 	if (copy_from_user(&input, argp, sizeof(struct sev_issue_cmd)))
2083 		return -EFAULT;
2084 
2085 	if (input.cmd > SEV_MAX)
2086 		return -EINVAL;
2087 
2088 	mutex_lock(&sev_cmd_mutex);
2089 
2090 	switch (input.cmd) {
2091 
2092 	case SEV_FACTORY_RESET:
2093 		ret = sev_ioctl_do_reset(&input, writable);
2094 		break;
2095 	case SEV_PLATFORM_STATUS:
2096 		ret = sev_ioctl_do_platform_status(&input);
2097 		break;
2098 	case SEV_PEK_GEN:
2099 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PEK_GEN, &input, writable);
2100 		break;
2101 	case SEV_PDH_GEN:
2102 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PDH_GEN, &input, writable);
2103 		break;
2104 	case SEV_PEK_CSR:
2105 		ret = sev_ioctl_do_pek_csr(&input, writable);
2106 		break;
2107 	case SEV_PEK_CERT_IMPORT:
2108 		ret = sev_ioctl_do_pek_import(&input, writable);
2109 		break;
2110 	case SEV_PDH_CERT_EXPORT:
2111 		ret = sev_ioctl_do_pdh_export(&input, writable);
2112 		break;
2113 	case SEV_GET_ID:
2114 		pr_warn_once("SEV_GET_ID command is deprecated, use SEV_GET_ID2\n");
2115 		ret = sev_ioctl_do_get_id(&input);
2116 		break;
2117 	case SEV_GET_ID2:
2118 		ret = sev_ioctl_do_get_id2(&input);
2119 		break;
2120 	case SNP_PLATFORM_STATUS:
2121 		ret = sev_ioctl_do_snp_platform_status(&input);
2122 		break;
2123 	case SNP_COMMIT:
2124 		ret = sev_ioctl_do_snp_commit(&input);
2125 		break;
2126 	case SNP_SET_CONFIG:
2127 		ret = sev_ioctl_do_snp_set_config(&input, writable);
2128 		break;
2129 	case SNP_VLEK_LOAD:
2130 		ret = sev_ioctl_do_snp_vlek_load(&input, writable);
2131 		break;
2132 	default:
2133 		ret = -EINVAL;
2134 		goto out;
2135 	}
2136 
2137 	if (copy_to_user(argp, &input, sizeof(struct sev_issue_cmd)))
2138 		ret = -EFAULT;
2139 out:
2140 	mutex_unlock(&sev_cmd_mutex);
2141 
2142 	return ret;
2143 }
2144 
2145 static const struct file_operations sev_fops = {
2146 	.owner	= THIS_MODULE,
2147 	.unlocked_ioctl = sev_ioctl,
2148 };
2149 
2150 int sev_platform_status(struct sev_user_data_status *data, int *error)
2151 {
2152 	return sev_do_cmd(SEV_CMD_PLATFORM_STATUS, data, error);
2153 }
2154 EXPORT_SYMBOL_GPL(sev_platform_status);
2155 
2156 int sev_guest_deactivate(struct sev_data_deactivate *data, int *error)
2157 {
2158 	return sev_do_cmd(SEV_CMD_DEACTIVATE, data, error);
2159 }
2160 EXPORT_SYMBOL_GPL(sev_guest_deactivate);
2161 
2162 int sev_guest_activate(struct sev_data_activate *data, int *error)
2163 {
2164 	return sev_do_cmd(SEV_CMD_ACTIVATE, data, error);
2165 }
2166 EXPORT_SYMBOL_GPL(sev_guest_activate);
2167 
2168 int sev_guest_decommission(struct sev_data_decommission *data, int *error)
2169 {
2170 	return sev_do_cmd(SEV_CMD_DECOMMISSION, data, error);
2171 }
2172 EXPORT_SYMBOL_GPL(sev_guest_decommission);
2173 
2174 int sev_guest_df_flush(int *error)
2175 {
2176 	return sev_do_cmd(SEV_CMD_DF_FLUSH, NULL, error);
2177 }
2178 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
2179 
2180 static void sev_exit(struct kref *ref)
2181 {
2182 	misc_deregister(&misc_dev->misc);
2183 	kfree(misc_dev);
2184 	misc_dev = NULL;
2185 }
2186 
2187 static int sev_misc_init(struct sev_device *sev)
2188 {
2189 	struct device *dev = sev->dev;
2190 	int ret;
2191 
2192 	/*
2193 	 * SEV feature support can be detected on multiple devices but the SEV
2194 	 * FW commands must be issued on the master. During probe, we do not
2195 	 * know the master hence we create /dev/sev on the first device probe.
2196 	 * sev_do_cmd() finds the right master device to which to issue the
2197 	 * command to the firmware.
2198 	 */
2199 	if (!misc_dev) {
2200 		struct miscdevice *misc;
2201 
2202 		misc_dev = kzalloc(sizeof(*misc_dev), GFP_KERNEL);
2203 		if (!misc_dev)
2204 			return -ENOMEM;
2205 
2206 		misc = &misc_dev->misc;
2207 		misc->minor = MISC_DYNAMIC_MINOR;
2208 		misc->name = DEVICE_NAME;
2209 		misc->fops = &sev_fops;
2210 
2211 		ret = misc_register(misc);
2212 		if (ret)
2213 			return ret;
2214 
2215 		kref_init(&misc_dev->refcount);
2216 	} else {
2217 		kref_get(&misc_dev->refcount);
2218 	}
2219 
2220 	init_waitqueue_head(&sev->int_queue);
2221 	sev->misc = misc_dev;
2222 	dev_dbg(dev, "registered SEV device\n");
2223 
2224 	return 0;
2225 }
2226 
2227 int sev_dev_init(struct psp_device *psp)
2228 {
2229 	struct device *dev = psp->dev;
2230 	struct sev_device *sev;
2231 	int ret = -ENOMEM;
2232 
2233 	if (!boot_cpu_has(X86_FEATURE_SEV)) {
2234 		dev_info_once(dev, "SEV: memory encryption not enabled by BIOS\n");
2235 		return 0;
2236 	}
2237 
2238 	sev = devm_kzalloc(dev, sizeof(*sev), GFP_KERNEL);
2239 	if (!sev)
2240 		goto e_err;
2241 
2242 	sev->cmd_buf = (void *)devm_get_free_pages(dev, GFP_KERNEL, 1);
2243 	if (!sev->cmd_buf)
2244 		goto e_sev;
2245 
2246 	sev->cmd_buf_backup = (uint8_t *)sev->cmd_buf + PAGE_SIZE;
2247 
2248 	psp->sev_data = sev;
2249 
2250 	sev->dev = dev;
2251 	sev->psp = psp;
2252 
2253 	sev->io_regs = psp->io_regs;
2254 
2255 	sev->vdata = (struct sev_vdata *)psp->vdata->sev;
2256 	if (!sev->vdata) {
2257 		ret = -ENODEV;
2258 		dev_err(dev, "sev: missing driver data\n");
2259 		goto e_buf;
2260 	}
2261 
2262 	psp_set_sev_irq_handler(psp, sev_irq_handler, sev);
2263 
2264 	ret = sev_misc_init(sev);
2265 	if (ret)
2266 		goto e_irq;
2267 
2268 	dev_notice(dev, "sev enabled\n");
2269 
2270 	return 0;
2271 
2272 e_irq:
2273 	psp_clear_sev_irq_handler(psp);
2274 e_buf:
2275 	devm_free_pages(dev, (unsigned long)sev->cmd_buf);
2276 e_sev:
2277 	devm_kfree(dev, sev);
2278 e_err:
2279 	psp->sev_data = NULL;
2280 
2281 	dev_notice(dev, "sev initialization failed\n");
2282 
2283 	return ret;
2284 }
2285 
2286 static void __sev_firmware_shutdown(struct sev_device *sev, bool panic)
2287 {
2288 	int error;
2289 
2290 	__sev_platform_shutdown_locked(NULL);
2291 
2292 	if (sev_es_tmr) {
2293 		/*
2294 		 * The TMR area was encrypted, flush it from the cache.
2295 		 *
2296 		 * If invoked during panic handling, local interrupts are
2297 		 * disabled and all CPUs are stopped, so wbinvd_on_all_cpus()
2298 		 * can't be used. In that case, wbinvd() is done on remote CPUs
2299 		 * via the NMI callback, and done for this CPU later during
2300 		 * SNP shutdown, so wbinvd_on_all_cpus() can be skipped.
2301 		 */
2302 		if (!panic)
2303 			wbinvd_on_all_cpus();
2304 
2305 		__snp_free_firmware_pages(virt_to_page(sev_es_tmr),
2306 					  get_order(sev_es_tmr_size),
2307 					  true);
2308 		sev_es_tmr = NULL;
2309 	}
2310 
2311 	if (sev_init_ex_buffer) {
2312 		__snp_free_firmware_pages(virt_to_page(sev_init_ex_buffer),
2313 					  get_order(NV_LENGTH),
2314 					  true);
2315 		sev_init_ex_buffer = NULL;
2316 	}
2317 
2318 	if (snp_range_list) {
2319 		kfree(snp_range_list);
2320 		snp_range_list = NULL;
2321 	}
2322 
2323 	__sev_snp_shutdown_locked(&error, panic);
2324 }
2325 
2326 static void sev_firmware_shutdown(struct sev_device *sev)
2327 {
2328 	mutex_lock(&sev_cmd_mutex);
2329 	__sev_firmware_shutdown(sev, false);
2330 	mutex_unlock(&sev_cmd_mutex);
2331 }
2332 
2333 void sev_dev_destroy(struct psp_device *psp)
2334 {
2335 	struct sev_device *sev = psp->sev_data;
2336 
2337 	if (!sev)
2338 		return;
2339 
2340 	sev_firmware_shutdown(sev);
2341 
2342 	if (sev->misc)
2343 		kref_put(&misc_dev->refcount, sev_exit);
2344 
2345 	psp_clear_sev_irq_handler(psp);
2346 }
2347 
2348 static int snp_shutdown_on_panic(struct notifier_block *nb,
2349 				 unsigned long reason, void *arg)
2350 {
2351 	struct sev_device *sev = psp_master->sev_data;
2352 
2353 	/*
2354 	 * If sev_cmd_mutex is already acquired, then it's likely
2355 	 * another PSP command is in flight and issuing a shutdown
2356 	 * would fail in unexpected ways. Rather than create even
2357 	 * more confusion during a panic, just bail out here.
2358 	 */
2359 	if (mutex_is_locked(&sev_cmd_mutex))
2360 		return NOTIFY_DONE;
2361 
2362 	__sev_firmware_shutdown(sev, true);
2363 
2364 	return NOTIFY_DONE;
2365 }
2366 
2367 static struct notifier_block snp_panic_notifier = {
2368 	.notifier_call = snp_shutdown_on_panic,
2369 };
2370 
2371 int sev_issue_cmd_external_user(struct file *filep, unsigned int cmd,
2372 				void *data, int *error)
2373 {
2374 	if (!filep || filep->f_op != &sev_fops)
2375 		return -EBADF;
2376 
2377 	return sev_do_cmd(cmd, data, error);
2378 }
2379 EXPORT_SYMBOL_GPL(sev_issue_cmd_external_user);
2380 
2381 void sev_pci_init(void)
2382 {
2383 	struct sev_device *sev = psp_master->sev_data;
2384 	struct sev_platform_init_args args = {0};
2385 	int rc;
2386 
2387 	if (!sev)
2388 		return;
2389 
2390 	psp_timeout = psp_probe_timeout;
2391 
2392 	if (sev_get_api_version())
2393 		goto err;
2394 
2395 	if (sev_update_firmware(sev->dev) == 0)
2396 		sev_get_api_version();
2397 
2398 	/* Initialize the platform */
2399 	args.probe = true;
2400 	rc = sev_platform_init(&args);
2401 	if (rc)
2402 		dev_err(sev->dev, "SEV: failed to INIT error %#x, rc %d\n",
2403 			args.error, rc);
2404 
2405 	dev_info(sev->dev, "SEV%s API:%d.%d build:%d\n", sev->snp_initialized ?
2406 		"-SNP" : "", sev->api_major, sev->api_minor, sev->build);
2407 
2408 	atomic_notifier_chain_register(&panic_notifier_list,
2409 				       &snp_panic_notifier);
2410 	return;
2411 
2412 err:
2413 	psp_master->sev_data = NULL;
2414 }
2415 
2416 void sev_pci_exit(void)
2417 {
2418 	struct sev_device *sev = psp_master->sev_data;
2419 
2420 	if (!sev)
2421 		return;
2422 
2423 	sev_firmware_shutdown(sev);
2424 
2425 	atomic_notifier_chain_unregister(&panic_notifier_list,
2426 					 &snp_panic_notifier);
2427 }
2428