xref: /linux/drivers/crypto/ccp/sev-dev.c (revision 34f7c6e7d4396090692a09789db231e12cb4762b)
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/module.h>
11 #include <linux/kernel.h>
12 #include <linux/kthread.h>
13 #include <linux/sched.h>
14 #include <linux/interrupt.h>
15 #include <linux/spinlock.h>
16 #include <linux/spinlock_types.h>
17 #include <linux/types.h>
18 #include <linux/mutex.h>
19 #include <linux/delay.h>
20 #include <linux/hw_random.h>
21 #include <linux/ccp.h>
22 #include <linux/firmware.h>
23 #include <linux/gfp.h>
24 #include <linux/cpufeature.h>
25 #include <linux/fs.h>
26 
27 #include <asm/smp.h>
28 
29 #include "psp-dev.h"
30 #include "sev-dev.h"
31 
32 #define DEVICE_NAME		"sev"
33 #define SEV_FW_FILE		"amd/sev.fw"
34 #define SEV_FW_NAME_SIZE	64
35 
36 static DEFINE_MUTEX(sev_cmd_mutex);
37 static struct sev_misc_dev *misc_dev;
38 
39 static int psp_cmd_timeout = 100;
40 module_param(psp_cmd_timeout, int, 0644);
41 MODULE_PARM_DESC(psp_cmd_timeout, " default timeout value, in seconds, for PSP commands");
42 
43 static int psp_probe_timeout = 5;
44 module_param(psp_probe_timeout, int, 0644);
45 MODULE_PARM_DESC(psp_probe_timeout, " default timeout value, in seconds, during PSP device probe");
46 
47 static char *init_ex_path;
48 module_param(init_ex_path, charp, 0444);
49 MODULE_PARM_DESC(init_ex_path, " Path for INIT_EX data; if set try INIT_EX");
50 
51 static bool psp_init_on_probe = true;
52 module_param(psp_init_on_probe, bool, 0444);
53 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");
54 
55 MODULE_FIRMWARE("amd/amd_sev_fam17h_model0xh.sbin"); /* 1st gen EPYC */
56 MODULE_FIRMWARE("amd/amd_sev_fam17h_model3xh.sbin"); /* 2nd gen EPYC */
57 MODULE_FIRMWARE("amd/amd_sev_fam19h_model0xh.sbin"); /* 3rd gen EPYC */
58 
59 static bool psp_dead;
60 static int psp_timeout;
61 
62 /* Trusted Memory Region (TMR):
63  *   The TMR is a 1MB area that must be 1MB aligned.  Use the page allocator
64  *   to allocate the memory, which will return aligned memory for the specified
65  *   allocation order.
66  */
67 #define SEV_ES_TMR_SIZE		(1024 * 1024)
68 static void *sev_es_tmr;
69 
70 /* INIT_EX NV Storage:
71  *   The NV Storage is a 32Kb area and must be 4Kb page aligned.  Use the page
72  *   allocator to allocate the memory, which will return aligned memory for the
73  *   specified allocation order.
74  */
75 #define NV_LENGTH (32 * 1024)
76 static void *sev_init_ex_buffer;
77 
78 static inline bool sev_version_greater_or_equal(u8 maj, u8 min)
79 {
80 	struct sev_device *sev = psp_master->sev_data;
81 
82 	if (sev->api_major > maj)
83 		return true;
84 
85 	if (sev->api_major == maj && sev->api_minor >= min)
86 		return true;
87 
88 	return false;
89 }
90 
91 static void sev_irq_handler(int irq, void *data, unsigned int status)
92 {
93 	struct sev_device *sev = data;
94 	int reg;
95 
96 	/* Check if it is command completion: */
97 	if (!(status & SEV_CMD_COMPLETE))
98 		return;
99 
100 	/* Check if it is SEV command completion: */
101 	reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
102 	if (reg & PSP_CMDRESP_RESP) {
103 		sev->int_rcvd = 1;
104 		wake_up(&sev->int_queue);
105 	}
106 }
107 
108 static int sev_wait_cmd_ioc(struct sev_device *sev,
109 			    unsigned int *reg, unsigned int timeout)
110 {
111 	int ret;
112 
113 	ret = wait_event_timeout(sev->int_queue,
114 			sev->int_rcvd, timeout * HZ);
115 	if (!ret)
116 		return -ETIMEDOUT;
117 
118 	*reg = ioread32(sev->io_regs + sev->vdata->cmdresp_reg);
119 
120 	return 0;
121 }
122 
123 static int sev_cmd_buffer_len(int cmd)
124 {
125 	switch (cmd) {
126 	case SEV_CMD_INIT:			return sizeof(struct sev_data_init);
127 	case SEV_CMD_INIT_EX:                   return sizeof(struct sev_data_init_ex);
128 	case SEV_CMD_PLATFORM_STATUS:		return sizeof(struct sev_user_data_status);
129 	case SEV_CMD_PEK_CSR:			return sizeof(struct sev_data_pek_csr);
130 	case SEV_CMD_PEK_CERT_IMPORT:		return sizeof(struct sev_data_pek_cert_import);
131 	case SEV_CMD_PDH_CERT_EXPORT:		return sizeof(struct sev_data_pdh_cert_export);
132 	case SEV_CMD_LAUNCH_START:		return sizeof(struct sev_data_launch_start);
133 	case SEV_CMD_LAUNCH_UPDATE_DATA:	return sizeof(struct sev_data_launch_update_data);
134 	case SEV_CMD_LAUNCH_UPDATE_VMSA:	return sizeof(struct sev_data_launch_update_vmsa);
135 	case SEV_CMD_LAUNCH_FINISH:		return sizeof(struct sev_data_launch_finish);
136 	case SEV_CMD_LAUNCH_MEASURE:		return sizeof(struct sev_data_launch_measure);
137 	case SEV_CMD_ACTIVATE:			return sizeof(struct sev_data_activate);
138 	case SEV_CMD_DEACTIVATE:		return sizeof(struct sev_data_deactivate);
139 	case SEV_CMD_DECOMMISSION:		return sizeof(struct sev_data_decommission);
140 	case SEV_CMD_GUEST_STATUS:		return sizeof(struct sev_data_guest_status);
141 	case SEV_CMD_DBG_DECRYPT:		return sizeof(struct sev_data_dbg);
142 	case SEV_CMD_DBG_ENCRYPT:		return sizeof(struct sev_data_dbg);
143 	case SEV_CMD_SEND_START:		return sizeof(struct sev_data_send_start);
144 	case SEV_CMD_SEND_UPDATE_DATA:		return sizeof(struct sev_data_send_update_data);
145 	case SEV_CMD_SEND_UPDATE_VMSA:		return sizeof(struct sev_data_send_update_vmsa);
146 	case SEV_CMD_SEND_FINISH:		return sizeof(struct sev_data_send_finish);
147 	case SEV_CMD_RECEIVE_START:		return sizeof(struct sev_data_receive_start);
148 	case SEV_CMD_RECEIVE_FINISH:		return sizeof(struct sev_data_receive_finish);
149 	case SEV_CMD_RECEIVE_UPDATE_DATA:	return sizeof(struct sev_data_receive_update_data);
150 	case SEV_CMD_RECEIVE_UPDATE_VMSA:	return sizeof(struct sev_data_receive_update_vmsa);
151 	case SEV_CMD_LAUNCH_UPDATE_SECRET:	return sizeof(struct sev_data_launch_secret);
152 	case SEV_CMD_DOWNLOAD_FIRMWARE:		return sizeof(struct sev_data_download_firmware);
153 	case SEV_CMD_GET_ID:			return sizeof(struct sev_data_get_id);
154 	case SEV_CMD_ATTESTATION_REPORT:	return sizeof(struct sev_data_attestation_report);
155 	case SEV_CMD_SEND_CANCEL:		return sizeof(struct sev_data_send_cancel);
156 	default:				return 0;
157 	}
158 
159 	return 0;
160 }
161 
162 static void *sev_fw_alloc(unsigned long len)
163 {
164 	struct page *page;
165 
166 	page = alloc_pages(GFP_KERNEL, get_order(len));
167 	if (!page)
168 		return NULL;
169 
170 	return page_address(page);
171 }
172 
173 static int sev_read_init_ex_file(void)
174 {
175 	struct sev_device *sev = psp_master->sev_data;
176 	struct file *fp;
177 	ssize_t nread;
178 
179 	lockdep_assert_held(&sev_cmd_mutex);
180 
181 	if (!sev_init_ex_buffer)
182 		return -EOPNOTSUPP;
183 
184 	fp = filp_open(init_ex_path, O_RDONLY, 0);
185 	if (IS_ERR(fp)) {
186 		int ret = PTR_ERR(fp);
187 
188 		dev_err(sev->dev,
189 			"SEV: could not open %s for read, error %d\n",
190 			init_ex_path, ret);
191 		return ret;
192 	}
193 
194 	nread = kernel_read(fp, sev_init_ex_buffer, NV_LENGTH, NULL);
195 	if (nread != NV_LENGTH) {
196 		dev_err(sev->dev,
197 			"SEV: failed to read %u bytes to non volatile memory area, ret %ld\n",
198 			NV_LENGTH, nread);
199 		return -EIO;
200 	}
201 
202 	dev_dbg(sev->dev, "SEV: read %ld bytes from NV file\n", nread);
203 	filp_close(fp, NULL);
204 
205 	return 0;
206 }
207 
208 static void sev_write_init_ex_file(void)
209 {
210 	struct sev_device *sev = psp_master->sev_data;
211 	struct file *fp;
212 	loff_t offset = 0;
213 	ssize_t nwrite;
214 
215 	lockdep_assert_held(&sev_cmd_mutex);
216 
217 	if (!sev_init_ex_buffer)
218 		return;
219 
220 	fp = filp_open(init_ex_path, O_CREAT | O_WRONLY, 0600);
221 	if (IS_ERR(fp)) {
222 		dev_err(sev->dev,
223 			"SEV: could not open file for write, error %ld\n",
224 			PTR_ERR(fp));
225 		return;
226 	}
227 
228 	nwrite = kernel_write(fp, sev_init_ex_buffer, NV_LENGTH, &offset);
229 	vfs_fsync(fp, 0);
230 	filp_close(fp, NULL);
231 
232 	if (nwrite != NV_LENGTH) {
233 		dev_err(sev->dev,
234 			"SEV: failed to write %u bytes to non volatile memory area, ret %ld\n",
235 			NV_LENGTH, nwrite);
236 		return;
237 	}
238 
239 	dev_dbg(sev->dev, "SEV: write successful to NV file\n");
240 }
241 
242 static void sev_write_init_ex_file_if_required(int cmd_id)
243 {
244 	lockdep_assert_held(&sev_cmd_mutex);
245 
246 	if (!sev_init_ex_buffer)
247 		return;
248 
249 	/*
250 	 * Only a few platform commands modify the SPI/NV area, but none of the
251 	 * non-platform commands do. Only INIT(_EX), PLATFORM_RESET, PEK_GEN,
252 	 * PEK_CERT_IMPORT, and PDH_GEN do.
253 	 */
254 	switch (cmd_id) {
255 	case SEV_CMD_FACTORY_RESET:
256 	case SEV_CMD_INIT_EX:
257 	case SEV_CMD_PDH_GEN:
258 	case SEV_CMD_PEK_CERT_IMPORT:
259 	case SEV_CMD_PEK_GEN:
260 		break;
261 	default:
262 		return;
263 	}
264 
265 	sev_write_init_ex_file();
266 }
267 
268 static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret)
269 {
270 	struct psp_device *psp = psp_master;
271 	struct sev_device *sev;
272 	unsigned int phys_lsb, phys_msb;
273 	unsigned int reg, ret = 0;
274 	int buf_len;
275 
276 	if (!psp || !psp->sev_data)
277 		return -ENODEV;
278 
279 	if (psp_dead)
280 		return -EBUSY;
281 
282 	sev = psp->sev_data;
283 
284 	buf_len = sev_cmd_buffer_len(cmd);
285 	if (WARN_ON_ONCE(!data != !buf_len))
286 		return -EINVAL;
287 
288 	/*
289 	 * Copy the incoming data to driver's scratch buffer as __pa() will not
290 	 * work for some memory, e.g. vmalloc'd addresses, and @data may not be
291 	 * physically contiguous.
292 	 */
293 	if (data)
294 		memcpy(sev->cmd_buf, data, buf_len);
295 
296 	/* Get the physical address of the command buffer */
297 	phys_lsb = data ? lower_32_bits(__psp_pa(sev->cmd_buf)) : 0;
298 	phys_msb = data ? upper_32_bits(__psp_pa(sev->cmd_buf)) : 0;
299 
300 	dev_dbg(sev->dev, "sev command id %#x buffer 0x%08x%08x timeout %us\n",
301 		cmd, phys_msb, phys_lsb, psp_timeout);
302 
303 	print_hex_dump_debug("(in):  ", DUMP_PREFIX_OFFSET, 16, 2, data,
304 			     buf_len, false);
305 
306 	iowrite32(phys_lsb, sev->io_regs + sev->vdata->cmdbuff_addr_lo_reg);
307 	iowrite32(phys_msb, sev->io_regs + sev->vdata->cmdbuff_addr_hi_reg);
308 
309 	sev->int_rcvd = 0;
310 
311 	reg = cmd;
312 	reg <<= SEV_CMDRESP_CMD_SHIFT;
313 	reg |= SEV_CMDRESP_IOC;
314 	iowrite32(reg, sev->io_regs + sev->vdata->cmdresp_reg);
315 
316 	/* wait for command completion */
317 	ret = sev_wait_cmd_ioc(sev, &reg, psp_timeout);
318 	if (ret) {
319 		if (psp_ret)
320 			*psp_ret = 0;
321 
322 		dev_err(sev->dev, "sev command %#x timed out, disabling PSP\n", cmd);
323 		psp_dead = true;
324 
325 		return ret;
326 	}
327 
328 	psp_timeout = psp_cmd_timeout;
329 
330 	if (psp_ret)
331 		*psp_ret = reg & PSP_CMDRESP_ERR_MASK;
332 
333 	if (reg & PSP_CMDRESP_ERR_MASK) {
334 		dev_dbg(sev->dev, "sev command %#x failed (%#010x)\n",
335 			cmd, reg & PSP_CMDRESP_ERR_MASK);
336 		ret = -EIO;
337 	} else {
338 		sev_write_init_ex_file_if_required(cmd);
339 	}
340 
341 	print_hex_dump_debug("(out): ", DUMP_PREFIX_OFFSET, 16, 2, data,
342 			     buf_len, false);
343 
344 	/*
345 	 * Copy potential output from the PSP back to data.  Do this even on
346 	 * failure in case the caller wants to glean something from the error.
347 	 */
348 	if (data)
349 		memcpy(data, sev->cmd_buf, buf_len);
350 
351 	return ret;
352 }
353 
354 static int sev_do_cmd(int cmd, void *data, int *psp_ret)
355 {
356 	int rc;
357 
358 	mutex_lock(&sev_cmd_mutex);
359 	rc = __sev_do_cmd_locked(cmd, data, psp_ret);
360 	mutex_unlock(&sev_cmd_mutex);
361 
362 	return rc;
363 }
364 
365 static int __sev_init_locked(int *error)
366 {
367 	struct sev_data_init data;
368 
369 	memset(&data, 0, sizeof(data));
370 	if (sev_es_tmr) {
371 		/*
372 		 * Do not include the encryption mask on the physical
373 		 * address of the TMR (firmware should clear it anyway).
374 		 */
375 		data.tmr_address = __pa(sev_es_tmr);
376 
377 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
378 		data.tmr_len = SEV_ES_TMR_SIZE;
379 	}
380 
381 	return __sev_do_cmd_locked(SEV_CMD_INIT, &data, error);
382 }
383 
384 static int __sev_init_ex_locked(int *error)
385 {
386 	struct sev_data_init_ex data;
387 	int ret;
388 
389 	memset(&data, 0, sizeof(data));
390 	data.length = sizeof(data);
391 	data.nv_address = __psp_pa(sev_init_ex_buffer);
392 	data.nv_len = NV_LENGTH;
393 
394 	ret = sev_read_init_ex_file();
395 	if (ret)
396 		return ret;
397 
398 	if (sev_es_tmr) {
399 		/*
400 		 * Do not include the encryption mask on the physical
401 		 * address of the TMR (firmware should clear it anyway).
402 		 */
403 		data.tmr_address = __pa(sev_es_tmr);
404 
405 		data.flags |= SEV_INIT_FLAGS_SEV_ES;
406 		data.tmr_len = SEV_ES_TMR_SIZE;
407 	}
408 
409 	return __sev_do_cmd_locked(SEV_CMD_INIT_EX, &data, error);
410 }
411 
412 static int __sev_platform_init_locked(int *error)
413 {
414 	struct psp_device *psp = psp_master;
415 	struct sev_device *sev;
416 	int rc, psp_ret = -1;
417 	int (*init_function)(int *error);
418 
419 	if (!psp || !psp->sev_data)
420 		return -ENODEV;
421 
422 	sev = psp->sev_data;
423 
424 	if (sev->state == SEV_STATE_INIT)
425 		return 0;
426 
427 	init_function = sev_init_ex_buffer ? __sev_init_ex_locked :
428 			__sev_init_locked;
429 	rc = init_function(&psp_ret);
430 	if (rc && psp_ret == SEV_RET_SECURE_DATA_INVALID) {
431 		/*
432 		 * Initialization command returned an integrity check failure
433 		 * status code, meaning that firmware load and validation of SEV
434 		 * related persistent data has failed. Retrying the
435 		 * initialization function should succeed by replacing the state
436 		 * with a reset state.
437 		 */
438 		dev_dbg(sev->dev, "SEV: retrying INIT command");
439 		rc = init_function(&psp_ret);
440 	}
441 	if (error)
442 		*error = psp_ret;
443 
444 	if (rc)
445 		return rc;
446 
447 	sev->state = SEV_STATE_INIT;
448 
449 	/* Prepare for first SEV guest launch after INIT */
450 	wbinvd_on_all_cpus();
451 	rc = __sev_do_cmd_locked(SEV_CMD_DF_FLUSH, NULL, error);
452 	if (rc)
453 		return rc;
454 
455 	dev_dbg(sev->dev, "SEV firmware initialized\n");
456 
457 	dev_info(sev->dev, "SEV API:%d.%d build:%d\n", sev->api_major,
458 		 sev->api_minor, sev->build);
459 
460 	return 0;
461 }
462 
463 int sev_platform_init(int *error)
464 {
465 	int rc;
466 
467 	mutex_lock(&sev_cmd_mutex);
468 	rc = __sev_platform_init_locked(error);
469 	mutex_unlock(&sev_cmd_mutex);
470 
471 	return rc;
472 }
473 EXPORT_SYMBOL_GPL(sev_platform_init);
474 
475 static int __sev_platform_shutdown_locked(int *error)
476 {
477 	struct sev_device *sev = psp_master->sev_data;
478 	int ret;
479 
480 	if (sev->state == SEV_STATE_UNINIT)
481 		return 0;
482 
483 	ret = __sev_do_cmd_locked(SEV_CMD_SHUTDOWN, NULL, error);
484 	if (ret)
485 		return ret;
486 
487 	sev->state = SEV_STATE_UNINIT;
488 	dev_dbg(sev->dev, "SEV firmware shutdown\n");
489 
490 	return ret;
491 }
492 
493 static int sev_platform_shutdown(int *error)
494 {
495 	int rc;
496 
497 	mutex_lock(&sev_cmd_mutex);
498 	rc = __sev_platform_shutdown_locked(NULL);
499 	mutex_unlock(&sev_cmd_mutex);
500 
501 	return rc;
502 }
503 
504 static int sev_get_platform_state(int *state, int *error)
505 {
506 	struct sev_user_data_status data;
507 	int rc;
508 
509 	rc = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, error);
510 	if (rc)
511 		return rc;
512 
513 	*state = data.state;
514 	return rc;
515 }
516 
517 static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable)
518 {
519 	int state, rc;
520 
521 	if (!writable)
522 		return -EPERM;
523 
524 	/*
525 	 * The SEV spec requires that FACTORY_RESET must be issued in
526 	 * UNINIT state. Before we go further lets check if any guest is
527 	 * active.
528 	 *
529 	 * If FW is in WORKING state then deny the request otherwise issue
530 	 * SHUTDOWN command do INIT -> UNINIT before issuing the FACTORY_RESET.
531 	 *
532 	 */
533 	rc = sev_get_platform_state(&state, &argp->error);
534 	if (rc)
535 		return rc;
536 
537 	if (state == SEV_STATE_WORKING)
538 		return -EBUSY;
539 
540 	if (state == SEV_STATE_INIT) {
541 		rc = __sev_platform_shutdown_locked(&argp->error);
542 		if (rc)
543 			return rc;
544 	}
545 
546 	return __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error);
547 }
548 
549 static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp)
550 {
551 	struct sev_user_data_status data;
552 	int ret;
553 
554 	ret = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, &argp->error);
555 	if (ret)
556 		return ret;
557 
558 	if (copy_to_user((void __user *)argp->data, &data, sizeof(data)))
559 		ret = -EFAULT;
560 
561 	return ret;
562 }
563 
564 static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool writable)
565 {
566 	struct sev_device *sev = psp_master->sev_data;
567 	int rc;
568 
569 	if (!writable)
570 		return -EPERM;
571 
572 	if (sev->state == SEV_STATE_UNINIT) {
573 		rc = __sev_platform_init_locked(&argp->error);
574 		if (rc)
575 			return rc;
576 	}
577 
578 	return __sev_do_cmd_locked(cmd, NULL, &argp->error);
579 }
580 
581 static int sev_ioctl_do_pek_csr(struct sev_issue_cmd *argp, bool writable)
582 {
583 	struct sev_device *sev = psp_master->sev_data;
584 	struct sev_user_data_pek_csr input;
585 	struct sev_data_pek_csr data;
586 	void __user *input_address;
587 	void *blob = NULL;
588 	int ret;
589 
590 	if (!writable)
591 		return -EPERM;
592 
593 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
594 		return -EFAULT;
595 
596 	memset(&data, 0, sizeof(data));
597 
598 	/* userspace wants to query CSR length */
599 	if (!input.address || !input.length)
600 		goto cmd;
601 
602 	/* allocate a physically contiguous buffer to store the CSR blob */
603 	input_address = (void __user *)input.address;
604 	if (input.length > SEV_FW_BLOB_MAX_SIZE)
605 		return -EFAULT;
606 
607 	blob = kmalloc(input.length, GFP_KERNEL);
608 	if (!blob)
609 		return -ENOMEM;
610 
611 	data.address = __psp_pa(blob);
612 	data.len = input.length;
613 
614 cmd:
615 	if (sev->state == SEV_STATE_UNINIT) {
616 		ret = __sev_platform_init_locked(&argp->error);
617 		if (ret)
618 			goto e_free_blob;
619 	}
620 
621 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CSR, &data, &argp->error);
622 
623 	 /* If we query the CSR length, FW responded with expected data. */
624 	input.length = data.len;
625 
626 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
627 		ret = -EFAULT;
628 		goto e_free_blob;
629 	}
630 
631 	if (blob) {
632 		if (copy_to_user(input_address, blob, input.length))
633 			ret = -EFAULT;
634 	}
635 
636 e_free_blob:
637 	kfree(blob);
638 	return ret;
639 }
640 
641 void *psp_copy_user_blob(u64 uaddr, u32 len)
642 {
643 	if (!uaddr || !len)
644 		return ERR_PTR(-EINVAL);
645 
646 	/* verify that blob length does not exceed our limit */
647 	if (len > SEV_FW_BLOB_MAX_SIZE)
648 		return ERR_PTR(-EINVAL);
649 
650 	return memdup_user((void __user *)uaddr, len);
651 }
652 EXPORT_SYMBOL_GPL(psp_copy_user_blob);
653 
654 static int sev_get_api_version(void)
655 {
656 	struct sev_device *sev = psp_master->sev_data;
657 	struct sev_user_data_status status;
658 	int error = 0, ret;
659 
660 	ret = sev_platform_status(&status, &error);
661 	if (ret) {
662 		dev_err(sev->dev,
663 			"SEV: failed to get status. Error: %#x\n", error);
664 		return 1;
665 	}
666 
667 	sev->api_major = status.api_major;
668 	sev->api_minor = status.api_minor;
669 	sev->build = status.build;
670 	sev->state = status.state;
671 
672 	return 0;
673 }
674 
675 static int sev_get_firmware(struct device *dev,
676 			    const struct firmware **firmware)
677 {
678 	char fw_name_specific[SEV_FW_NAME_SIZE];
679 	char fw_name_subset[SEV_FW_NAME_SIZE];
680 
681 	snprintf(fw_name_specific, sizeof(fw_name_specific),
682 		 "amd/amd_sev_fam%.2xh_model%.2xh.sbin",
683 		 boot_cpu_data.x86, boot_cpu_data.x86_model);
684 
685 	snprintf(fw_name_subset, sizeof(fw_name_subset),
686 		 "amd/amd_sev_fam%.2xh_model%.1xxh.sbin",
687 		 boot_cpu_data.x86, (boot_cpu_data.x86_model & 0xf0) >> 4);
688 
689 	/* Check for SEV FW for a particular model.
690 	 * Ex. amd_sev_fam17h_model00h.sbin for Family 17h Model 00h
691 	 *
692 	 * or
693 	 *
694 	 * Check for SEV FW common to a subset of models.
695 	 * Ex. amd_sev_fam17h_model0xh.sbin for
696 	 *     Family 17h Model 00h -- Family 17h Model 0Fh
697 	 *
698 	 * or
699 	 *
700 	 * Fall-back to using generic name: sev.fw
701 	 */
702 	if ((firmware_request_nowarn(firmware, fw_name_specific, dev) >= 0) ||
703 	    (firmware_request_nowarn(firmware, fw_name_subset, dev) >= 0) ||
704 	    (firmware_request_nowarn(firmware, SEV_FW_FILE, dev) >= 0))
705 		return 0;
706 
707 	return -ENOENT;
708 }
709 
710 /* Don't fail if SEV FW couldn't be updated. Continue with existing SEV FW */
711 static int sev_update_firmware(struct device *dev)
712 {
713 	struct sev_data_download_firmware *data;
714 	const struct firmware *firmware;
715 	int ret, error, order;
716 	struct page *p;
717 	u64 data_size;
718 
719 	if (sev_get_firmware(dev, &firmware) == -ENOENT) {
720 		dev_dbg(dev, "No SEV firmware file present\n");
721 		return -1;
722 	}
723 
724 	/*
725 	 * SEV FW expects the physical address given to it to be 32
726 	 * byte aligned. Memory allocated has structure placed at the
727 	 * beginning followed by the firmware being passed to the SEV
728 	 * FW. Allocate enough memory for data structure + alignment
729 	 * padding + SEV FW.
730 	 */
731 	data_size = ALIGN(sizeof(struct sev_data_download_firmware), 32);
732 
733 	order = get_order(firmware->size + data_size);
734 	p = alloc_pages(GFP_KERNEL, order);
735 	if (!p) {
736 		ret = -1;
737 		goto fw_err;
738 	}
739 
740 	/*
741 	 * Copy firmware data to a kernel allocated contiguous
742 	 * memory region.
743 	 */
744 	data = page_address(p);
745 	memcpy(page_address(p) + data_size, firmware->data, firmware->size);
746 
747 	data->address = __psp_pa(page_address(p) + data_size);
748 	data->len = firmware->size;
749 
750 	ret = sev_do_cmd(SEV_CMD_DOWNLOAD_FIRMWARE, data, &error);
751 	if (ret)
752 		dev_dbg(dev, "Failed to update SEV firmware: %#x\n", error);
753 	else
754 		dev_info(dev, "SEV firmware update successful\n");
755 
756 	__free_pages(p, order);
757 
758 fw_err:
759 	release_firmware(firmware);
760 
761 	return ret;
762 }
763 
764 static int sev_ioctl_do_pek_import(struct sev_issue_cmd *argp, bool writable)
765 {
766 	struct sev_device *sev = psp_master->sev_data;
767 	struct sev_user_data_pek_cert_import input;
768 	struct sev_data_pek_cert_import data;
769 	void *pek_blob, *oca_blob;
770 	int ret;
771 
772 	if (!writable)
773 		return -EPERM;
774 
775 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
776 		return -EFAULT;
777 
778 	/* copy PEK certificate blobs from userspace */
779 	pek_blob = psp_copy_user_blob(input.pek_cert_address, input.pek_cert_len);
780 	if (IS_ERR(pek_blob))
781 		return PTR_ERR(pek_blob);
782 
783 	data.reserved = 0;
784 	data.pek_cert_address = __psp_pa(pek_blob);
785 	data.pek_cert_len = input.pek_cert_len;
786 
787 	/* copy PEK certificate blobs from userspace */
788 	oca_blob = psp_copy_user_blob(input.oca_cert_address, input.oca_cert_len);
789 	if (IS_ERR(oca_blob)) {
790 		ret = PTR_ERR(oca_blob);
791 		goto e_free_pek;
792 	}
793 
794 	data.oca_cert_address = __psp_pa(oca_blob);
795 	data.oca_cert_len = input.oca_cert_len;
796 
797 	/* If platform is not in INIT state then transition it to INIT */
798 	if (sev->state != SEV_STATE_INIT) {
799 		ret = __sev_platform_init_locked(&argp->error);
800 		if (ret)
801 			goto e_free_oca;
802 	}
803 
804 	ret = __sev_do_cmd_locked(SEV_CMD_PEK_CERT_IMPORT, &data, &argp->error);
805 
806 e_free_oca:
807 	kfree(oca_blob);
808 e_free_pek:
809 	kfree(pek_blob);
810 	return ret;
811 }
812 
813 static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp)
814 {
815 	struct sev_user_data_get_id2 input;
816 	struct sev_data_get_id data;
817 	void __user *input_address;
818 	void *id_blob = NULL;
819 	int ret;
820 
821 	/* SEV GET_ID is available from SEV API v0.16 and up */
822 	if (!sev_version_greater_or_equal(0, 16))
823 		return -ENOTSUPP;
824 
825 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
826 		return -EFAULT;
827 
828 	input_address = (void __user *)input.address;
829 
830 	if (input.address && input.length) {
831 		id_blob = kmalloc(input.length, GFP_KERNEL);
832 		if (!id_blob)
833 			return -ENOMEM;
834 
835 		data.address = __psp_pa(id_blob);
836 		data.len = input.length;
837 	} else {
838 		data.address = 0;
839 		data.len = 0;
840 	}
841 
842 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, &data, &argp->error);
843 
844 	/*
845 	 * Firmware will return the length of the ID value (either the minimum
846 	 * required length or the actual length written), return it to the user.
847 	 */
848 	input.length = data.len;
849 
850 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
851 		ret = -EFAULT;
852 		goto e_free;
853 	}
854 
855 	if (id_blob) {
856 		if (copy_to_user(input_address, id_blob, data.len)) {
857 			ret = -EFAULT;
858 			goto e_free;
859 		}
860 	}
861 
862 e_free:
863 	kfree(id_blob);
864 
865 	return ret;
866 }
867 
868 static int sev_ioctl_do_get_id(struct sev_issue_cmd *argp)
869 {
870 	struct sev_data_get_id *data;
871 	u64 data_size, user_size;
872 	void *id_blob, *mem;
873 	int ret;
874 
875 	/* SEV GET_ID available from SEV API v0.16 and up */
876 	if (!sev_version_greater_or_equal(0, 16))
877 		return -ENOTSUPP;
878 
879 	/* SEV FW expects the buffer it fills with the ID to be
880 	 * 8-byte aligned. Memory allocated should be enough to
881 	 * hold data structure + alignment padding + memory
882 	 * where SEV FW writes the ID.
883 	 */
884 	data_size = ALIGN(sizeof(struct sev_data_get_id), 8);
885 	user_size = sizeof(struct sev_user_data_get_id);
886 
887 	mem = kzalloc(data_size + user_size, GFP_KERNEL);
888 	if (!mem)
889 		return -ENOMEM;
890 
891 	data = mem;
892 	id_blob = mem + data_size;
893 
894 	data->address = __psp_pa(id_blob);
895 	data->len = user_size;
896 
897 	ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, data, &argp->error);
898 	if (!ret) {
899 		if (copy_to_user((void __user *)argp->data, id_blob, data->len))
900 			ret = -EFAULT;
901 	}
902 
903 	kfree(mem);
904 
905 	return ret;
906 }
907 
908 static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable)
909 {
910 	struct sev_device *sev = psp_master->sev_data;
911 	struct sev_user_data_pdh_cert_export input;
912 	void *pdh_blob = NULL, *cert_blob = NULL;
913 	struct sev_data_pdh_cert_export data;
914 	void __user *input_cert_chain_address;
915 	void __user *input_pdh_cert_address;
916 	int ret;
917 
918 	/* If platform is not in INIT state then transition it to INIT. */
919 	if (sev->state != SEV_STATE_INIT) {
920 		if (!writable)
921 			return -EPERM;
922 
923 		ret = __sev_platform_init_locked(&argp->error);
924 		if (ret)
925 			return ret;
926 	}
927 
928 	if (copy_from_user(&input, (void __user *)argp->data, sizeof(input)))
929 		return -EFAULT;
930 
931 	memset(&data, 0, sizeof(data));
932 
933 	/* Userspace wants to query the certificate length. */
934 	if (!input.pdh_cert_address ||
935 	    !input.pdh_cert_len ||
936 	    !input.cert_chain_address)
937 		goto cmd;
938 
939 	input_pdh_cert_address = (void __user *)input.pdh_cert_address;
940 	input_cert_chain_address = (void __user *)input.cert_chain_address;
941 
942 	/* Allocate a physically contiguous buffer to store the PDH blob. */
943 	if (input.pdh_cert_len > SEV_FW_BLOB_MAX_SIZE)
944 		return -EFAULT;
945 
946 	/* Allocate a physically contiguous buffer to store the cert chain blob. */
947 	if (input.cert_chain_len > SEV_FW_BLOB_MAX_SIZE)
948 		return -EFAULT;
949 
950 	pdh_blob = kmalloc(input.pdh_cert_len, GFP_KERNEL);
951 	if (!pdh_blob)
952 		return -ENOMEM;
953 
954 	data.pdh_cert_address = __psp_pa(pdh_blob);
955 	data.pdh_cert_len = input.pdh_cert_len;
956 
957 	cert_blob = kmalloc(input.cert_chain_len, GFP_KERNEL);
958 	if (!cert_blob) {
959 		ret = -ENOMEM;
960 		goto e_free_pdh;
961 	}
962 
963 	data.cert_chain_address = __psp_pa(cert_blob);
964 	data.cert_chain_len = input.cert_chain_len;
965 
966 cmd:
967 	ret = __sev_do_cmd_locked(SEV_CMD_PDH_CERT_EXPORT, &data, &argp->error);
968 
969 	/* If we query the length, FW responded with expected data. */
970 	input.cert_chain_len = data.cert_chain_len;
971 	input.pdh_cert_len = data.pdh_cert_len;
972 
973 	if (copy_to_user((void __user *)argp->data, &input, sizeof(input))) {
974 		ret = -EFAULT;
975 		goto e_free_cert;
976 	}
977 
978 	if (pdh_blob) {
979 		if (copy_to_user(input_pdh_cert_address,
980 				 pdh_blob, input.pdh_cert_len)) {
981 			ret = -EFAULT;
982 			goto e_free_cert;
983 		}
984 	}
985 
986 	if (cert_blob) {
987 		if (copy_to_user(input_cert_chain_address,
988 				 cert_blob, input.cert_chain_len))
989 			ret = -EFAULT;
990 	}
991 
992 e_free_cert:
993 	kfree(cert_blob);
994 e_free_pdh:
995 	kfree(pdh_blob);
996 	return ret;
997 }
998 
999 static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)
1000 {
1001 	void __user *argp = (void __user *)arg;
1002 	struct sev_issue_cmd input;
1003 	int ret = -EFAULT;
1004 	bool writable = file->f_mode & FMODE_WRITE;
1005 
1006 	if (!psp_master || !psp_master->sev_data)
1007 		return -ENODEV;
1008 
1009 	if (ioctl != SEV_ISSUE_CMD)
1010 		return -EINVAL;
1011 
1012 	if (copy_from_user(&input, argp, sizeof(struct sev_issue_cmd)))
1013 		return -EFAULT;
1014 
1015 	if (input.cmd > SEV_MAX)
1016 		return -EINVAL;
1017 
1018 	mutex_lock(&sev_cmd_mutex);
1019 
1020 	switch (input.cmd) {
1021 
1022 	case SEV_FACTORY_RESET:
1023 		ret = sev_ioctl_do_reset(&input, writable);
1024 		break;
1025 	case SEV_PLATFORM_STATUS:
1026 		ret = sev_ioctl_do_platform_status(&input);
1027 		break;
1028 	case SEV_PEK_GEN:
1029 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PEK_GEN, &input, writable);
1030 		break;
1031 	case SEV_PDH_GEN:
1032 		ret = sev_ioctl_do_pek_pdh_gen(SEV_CMD_PDH_GEN, &input, writable);
1033 		break;
1034 	case SEV_PEK_CSR:
1035 		ret = sev_ioctl_do_pek_csr(&input, writable);
1036 		break;
1037 	case SEV_PEK_CERT_IMPORT:
1038 		ret = sev_ioctl_do_pek_import(&input, writable);
1039 		break;
1040 	case SEV_PDH_CERT_EXPORT:
1041 		ret = sev_ioctl_do_pdh_export(&input, writable);
1042 		break;
1043 	case SEV_GET_ID:
1044 		pr_warn_once("SEV_GET_ID command is deprecated, use SEV_GET_ID2\n");
1045 		ret = sev_ioctl_do_get_id(&input);
1046 		break;
1047 	case SEV_GET_ID2:
1048 		ret = sev_ioctl_do_get_id2(&input);
1049 		break;
1050 	default:
1051 		ret = -EINVAL;
1052 		goto out;
1053 	}
1054 
1055 	if (copy_to_user(argp, &input, sizeof(struct sev_issue_cmd)))
1056 		ret = -EFAULT;
1057 out:
1058 	mutex_unlock(&sev_cmd_mutex);
1059 
1060 	return ret;
1061 }
1062 
1063 static const struct file_operations sev_fops = {
1064 	.owner	= THIS_MODULE,
1065 	.unlocked_ioctl = sev_ioctl,
1066 };
1067 
1068 int sev_platform_status(struct sev_user_data_status *data, int *error)
1069 {
1070 	return sev_do_cmd(SEV_CMD_PLATFORM_STATUS, data, error);
1071 }
1072 EXPORT_SYMBOL_GPL(sev_platform_status);
1073 
1074 int sev_guest_deactivate(struct sev_data_deactivate *data, int *error)
1075 {
1076 	return sev_do_cmd(SEV_CMD_DEACTIVATE, data, error);
1077 }
1078 EXPORT_SYMBOL_GPL(sev_guest_deactivate);
1079 
1080 int sev_guest_activate(struct sev_data_activate *data, int *error)
1081 {
1082 	return sev_do_cmd(SEV_CMD_ACTIVATE, data, error);
1083 }
1084 EXPORT_SYMBOL_GPL(sev_guest_activate);
1085 
1086 int sev_guest_decommission(struct sev_data_decommission *data, int *error)
1087 {
1088 	return sev_do_cmd(SEV_CMD_DECOMMISSION, data, error);
1089 }
1090 EXPORT_SYMBOL_GPL(sev_guest_decommission);
1091 
1092 int sev_guest_df_flush(int *error)
1093 {
1094 	return sev_do_cmd(SEV_CMD_DF_FLUSH, NULL, error);
1095 }
1096 EXPORT_SYMBOL_GPL(sev_guest_df_flush);
1097 
1098 static void sev_exit(struct kref *ref)
1099 {
1100 	misc_deregister(&misc_dev->misc);
1101 	kfree(misc_dev);
1102 	misc_dev = NULL;
1103 }
1104 
1105 static int sev_misc_init(struct sev_device *sev)
1106 {
1107 	struct device *dev = sev->dev;
1108 	int ret;
1109 
1110 	/*
1111 	 * SEV feature support can be detected on multiple devices but the SEV
1112 	 * FW commands must be issued on the master. During probe, we do not
1113 	 * know the master hence we create /dev/sev on the first device probe.
1114 	 * sev_do_cmd() finds the right master device to which to issue the
1115 	 * command to the firmware.
1116 	 */
1117 	if (!misc_dev) {
1118 		struct miscdevice *misc;
1119 
1120 		misc_dev = kzalloc(sizeof(*misc_dev), GFP_KERNEL);
1121 		if (!misc_dev)
1122 			return -ENOMEM;
1123 
1124 		misc = &misc_dev->misc;
1125 		misc->minor = MISC_DYNAMIC_MINOR;
1126 		misc->name = DEVICE_NAME;
1127 		misc->fops = &sev_fops;
1128 
1129 		ret = misc_register(misc);
1130 		if (ret)
1131 			return ret;
1132 
1133 		kref_init(&misc_dev->refcount);
1134 	} else {
1135 		kref_get(&misc_dev->refcount);
1136 	}
1137 
1138 	init_waitqueue_head(&sev->int_queue);
1139 	sev->misc = misc_dev;
1140 	dev_dbg(dev, "registered SEV device\n");
1141 
1142 	return 0;
1143 }
1144 
1145 int sev_dev_init(struct psp_device *psp)
1146 {
1147 	struct device *dev = psp->dev;
1148 	struct sev_device *sev;
1149 	int ret = -ENOMEM;
1150 
1151 	if (!boot_cpu_has(X86_FEATURE_SEV)) {
1152 		dev_info_once(dev, "SEV: memory encryption not enabled by BIOS\n");
1153 		return 0;
1154 	}
1155 
1156 	sev = devm_kzalloc(dev, sizeof(*sev), GFP_KERNEL);
1157 	if (!sev)
1158 		goto e_err;
1159 
1160 	sev->cmd_buf = (void *)devm_get_free_pages(dev, GFP_KERNEL, 0);
1161 	if (!sev->cmd_buf)
1162 		goto e_sev;
1163 
1164 	psp->sev_data = sev;
1165 
1166 	sev->dev = dev;
1167 	sev->psp = psp;
1168 
1169 	sev->io_regs = psp->io_regs;
1170 
1171 	sev->vdata = (struct sev_vdata *)psp->vdata->sev;
1172 	if (!sev->vdata) {
1173 		ret = -ENODEV;
1174 		dev_err(dev, "sev: missing driver data\n");
1175 		goto e_buf;
1176 	}
1177 
1178 	psp_set_sev_irq_handler(psp, sev_irq_handler, sev);
1179 
1180 	ret = sev_misc_init(sev);
1181 	if (ret)
1182 		goto e_irq;
1183 
1184 	dev_notice(dev, "sev enabled\n");
1185 
1186 	return 0;
1187 
1188 e_irq:
1189 	psp_clear_sev_irq_handler(psp);
1190 e_buf:
1191 	devm_free_pages(dev, (unsigned long)sev->cmd_buf);
1192 e_sev:
1193 	devm_kfree(dev, sev);
1194 e_err:
1195 	psp->sev_data = NULL;
1196 
1197 	dev_notice(dev, "sev initialization failed\n");
1198 
1199 	return ret;
1200 }
1201 
1202 static void sev_firmware_shutdown(struct sev_device *sev)
1203 {
1204 	sev_platform_shutdown(NULL);
1205 
1206 	if (sev_es_tmr) {
1207 		/* The TMR area was encrypted, flush it from the cache */
1208 		wbinvd_on_all_cpus();
1209 
1210 		free_pages((unsigned long)sev_es_tmr,
1211 			   get_order(SEV_ES_TMR_SIZE));
1212 		sev_es_tmr = NULL;
1213 	}
1214 
1215 	if (sev_init_ex_buffer) {
1216 		free_pages((unsigned long)sev_init_ex_buffer,
1217 			   get_order(NV_LENGTH));
1218 		sev_init_ex_buffer = NULL;
1219 	}
1220 }
1221 
1222 void sev_dev_destroy(struct psp_device *psp)
1223 {
1224 	struct sev_device *sev = psp->sev_data;
1225 
1226 	if (!sev)
1227 		return;
1228 
1229 	sev_firmware_shutdown(sev);
1230 
1231 	if (sev->misc)
1232 		kref_put(&misc_dev->refcount, sev_exit);
1233 
1234 	psp_clear_sev_irq_handler(psp);
1235 }
1236 
1237 int sev_issue_cmd_external_user(struct file *filep, unsigned int cmd,
1238 				void *data, int *error)
1239 {
1240 	if (!filep || filep->f_op != &sev_fops)
1241 		return -EBADF;
1242 
1243 	return sev_do_cmd(cmd, data, error);
1244 }
1245 EXPORT_SYMBOL_GPL(sev_issue_cmd_external_user);
1246 
1247 void sev_pci_init(void)
1248 {
1249 	struct sev_device *sev = psp_master->sev_data;
1250 	int error, rc;
1251 
1252 	if (!sev)
1253 		return;
1254 
1255 	psp_timeout = psp_probe_timeout;
1256 
1257 	if (sev_get_api_version())
1258 		goto err;
1259 
1260 	if (sev_version_greater_or_equal(0, 15) &&
1261 	    sev_update_firmware(sev->dev) == 0)
1262 		sev_get_api_version();
1263 
1264 	/* If an init_ex_path is provided rely on INIT_EX for PSP initialization
1265 	 * instead of INIT.
1266 	 */
1267 	if (init_ex_path) {
1268 		sev_init_ex_buffer = sev_fw_alloc(NV_LENGTH);
1269 		if (!sev_init_ex_buffer) {
1270 			dev_err(sev->dev,
1271 				"SEV: INIT_EX NV memory allocation failed\n");
1272 			goto err;
1273 		}
1274 	}
1275 
1276 	/* Obtain the TMR memory area for SEV-ES use */
1277 	sev_es_tmr = sev_fw_alloc(SEV_ES_TMR_SIZE);
1278 	if (!sev_es_tmr)
1279 		dev_warn(sev->dev,
1280 			 "SEV: TMR allocation failed, SEV-ES support unavailable\n");
1281 
1282 	if (!psp_init_on_probe)
1283 		return;
1284 
1285 	/* Initialize the platform */
1286 	rc = sev_platform_init(&error);
1287 	if (rc)
1288 		dev_err(sev->dev, "SEV: failed to INIT error %#x, rc %d\n",
1289 			error, rc);
1290 
1291 	return;
1292 
1293 err:
1294 	psp_master->sev_data = NULL;
1295 }
1296 
1297 void sev_pci_exit(void)
1298 {
1299 	struct sev_device *sev = psp_master->sev_data;
1300 
1301 	if (!sev)
1302 		return;
1303 
1304 	sev_firmware_shutdown(sev);
1305 }
1306