xref: /linux/drivers/platform/x86/amd/hsmp/hsmp.c (revision d20457b46eca76b9bb716dd31af591cad21607b5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * AMD HSMP Platform Driver
4  * Copyright (c) 2022, AMD.
5  * All Rights Reserved.
6  *
7  * This file provides a device implementation for HSMP interface
8  */
9 
10 #include <asm/amd/hsmp.h>
11 
12 #include <linux/acpi.h>
13 #include <linux/delay.h>
14 #include <linux/device.h>
15 #include <linux/semaphore.h>
16 #include <linux/sysfs.h>
17 
18 #include "hsmp.h"
19 
20 /* HSMP Status / Error codes */
21 #define HSMP_STATUS_NOT_READY	0x00
22 #define HSMP_STATUS_OK		0x01
23 #define HSMP_ERR_INVALID_MSG	0xFE
24 #define HSMP_ERR_INVALID_INPUT	0xFF
25 #define HSMP_ERR_PREREQ_NOT_SATISFIED	0xFD
26 #define HSMP_ERR_SMU_BUSY		0xFC
27 
28 /* Timeout in millsec */
29 #define HSMP_MSG_TIMEOUT	100
30 #define HSMP_SHORT_SLEEP	1
31 
32 #define HSMP_WR			true
33 #define HSMP_RD			false
34 
35 /*
36  * When same message numbers are used for both GET and SET operation,
37  * bit:31 indicates whether its SET or GET operation.
38  */
39 #define CHECK_GET_BIT		BIT(31)
40 
41 static struct hsmp_plat_device hsmp_pdev;
42 
43 /*
44  * Send a message to the HSMP port via PCI-e config space registers
45  * or by writing to MMIO space.
46  *
47  * The caller is expected to zero out any unused arguments.
48  * If a response is expected, the number of response words should be greater than 0.
49  *
50  * Returns 0 for success and populates the requested number of arguments.
51  * Returns a negative error code for failure.
52  */
53 static int __hsmp_send_message(struct hsmp_socket *sock, struct hsmp_message *msg)
54 {
55 	struct hsmp_mbaddr_info *mbinfo;
56 	unsigned long timeout, short_sleep;
57 	u32 mbox_status;
58 	u32 index;
59 	int ret;
60 
61 	mbinfo = &sock->mbinfo;
62 
63 	/* Clear the status register */
64 	mbox_status = HSMP_STATUS_NOT_READY;
65 	ret = sock->amd_hsmp_rdwr(sock, mbinfo->msg_resp_off, &mbox_status, HSMP_WR);
66 	if (ret) {
67 		dev_err(sock->dev, "Error %d clearing mailbox status register\n", ret);
68 		return ret;
69 	}
70 
71 	index = 0;
72 	/* Write any message arguments */
73 	while (index < msg->num_args) {
74 		ret = sock->amd_hsmp_rdwr(sock, mbinfo->msg_arg_off + (index << 2),
75 					  &msg->args[index], HSMP_WR);
76 		if (ret) {
77 			dev_err(sock->dev, "Error %d writing message argument %d\n", ret, index);
78 			return ret;
79 		}
80 		index++;
81 	}
82 
83 	/* Write the message ID which starts the operation */
84 	ret = sock->amd_hsmp_rdwr(sock, mbinfo->msg_id_off, &msg->msg_id, HSMP_WR);
85 	if (ret) {
86 		dev_err(sock->dev, "Error %d writing message ID %u\n", ret, msg->msg_id);
87 		return ret;
88 	}
89 
90 	/*
91 	 * Depending on when the trigger write completes relative to the SMU
92 	 * firmware 1 ms cycle, the operation may take from tens of us to 1 ms
93 	 * to complete. Some operations may take more. Therefore we will try
94 	 * a few short duration sleeps and switch to long sleeps if we don't
95 	 * succeed quickly.
96 	 */
97 	short_sleep = jiffies + msecs_to_jiffies(HSMP_SHORT_SLEEP);
98 	timeout	= jiffies + msecs_to_jiffies(HSMP_MSG_TIMEOUT);
99 
100 	while (true) {
101 		ret = sock->amd_hsmp_rdwr(sock, mbinfo->msg_resp_off, &mbox_status, HSMP_RD);
102 		if (ret) {
103 			dev_err(sock->dev, "Error %d reading mailbox status\n", ret);
104 			return ret;
105 		}
106 
107 		if (mbox_status != HSMP_STATUS_NOT_READY)
108 			break;
109 
110 		if (!time_before(jiffies, timeout))
111 			break;
112 
113 		if (time_before(jiffies, short_sleep))
114 			usleep_range(50, 100);
115 		else
116 			usleep_range(1000, 2000);
117 	}
118 
119 	if (unlikely(mbox_status == HSMP_STATUS_NOT_READY)) {
120 		dev_err(sock->dev, "Message ID 0x%X failure : SMU timeout (status = 0x%X)\n",
121 			msg->msg_id, mbox_status);
122 		return -ETIMEDOUT;
123 	} else if (unlikely(mbox_status == HSMP_ERR_INVALID_MSG)) {
124 		dev_err(sock->dev, "Message ID 0x%X failure : Invalid message (status = 0x%X)\n",
125 			msg->msg_id, mbox_status);
126 		return -ENOMSG;
127 	} else if (unlikely(mbox_status == HSMP_ERR_INVALID_INPUT)) {
128 		dev_err(sock->dev, "Message ID 0x%X failure : Invalid arguments (status = 0x%X)\n",
129 			msg->msg_id, mbox_status);
130 		return -EINVAL;
131 	} else if (unlikely(mbox_status == HSMP_ERR_PREREQ_NOT_SATISFIED)) {
132 		dev_err(sock->dev, "Message ID 0x%X failure : Prerequisite not satisfied (status = 0x%X)\n",
133 			msg->msg_id, mbox_status);
134 		return -EREMOTEIO;
135 	} else if (unlikely(mbox_status == HSMP_ERR_SMU_BUSY)) {
136 		dev_err(sock->dev, "Message ID 0x%X failure : SMU BUSY (status = 0x%X)\n",
137 			msg->msg_id, mbox_status);
138 		return -EBUSY;
139 	} else if (unlikely(mbox_status != HSMP_STATUS_OK)) {
140 		dev_err(sock->dev, "Message ID 0x%X unknown failure (status = 0x%X)\n",
141 			msg->msg_id, mbox_status);
142 		return -EIO;
143 	}
144 
145 	/*
146 	 * SMU has responded OK. Read response data.
147 	 * SMU reads the input arguments from eight 32 bit registers starting
148 	 * from SMN_HSMP_MSG_DATA and writes the response data to the same
149 	 * SMN_HSMP_MSG_DATA address.
150 	 * We copy the response data if any, back to the args[].
151 	 */
152 	index = 0;
153 	while (index < msg->response_sz) {
154 		ret = sock->amd_hsmp_rdwr(sock, mbinfo->msg_arg_off + (index << 2),
155 					  &msg->args[index], HSMP_RD);
156 		if (ret) {
157 			dev_err(sock->dev, "Error %d reading response %u for message ID:%u\n",
158 				ret, index, msg->msg_id);
159 			break;
160 		}
161 		index++;
162 	}
163 
164 	return ret;
165 }
166 
167 static int validate_message(struct hsmp_message *msg)
168 {
169 	/* msg_id against valid range of message IDs */
170 	if (msg->msg_id < HSMP_TEST || msg->msg_id >= HSMP_MSG_ID_MAX)
171 		return -ENOMSG;
172 
173 	/* msg_id is a reserved message ID */
174 	if (hsmp_msg_desc_table[msg->msg_id].type == HSMP_RSVD)
175 		return -ENOMSG;
176 
177 	/*
178 	 * num_args passed by user should match the num_args specified in
179 	 * message description table.
180 	 */
181 	if (msg->num_args != hsmp_msg_desc_table[msg->msg_id].num_args)
182 		return -EINVAL;
183 
184 	/*
185 	 * Some older HSMP SET messages are updated to add GET in the same message.
186 	 * In these messages, GET returns the current value and SET also returns
187 	 * the successfully set value. To support this GET and SET in same message
188 	 * while maintaining backward compatibility for the HSMP users,
189 	 * hsmp_msg_desc_table[] indicates only maximum allowed response_sz.
190 	 */
191 	if (hsmp_msg_desc_table[msg->msg_id].type == HSMP_SET_GET) {
192 		if (msg->response_sz > hsmp_msg_desc_table[msg->msg_id].response_sz)
193 			return -EINVAL;
194 	} else {
195 		/* only HSMP_SET or HSMP_GET messages go through this strict check */
196 		if (msg->response_sz != hsmp_msg_desc_table[msg->msg_id].response_sz)
197 			return -EINVAL;
198 	}
199 	return 0;
200 }
201 
202 int hsmp_send_message(struct hsmp_message *msg)
203 {
204 	struct hsmp_socket *sock;
205 	unsigned int sock_ind;
206 	int ret;
207 
208 	if (!msg)
209 		return -EINVAL;
210 	ret = validate_message(msg);
211 	if (ret)
212 		return ret;
213 
214 	if (!hsmp_pdev.sock || msg->sock_ind >= hsmp_pdev.num_sockets)
215 		return -ENODEV;
216 
217 	/*
218 	 * Sanitize sock_ind after the bounds check.  A mispredicted branch can
219 	 * still let the CPU speculatively use msg->sock_ind as an index into
220 	 * hsmp_pdev.sock[] (Spectre v1, CVE-2017-5753), including for callers
221 	 * other than hsmp_ioctl_msg() that pass a user-derived socket index.
222 	 */
223 	sock_ind = array_index_nospec(msg->sock_ind, hsmp_pdev.num_sockets);
224 	sock = &hsmp_pdev.sock[sock_ind];
225 
226 	ret = down_interruptible(&sock->hsmp_sem);
227 	if (ret < 0)
228 		return ret;
229 
230 	ret = __hsmp_send_message(sock, msg);
231 
232 	up(&sock->hsmp_sem);
233 
234 	return ret;
235 }
236 EXPORT_SYMBOL_NS_GPL(hsmp_send_message, "AMD_HSMP");
237 
238 int hsmp_msg_get_nargs(u16 sock_ind, u32 msg_id, u32 *data, u8 num_args)
239 {
240 	struct hsmp_message msg = {};
241 	unsigned int i;
242 	int ret;
243 
244 	if (!data)
245 		return -EINVAL;
246 	msg.msg_id = msg_id;
247 	msg.sock_ind = sock_ind;
248 	msg.response_sz = num_args;
249 
250 	ret = hsmp_send_message(&msg);
251 	if (ret)
252 		return ret;
253 
254 	for (i = 0; i < num_args; i++)
255 		data[i] = msg.args[i];
256 
257 	return 0;
258 }
259 EXPORT_SYMBOL_NS_GPL(hsmp_msg_get_nargs, "AMD_HSMP");
260 
261 int hsmp_test(u16 sock_ind, u32 value)
262 {
263 	struct hsmp_message msg = { 0 };
264 	int ret;
265 
266 	/*
267 	 * Test the hsmp port by performing TEST command. The test message
268 	 * takes one argument and returns the value of that argument + 1.
269 	 */
270 	msg.msg_id	= HSMP_TEST;
271 	msg.num_args	= 1;
272 	msg.response_sz	= 1;
273 	msg.args[0]	= value;
274 	msg.sock_ind	= sock_ind;
275 
276 	ret = hsmp_send_message(&msg);
277 	if (ret)
278 		return ret;
279 
280 	/* Check the response value */
281 	if (msg.args[0] != (value + 1)) {
282 		dev_err(hsmp_pdev.sock[sock_ind].dev,
283 			"Socket %d test message failed, Expected 0x%08X, received 0x%08X\n",
284 			sock_ind, (value + 1), msg.args[0]);
285 		return -EBADE;
286 	}
287 
288 	return ret;
289 }
290 EXPORT_SYMBOL_NS_GPL(hsmp_test, "AMD_HSMP");
291 
292 static bool is_get_msg(struct hsmp_message *msg)
293 {
294 	if (hsmp_msg_desc_table[msg->msg_id].type == HSMP_GET)
295 		return true;
296 
297 	if (hsmp_msg_desc_table[msg->msg_id].type == HSMP_SET_GET &&
298 	    (msg->args[0] & CHECK_GET_BIT))
299 		return true;
300 
301 	return false;
302 }
303 
304 long hsmp_ioctl(struct file *fp, unsigned int cmd, unsigned long arg)
305 {
306 	int __user *arguser = (int  __user *)arg;
307 	struct hsmp_message msg = { 0 };
308 	int ret;
309 
310 	if (copy_struct_from_user(&msg, sizeof(msg), arguser, sizeof(struct hsmp_message)))
311 		return -EFAULT;
312 
313 	/*
314 	 * Check msg_id is within the range of supported msg ids
315 	 * i.e within the array bounds of hsmp_msg_desc_table
316 	 */
317 	if (msg.msg_id < HSMP_TEST || msg.msg_id >= HSMP_MSG_ID_MAX)
318 		return -ENOMSG;
319 
320 	/*
321 	 * Sanitize the user-controlled msg_id against speculative
322 	 * execution.  The bounds check above retires the out-of-range
323 	 * case with -ENOMSG, but a mispredicted branch can still let the
324 	 * CPU speculatively use msg_id as an index into
325 	 * hsmp_msg_desc_table[] (here and in validate_message() /
326 	 * is_get_msg() called downstream via hsmp_send_message()), and
327 	 * pull arbitrary kernel memory into the cache (Spectre v1,
328 	 * CVE-2017-5753).  Clamp once into msg.msg_id so every downstream
329 	 * dereference sees the sanitized value.
330 	 */
331 	msg.msg_id = array_index_nospec(msg.msg_id, HSMP_MSG_ID_MAX);
332 
333 	switch (fp->f_mode & (FMODE_WRITE | FMODE_READ)) {
334 	case FMODE_WRITE:
335 		/*
336 		 * Device is opened in O_WRONLY mode
337 		 * Execute only set/configure commands
338 		 */
339 		if (is_get_msg(&msg))
340 			return -EPERM;
341 		break;
342 	case FMODE_READ:
343 		/*
344 		 * Device is opened in O_RDONLY mode
345 		 * Execute only get/monitor commands
346 		 */
347 		if (!is_get_msg(&msg))
348 			return -EPERM;
349 		break;
350 	case FMODE_READ | FMODE_WRITE:
351 		/*
352 		 * Device is opened in O_RDWR mode
353 		 * Execute both get/monitor and set/configure commands
354 		 */
355 		break;
356 	default:
357 		return -EPERM;
358 	}
359 
360 	ret = hsmp_send_message(&msg);
361 	if (ret)
362 		return ret;
363 
364 	if (hsmp_msg_desc_table[msg.msg_id].response_sz > 0) {
365 		/* Copy results back to user for get/monitor commands */
366 		if (copy_to_user(arguser, &msg, sizeof(struct hsmp_message)))
367 			return -EFAULT;
368 	}
369 
370 	return 0;
371 }
372 
373 ssize_t hsmp_metric_tbl_read(struct hsmp_socket *sock, char *buf, size_t size)
374 {
375 	struct hsmp_message msg = { 0 };
376 	int ret;
377 
378 	if (!sock || !buf)
379 		return -EINVAL;
380 
381 	if (!sock->metric_tbl_addr) {
382 		dev_err(sock->dev, "Metrics table address not available\n");
383 		return -ENOMEM;
384 	}
385 
386 	/* Do not support lseek(), also don't allow more than the size of metric table */
387 	if (size != sizeof(struct hsmp_metric_table)) {
388 		dev_err(sock->dev, "Wrong buffer size\n");
389 		return -EINVAL;
390 	}
391 
392 	msg.msg_id	= HSMP_GET_METRIC_TABLE;
393 	msg.sock_ind	= sock->sock_ind;
394 
395 	ret = hsmp_send_message(&msg);
396 	if (ret)
397 		return ret;
398 	memcpy_fromio(buf, sock->metric_tbl_addr, size);
399 
400 	return size;
401 }
402 EXPORT_SYMBOL_NS_GPL(hsmp_metric_tbl_read, "AMD_HSMP");
403 
404 int hsmp_get_tbl_dram_base(u16 sock_ind)
405 {
406 	struct hsmp_socket *sock = &hsmp_pdev.sock[sock_ind];
407 	struct hsmp_message msg = { 0 };
408 	phys_addr_t dram_addr;
409 	int ret;
410 
411 	msg.sock_ind	= sock_ind;
412 	msg.response_sz	= hsmp_msg_desc_table[HSMP_GET_METRIC_TABLE_DRAM_ADDR].response_sz;
413 	msg.msg_id	= HSMP_GET_METRIC_TABLE_DRAM_ADDR;
414 
415 	ret = hsmp_send_message(&msg);
416 	if (ret)
417 		return ret;
418 
419 	/*
420 	 * calculate the metric table DRAM address from lower and upper 32 bits
421 	 * sent from SMU and ioremap it to virtual address.
422 	 */
423 	dram_addr = msg.args[0] | ((u64)(msg.args[1]) << 32);
424 	if (!dram_addr) {
425 		dev_err(sock->dev, "Invalid DRAM address for metric table\n");
426 		return -ENOMEM;
427 	}
428 	sock->metric_tbl_addr = devm_ioremap(sock->dev, dram_addr,
429 					     sizeof(struct hsmp_metric_table));
430 	if (!sock->metric_tbl_addr) {
431 		dev_err(sock->dev, "Failed to ioremap metric table addr\n");
432 		return -ENOMEM;
433 	}
434 	return 0;
435 }
436 EXPORT_SYMBOL_NS_GPL(hsmp_get_tbl_dram_base, "AMD_HSMP");
437 
438 int hsmp_cache_proto_ver(u16 sock_ind)
439 {
440 	struct hsmp_message msg = { 0 };
441 	int ret;
442 
443 	msg.msg_id	= HSMP_GET_PROTO_VER;
444 	msg.sock_ind	= sock_ind;
445 	msg.response_sz = hsmp_msg_desc_table[HSMP_GET_PROTO_VER].response_sz;
446 
447 	ret = hsmp_send_message(&msg);
448 	if (!ret)
449 		hsmp_pdev.proto_ver = msg.args[0];
450 
451 	return ret;
452 }
453 EXPORT_SYMBOL_NS_GPL(hsmp_cache_proto_ver, "AMD_HSMP");
454 
455 static const struct file_operations hsmp_fops = {
456 	.owner		= THIS_MODULE,
457 	.unlocked_ioctl	= hsmp_ioctl,
458 	.compat_ioctl	= hsmp_ioctl,
459 };
460 
461 int hsmp_misc_register(struct device *dev)
462 {
463 	hsmp_pdev.mdev.name	= HSMP_CDEV_NAME;
464 	hsmp_pdev.mdev.minor	= MISC_DYNAMIC_MINOR;
465 	hsmp_pdev.mdev.fops	= &hsmp_fops;
466 	hsmp_pdev.mdev.parent	= dev;
467 	hsmp_pdev.mdev.nodename	= HSMP_DEVNODE_NAME;
468 	hsmp_pdev.mdev.mode	= 0644;
469 
470 	return misc_register(&hsmp_pdev.mdev);
471 }
472 EXPORT_SYMBOL_NS_GPL(hsmp_misc_register, "AMD_HSMP");
473 
474 void hsmp_misc_deregister(void)
475 {
476 	misc_deregister(&hsmp_pdev.mdev);
477 }
478 EXPORT_SYMBOL_NS_GPL(hsmp_misc_deregister, "AMD_HSMP");
479 
480 struct hsmp_plat_device *get_hsmp_pdev(void)
481 {
482 	return &hsmp_pdev;
483 }
484 EXPORT_SYMBOL_NS_GPL(get_hsmp_pdev, "AMD_HSMP");
485 
486 MODULE_DESCRIPTION("AMD HSMP Common driver");
487 MODULE_VERSION(DRIVER_VERSION);
488 MODULE_LICENSE("GPL");
489