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