1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * TDX guest user interface driver
4  *
5  * Copyright (C) 2022 Intel Corporation
6  */
7 
8 #include <linux/kernel.h>
9 #include <linux/miscdevice.h>
10 #include <linux/mm.h>
11 #include <linux/module.h>
12 #include <linux/mod_devicetable.h>
13 #include <linux/string.h>
14 #include <linux/uaccess.h>
15 
16 #include <uapi/linux/tdx-guest.h>
17 
18 #include <asm/cpu_device_id.h>
19 #include <asm/tdx.h>
20 
tdx_get_report0(struct tdx_report_req __user * req)21 static long tdx_get_report0(struct tdx_report_req __user *req)
22 {
23 	u8 *reportdata, *tdreport;
24 	long ret;
25 
26 	reportdata = kmalloc(TDX_REPORTDATA_LEN, GFP_KERNEL);
27 	if (!reportdata)
28 		return -ENOMEM;
29 
30 	tdreport = kzalloc(TDX_REPORT_LEN, GFP_KERNEL);
31 	if (!tdreport) {
32 		ret = -ENOMEM;
33 		goto out;
34 	}
35 
36 	if (copy_from_user(reportdata, req->reportdata, TDX_REPORTDATA_LEN)) {
37 		ret = -EFAULT;
38 		goto out;
39 	}
40 
41 	/* Generate TDREPORT0 using "TDG.MR.REPORT" TDCALL */
42 	ret = tdx_mcall_get_report0(reportdata, tdreport);
43 	if (ret)
44 		goto out;
45 
46 	if (copy_to_user(req->tdreport, tdreport, TDX_REPORT_LEN))
47 		ret = -EFAULT;
48 
49 out:
50 	kfree(reportdata);
51 	kfree(tdreport);
52 
53 	return ret;
54 }
55 
tdx_guest_ioctl(struct file * file,unsigned int cmd,unsigned long arg)56 static long tdx_guest_ioctl(struct file *file, unsigned int cmd,
57 			    unsigned long arg)
58 {
59 	switch (cmd) {
60 	case TDX_CMD_GET_REPORT0:
61 		return tdx_get_report0((struct tdx_report_req __user *)arg);
62 	default:
63 		return -ENOTTY;
64 	}
65 }
66 
67 static const struct file_operations tdx_guest_fops = {
68 	.owner = THIS_MODULE,
69 	.unlocked_ioctl = tdx_guest_ioctl,
70 	.llseek = no_llseek,
71 };
72 
73 static struct miscdevice tdx_misc_dev = {
74 	.name = KBUILD_MODNAME,
75 	.minor = MISC_DYNAMIC_MINOR,
76 	.fops = &tdx_guest_fops,
77 };
78 
79 static const struct x86_cpu_id tdx_guest_ids[] = {
80 	X86_MATCH_FEATURE(X86_FEATURE_TDX_GUEST, NULL),
81 	{}
82 };
83 MODULE_DEVICE_TABLE(x86cpu, tdx_guest_ids);
84 
tdx_guest_init(void)85 static int __init tdx_guest_init(void)
86 {
87 	if (!x86_match_cpu(tdx_guest_ids))
88 		return -ENODEV;
89 
90 	return misc_register(&tdx_misc_dev);
91 }
92 module_init(tdx_guest_init);
93 
tdx_guest_exit(void)94 static void __exit tdx_guest_exit(void)
95 {
96 	misc_deregister(&tdx_misc_dev);
97 }
98 module_exit(tdx_guest_exit);
99 
100 MODULE_AUTHOR("Kuppuswamy Sathyanarayanan <sathyanarayanan.kuppuswamy@linux.intel.com>");
101 MODULE_DESCRIPTION("TDX Guest Driver");
102 MODULE_LICENSE("GPL");
103