xref: /openbmc/linux/drivers/cxl/core/mbox.c (revision 59f8d1510739e92135df62d52e8c29bc075c46ad)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2020 Intel Corporation. All rights reserved. */
3 #include <linux/security.h>
4 #include <linux/debugfs.h>
5 #include <linux/ktime.h>
6 #include <linux/mutex.h>
7 #include <asm/unaligned.h>
8 #include <cxlpci.h>
9 #include <cxlmem.h>
10 #include <cxl.h>
11 
12 #include "core.h"
13 #include "trace.h"
14 
15 static bool cxl_raw_allow_all;
16 
17 /**
18  * DOC: cxl mbox
19  *
20  * Core implementation of the CXL 2.0 Type-3 Memory Device Mailbox. The
21  * implementation is used by the cxl_pci driver to initialize the device
22  * and implement the cxl_mem.h IOCTL UAPI. It also implements the
23  * backend of the cxl_pmem_ctl() transport for LIBNVDIMM.
24  */
25 
26 #define cxl_for_each_cmd(cmd)                                                  \
27 	for ((cmd) = &cxl_mem_commands[0];                                     \
28 	     ((cmd) - cxl_mem_commands) < ARRAY_SIZE(cxl_mem_commands); (cmd)++)
29 
30 #define CXL_CMD(_id, sin, sout, _flags)                                        \
31 	[CXL_MEM_COMMAND_ID_##_id] = {                                         \
32 	.info =	{                                                              \
33 			.id = CXL_MEM_COMMAND_ID_##_id,                        \
34 			.size_in = sin,                                        \
35 			.size_out = sout,                                      \
36 		},                                                             \
37 	.opcode = CXL_MBOX_OP_##_id,                                           \
38 	.flags = _flags,                                                       \
39 	}
40 
41 #define CXL_VARIABLE_PAYLOAD	~0U
42 /*
43  * This table defines the supported mailbox commands for the driver. This table
44  * is made up of a UAPI structure. Non-negative values as parameters in the
45  * table will be validated against the user's input. For example, if size_in is
46  * 0, and the user passed in 1, it is an error.
47  */
48 static struct cxl_mem_command cxl_mem_commands[CXL_MEM_COMMAND_ID_MAX] = {
49 	CXL_CMD(IDENTIFY, 0, 0x43, CXL_CMD_FLAG_FORCE_ENABLE),
50 #ifdef CONFIG_CXL_MEM_RAW_COMMANDS
51 	CXL_CMD(RAW, CXL_VARIABLE_PAYLOAD, CXL_VARIABLE_PAYLOAD, 0),
52 #endif
53 	CXL_CMD(GET_SUPPORTED_LOGS, 0, CXL_VARIABLE_PAYLOAD, CXL_CMD_FLAG_FORCE_ENABLE),
54 	CXL_CMD(GET_FW_INFO, 0, 0x50, 0),
55 	CXL_CMD(GET_PARTITION_INFO, 0, 0x20, 0),
56 	CXL_CMD(GET_LSA, 0x8, CXL_VARIABLE_PAYLOAD, 0),
57 	CXL_CMD(GET_HEALTH_INFO, 0, 0x12, 0),
58 	CXL_CMD(GET_LOG, 0x18, CXL_VARIABLE_PAYLOAD, CXL_CMD_FLAG_FORCE_ENABLE),
59 	CXL_CMD(SET_PARTITION_INFO, 0x0a, 0, 0),
60 	CXL_CMD(SET_LSA, CXL_VARIABLE_PAYLOAD, 0, 0),
61 	CXL_CMD(GET_ALERT_CONFIG, 0, 0x10, 0),
62 	CXL_CMD(SET_ALERT_CONFIG, 0xc, 0, 0),
63 	CXL_CMD(GET_SHUTDOWN_STATE, 0, 0x1, 0),
64 	CXL_CMD(SET_SHUTDOWN_STATE, 0x1, 0, 0),
65 	CXL_CMD(GET_SCAN_MEDIA_CAPS, 0x10, 0x4, 0),
66 };
67 
68 /*
69  * Commands that RAW doesn't permit. The rationale for each:
70  *
71  * CXL_MBOX_OP_ACTIVATE_FW: Firmware activation requires adjustment /
72  * coordination of transaction timeout values at the root bridge level.
73  *
74  * CXL_MBOX_OP_SET_PARTITION_INFO: The device memory map may change live
75  * and needs to be coordinated with HDM updates.
76  *
77  * CXL_MBOX_OP_SET_LSA: The label storage area may be cached by the
78  * driver and any writes from userspace invalidates those contents.
79  *
80  * CXL_MBOX_OP_SET_SHUTDOWN_STATE: Set shutdown state assumes no writes
81  * to the device after it is marked clean, userspace can not make that
82  * assertion.
83  *
84  * CXL_MBOX_OP_[GET_]SCAN_MEDIA: The kernel provides a native error list that
85  * is kept up to date with patrol notifications and error management.
86  *
87  * CXL_MBOX_OP_[GET_,INJECT_,CLEAR_]POISON: These commands require kernel
88  * driver orchestration for safety.
89  */
90 static u16 cxl_disabled_raw_commands[] = {
91 	CXL_MBOX_OP_ACTIVATE_FW,
92 	CXL_MBOX_OP_SET_PARTITION_INFO,
93 	CXL_MBOX_OP_SET_LSA,
94 	CXL_MBOX_OP_SET_SHUTDOWN_STATE,
95 	CXL_MBOX_OP_SCAN_MEDIA,
96 	CXL_MBOX_OP_GET_SCAN_MEDIA,
97 	CXL_MBOX_OP_GET_POISON,
98 	CXL_MBOX_OP_INJECT_POISON,
99 	CXL_MBOX_OP_CLEAR_POISON,
100 };
101 
102 /*
103  * Command sets that RAW doesn't permit. All opcodes in this set are
104  * disabled because they pass plain text security payloads over the
105  * user/kernel boundary. This functionality is intended to be wrapped
106  * behind the keys ABI which allows for encrypted payloads in the UAPI
107  */
108 static u8 security_command_sets[] = {
109 	0x44, /* Sanitize */
110 	0x45, /* Persistent Memory Data-at-rest Security */
111 	0x46, /* Security Passthrough */
112 };
113 
114 static bool cxl_is_security_command(u16 opcode)
115 {
116 	int i;
117 
118 	for (i = 0; i < ARRAY_SIZE(security_command_sets); i++)
119 		if (security_command_sets[i] == (opcode >> 8))
120 			return true;
121 	return false;
122 }
123 
124 static bool cxl_is_poison_command(u16 opcode)
125 {
126 #define CXL_MBOX_OP_POISON_CMDS 0x43
127 
128 	if ((opcode >> 8) == CXL_MBOX_OP_POISON_CMDS)
129 		return true;
130 
131 	return false;
132 }
133 
134 static void cxl_set_poison_cmd_enabled(struct cxl_poison_state *poison,
135 				       u16 opcode)
136 {
137 	switch (opcode) {
138 	case CXL_MBOX_OP_GET_POISON:
139 		set_bit(CXL_POISON_ENABLED_LIST, poison->enabled_cmds);
140 		break;
141 	case CXL_MBOX_OP_INJECT_POISON:
142 		set_bit(CXL_POISON_ENABLED_INJECT, poison->enabled_cmds);
143 		break;
144 	case CXL_MBOX_OP_CLEAR_POISON:
145 		set_bit(CXL_POISON_ENABLED_CLEAR, poison->enabled_cmds);
146 		break;
147 	case CXL_MBOX_OP_GET_SCAN_MEDIA_CAPS:
148 		set_bit(CXL_POISON_ENABLED_SCAN_CAPS, poison->enabled_cmds);
149 		break;
150 	case CXL_MBOX_OP_SCAN_MEDIA:
151 		set_bit(CXL_POISON_ENABLED_SCAN_MEDIA, poison->enabled_cmds);
152 		break;
153 	case CXL_MBOX_OP_GET_SCAN_MEDIA:
154 		set_bit(CXL_POISON_ENABLED_SCAN_RESULTS, poison->enabled_cmds);
155 		break;
156 	default:
157 		break;
158 	}
159 }
160 
161 static struct cxl_mem_command *cxl_mem_find_command(u16 opcode)
162 {
163 	struct cxl_mem_command *c;
164 
165 	cxl_for_each_cmd(c)
166 		if (c->opcode == opcode)
167 			return c;
168 
169 	return NULL;
170 }
171 
172 static const char *cxl_mem_opcode_to_name(u16 opcode)
173 {
174 	struct cxl_mem_command *c;
175 
176 	c = cxl_mem_find_command(opcode);
177 	if (!c)
178 		return NULL;
179 
180 	return cxl_command_names[c->info.id].name;
181 }
182 
183 /**
184  * cxl_internal_send_cmd() - Kernel internal interface to send a mailbox command
185  * @mds: The driver data for the operation
186  * @mbox_cmd: initialized command to execute
187  *
188  * Context: Any context.
189  * Return:
190  *  * %>=0	- Number of bytes returned in @out.
191  *  * %-E2BIG	- Payload is too large for hardware.
192  *  * %-EBUSY	- Couldn't acquire exclusive mailbox access.
193  *  * %-EFAULT	- Hardware error occurred.
194  *  * %-ENXIO	- Command completed, but device reported an error.
195  *  * %-EIO	- Unexpected output size.
196  *
197  * Mailbox commands may execute successfully yet the device itself reported an
198  * error. While this distinction can be useful for commands from userspace, the
199  * kernel will only be able to use results when both are successful.
200  */
201 int cxl_internal_send_cmd(struct cxl_memdev_state *mds,
202 			  struct cxl_mbox_cmd *mbox_cmd)
203 {
204 	size_t out_size, min_out;
205 	int rc;
206 
207 	if (mbox_cmd->size_in > mds->payload_size ||
208 	    mbox_cmd->size_out > mds->payload_size)
209 		return -E2BIG;
210 
211 	out_size = mbox_cmd->size_out;
212 	min_out = mbox_cmd->min_out;
213 	rc = mds->mbox_send(mds, mbox_cmd);
214 	/*
215 	 * EIO is reserved for a payload size mismatch and mbox_send()
216 	 * may not return this error.
217 	 */
218 	if (WARN_ONCE(rc == -EIO, "Bad return code: -EIO"))
219 		return -ENXIO;
220 	if (rc)
221 		return rc;
222 
223 	if (mbox_cmd->return_code != CXL_MBOX_CMD_RC_SUCCESS)
224 		return cxl_mbox_cmd_rc2errno(mbox_cmd);
225 
226 	if (!out_size)
227 		return 0;
228 
229 	/*
230 	 * Variable sized output needs to at least satisfy the caller's
231 	 * minimum if not the fully requested size.
232 	 */
233 	if (min_out == 0)
234 		min_out = out_size;
235 
236 	if (mbox_cmd->size_out < min_out)
237 		return -EIO;
238 	return 0;
239 }
240 EXPORT_SYMBOL_NS_GPL(cxl_internal_send_cmd, CXL);
241 
242 static bool cxl_mem_raw_command_allowed(u16 opcode)
243 {
244 	int i;
245 
246 	if (!IS_ENABLED(CONFIG_CXL_MEM_RAW_COMMANDS))
247 		return false;
248 
249 	if (security_locked_down(LOCKDOWN_PCI_ACCESS))
250 		return false;
251 
252 	if (cxl_raw_allow_all)
253 		return true;
254 
255 	if (cxl_is_security_command(opcode))
256 		return false;
257 
258 	for (i = 0; i < ARRAY_SIZE(cxl_disabled_raw_commands); i++)
259 		if (cxl_disabled_raw_commands[i] == opcode)
260 			return false;
261 
262 	return true;
263 }
264 
265 /**
266  * cxl_payload_from_user_allowed() - Check contents of in_payload.
267  * @opcode: The mailbox command opcode.
268  * @payload_in: Pointer to the input payload passed in from user space.
269  *
270  * Return:
271  *  * true	- payload_in passes check for @opcode.
272  *  * false	- payload_in contains invalid or unsupported values.
273  *
274  * The driver may inspect payload contents before sending a mailbox
275  * command from user space to the device. The intent is to reject
276  * commands with input payloads that are known to be unsafe. This
277  * check is not intended to replace the users careful selection of
278  * mailbox command parameters and makes no guarantee that the user
279  * command will succeed, nor that it is appropriate.
280  *
281  * The specific checks are determined by the opcode.
282  */
283 static bool cxl_payload_from_user_allowed(u16 opcode, void *payload_in)
284 {
285 	switch (opcode) {
286 	case CXL_MBOX_OP_SET_PARTITION_INFO: {
287 		struct cxl_mbox_set_partition_info *pi = payload_in;
288 
289 		if (pi->flags & CXL_SET_PARTITION_IMMEDIATE_FLAG)
290 			return false;
291 		break;
292 	}
293 	default:
294 		break;
295 	}
296 	return true;
297 }
298 
299 static int cxl_mbox_cmd_ctor(struct cxl_mbox_cmd *mbox,
300 			     struct cxl_memdev_state *mds, u16 opcode,
301 			     size_t in_size, size_t out_size, u64 in_payload)
302 {
303 	*mbox = (struct cxl_mbox_cmd) {
304 		.opcode = opcode,
305 		.size_in = in_size,
306 	};
307 
308 	if (in_size) {
309 		mbox->payload_in = vmemdup_user(u64_to_user_ptr(in_payload),
310 						in_size);
311 		if (IS_ERR(mbox->payload_in))
312 			return PTR_ERR(mbox->payload_in);
313 
314 		if (!cxl_payload_from_user_allowed(opcode, mbox->payload_in)) {
315 			dev_dbg(mds->cxlds.dev, "%s: input payload not allowed\n",
316 				cxl_mem_opcode_to_name(opcode));
317 			kvfree(mbox->payload_in);
318 			return -EBUSY;
319 		}
320 	}
321 
322 	/* Prepare to handle a full payload for variable sized output */
323 	if (out_size == CXL_VARIABLE_PAYLOAD)
324 		mbox->size_out = mds->payload_size;
325 	else
326 		mbox->size_out = out_size;
327 
328 	if (mbox->size_out) {
329 		mbox->payload_out = kvzalloc(mbox->size_out, GFP_KERNEL);
330 		if (!mbox->payload_out) {
331 			kvfree(mbox->payload_in);
332 			return -ENOMEM;
333 		}
334 	}
335 	return 0;
336 }
337 
338 static void cxl_mbox_cmd_dtor(struct cxl_mbox_cmd *mbox)
339 {
340 	kvfree(mbox->payload_in);
341 	kvfree(mbox->payload_out);
342 }
343 
344 static int cxl_to_mem_cmd_raw(struct cxl_mem_command *mem_cmd,
345 			      const struct cxl_send_command *send_cmd,
346 			      struct cxl_memdev_state *mds)
347 {
348 	if (send_cmd->raw.rsvd)
349 		return -EINVAL;
350 
351 	/*
352 	 * Unlike supported commands, the output size of RAW commands
353 	 * gets passed along without further checking, so it must be
354 	 * validated here.
355 	 */
356 	if (send_cmd->out.size > mds->payload_size)
357 		return -EINVAL;
358 
359 	if (!cxl_mem_raw_command_allowed(send_cmd->raw.opcode))
360 		return -EPERM;
361 
362 	dev_WARN_ONCE(mds->cxlds.dev, true, "raw command path used\n");
363 
364 	*mem_cmd = (struct cxl_mem_command) {
365 		.info = {
366 			.id = CXL_MEM_COMMAND_ID_RAW,
367 			.size_in = send_cmd->in.size,
368 			.size_out = send_cmd->out.size,
369 		},
370 		.opcode = send_cmd->raw.opcode
371 	};
372 
373 	return 0;
374 }
375 
376 static int cxl_to_mem_cmd(struct cxl_mem_command *mem_cmd,
377 			  const struct cxl_send_command *send_cmd,
378 			  struct cxl_memdev_state *mds)
379 {
380 	struct cxl_mem_command *c = &cxl_mem_commands[send_cmd->id];
381 	const struct cxl_command_info *info = &c->info;
382 
383 	if (send_cmd->flags & ~CXL_MEM_COMMAND_FLAG_MASK)
384 		return -EINVAL;
385 
386 	if (send_cmd->rsvd)
387 		return -EINVAL;
388 
389 	if (send_cmd->in.rsvd || send_cmd->out.rsvd)
390 		return -EINVAL;
391 
392 	/* Check that the command is enabled for hardware */
393 	if (!test_bit(info->id, mds->enabled_cmds))
394 		return -ENOTTY;
395 
396 	/* Check that the command is not claimed for exclusive kernel use */
397 	if (test_bit(info->id, mds->exclusive_cmds))
398 		return -EBUSY;
399 
400 	/* Check the input buffer is the expected size */
401 	if ((info->size_in != CXL_VARIABLE_PAYLOAD) &&
402 	    (info->size_in != send_cmd->in.size))
403 		return -ENOMEM;
404 
405 	/* Check the output buffer is at least large enough */
406 	if ((info->size_out != CXL_VARIABLE_PAYLOAD) &&
407 	    (send_cmd->out.size < info->size_out))
408 		return -ENOMEM;
409 
410 	*mem_cmd = (struct cxl_mem_command) {
411 		.info = {
412 			.id = info->id,
413 			.flags = info->flags,
414 			.size_in = send_cmd->in.size,
415 			.size_out = send_cmd->out.size,
416 		},
417 		.opcode = c->opcode
418 	};
419 
420 	return 0;
421 }
422 
423 /**
424  * cxl_validate_cmd_from_user() - Check fields for CXL_MEM_SEND_COMMAND.
425  * @mbox_cmd: Sanitized and populated &struct cxl_mbox_cmd.
426  * @mds: The driver data for the operation
427  * @send_cmd: &struct cxl_send_command copied in from userspace.
428  *
429  * Return:
430  *  * %0	- @out_cmd is ready to send.
431  *  * %-ENOTTY	- Invalid command specified.
432  *  * %-EINVAL	- Reserved fields or invalid values were used.
433  *  * %-ENOMEM	- Input or output buffer wasn't sized properly.
434  *  * %-EPERM	- Attempted to use a protected command.
435  *  * %-EBUSY	- Kernel has claimed exclusive access to this opcode
436  *
437  * The result of this command is a fully validated command in @mbox_cmd that is
438  * safe to send to the hardware.
439  */
440 static int cxl_validate_cmd_from_user(struct cxl_mbox_cmd *mbox_cmd,
441 				      struct cxl_memdev_state *mds,
442 				      const struct cxl_send_command *send_cmd)
443 {
444 	struct cxl_mem_command mem_cmd;
445 	int rc;
446 
447 	if (send_cmd->id == 0 || send_cmd->id >= CXL_MEM_COMMAND_ID_MAX)
448 		return -ENOTTY;
449 
450 	/*
451 	 * The user can never specify an input payload larger than what hardware
452 	 * supports, but output can be arbitrarily large (simply write out as
453 	 * much data as the hardware provides).
454 	 */
455 	if (send_cmd->in.size > mds->payload_size)
456 		return -EINVAL;
457 
458 	/* Sanitize and construct a cxl_mem_command */
459 	if (send_cmd->id == CXL_MEM_COMMAND_ID_RAW)
460 		rc = cxl_to_mem_cmd_raw(&mem_cmd, send_cmd, mds);
461 	else
462 		rc = cxl_to_mem_cmd(&mem_cmd, send_cmd, mds);
463 
464 	if (rc)
465 		return rc;
466 
467 	/* Sanitize and construct a cxl_mbox_cmd */
468 	return cxl_mbox_cmd_ctor(mbox_cmd, mds, mem_cmd.opcode,
469 				 mem_cmd.info.size_in, mem_cmd.info.size_out,
470 				 send_cmd->in.payload);
471 }
472 
473 int cxl_query_cmd(struct cxl_memdev *cxlmd,
474 		  struct cxl_mem_query_commands __user *q)
475 {
476 	struct cxl_memdev_state *mds = to_cxl_memdev_state(cxlmd->cxlds);
477 	struct device *dev = &cxlmd->dev;
478 	struct cxl_mem_command *cmd;
479 	u32 n_commands;
480 	int j = 0;
481 
482 	dev_dbg(dev, "Query IOCTL\n");
483 
484 	if (get_user(n_commands, &q->n_commands))
485 		return -EFAULT;
486 
487 	/* returns the total number if 0 elements are requested. */
488 	if (n_commands == 0)
489 		return put_user(ARRAY_SIZE(cxl_mem_commands), &q->n_commands);
490 
491 	/*
492 	 * otherwise, return max(n_commands, total commands) cxl_command_info
493 	 * structures.
494 	 */
495 	cxl_for_each_cmd(cmd) {
496 		struct cxl_command_info info = cmd->info;
497 
498 		if (test_bit(info.id, mds->enabled_cmds))
499 			info.flags |= CXL_MEM_COMMAND_FLAG_ENABLED;
500 		if (test_bit(info.id, mds->exclusive_cmds))
501 			info.flags |= CXL_MEM_COMMAND_FLAG_EXCLUSIVE;
502 
503 		if (copy_to_user(&q->commands[j++], &info, sizeof(info)))
504 			return -EFAULT;
505 
506 		if (j == n_commands)
507 			break;
508 	}
509 
510 	return 0;
511 }
512 
513 /**
514  * handle_mailbox_cmd_from_user() - Dispatch a mailbox command for userspace.
515  * @mds: The driver data for the operation
516  * @mbox_cmd: The validated mailbox command.
517  * @out_payload: Pointer to userspace's output payload.
518  * @size_out: (Input) Max payload size to copy out.
519  *            (Output) Payload size hardware generated.
520  * @retval: Hardware generated return code from the operation.
521  *
522  * Return:
523  *  * %0	- Mailbox transaction succeeded. This implies the mailbox
524  *		  protocol completed successfully not that the operation itself
525  *		  was successful.
526  *  * %-ENOMEM  - Couldn't allocate a bounce buffer.
527  *  * %-EFAULT	- Something happened with copy_to/from_user.
528  *  * %-EINTR	- Mailbox acquisition interrupted.
529  *  * %-EXXX	- Transaction level failures.
530  *
531  * Dispatches a mailbox command on behalf of a userspace request.
532  * The output payload is copied to userspace.
533  *
534  * See cxl_send_cmd().
535  */
536 static int handle_mailbox_cmd_from_user(struct cxl_memdev_state *mds,
537 					struct cxl_mbox_cmd *mbox_cmd,
538 					u64 out_payload, s32 *size_out,
539 					u32 *retval)
540 {
541 	struct device *dev = mds->cxlds.dev;
542 	int rc;
543 
544 	dev_dbg(dev,
545 		"Submitting %s command for user\n"
546 		"\topcode: %x\n"
547 		"\tsize: %zx\n",
548 		cxl_mem_opcode_to_name(mbox_cmd->opcode),
549 		mbox_cmd->opcode, mbox_cmd->size_in);
550 
551 	rc = mds->mbox_send(mds, mbox_cmd);
552 	if (rc)
553 		goto out;
554 
555 	/*
556 	 * @size_out contains the max size that's allowed to be written back out
557 	 * to userspace. While the payload may have written more output than
558 	 * this it will have to be ignored.
559 	 */
560 	if (mbox_cmd->size_out) {
561 		dev_WARN_ONCE(dev, mbox_cmd->size_out > *size_out,
562 			      "Invalid return size\n");
563 		if (copy_to_user(u64_to_user_ptr(out_payload),
564 				 mbox_cmd->payload_out, mbox_cmd->size_out)) {
565 			rc = -EFAULT;
566 			goto out;
567 		}
568 	}
569 
570 	*size_out = mbox_cmd->size_out;
571 	*retval = mbox_cmd->return_code;
572 
573 out:
574 	cxl_mbox_cmd_dtor(mbox_cmd);
575 	return rc;
576 }
577 
578 int cxl_send_cmd(struct cxl_memdev *cxlmd, struct cxl_send_command __user *s)
579 {
580 	struct cxl_memdev_state *mds = to_cxl_memdev_state(cxlmd->cxlds);
581 	struct device *dev = &cxlmd->dev;
582 	struct cxl_send_command send;
583 	struct cxl_mbox_cmd mbox_cmd;
584 	int rc;
585 
586 	dev_dbg(dev, "Send IOCTL\n");
587 
588 	if (copy_from_user(&send, s, sizeof(send)))
589 		return -EFAULT;
590 
591 	rc = cxl_validate_cmd_from_user(&mbox_cmd, mds, &send);
592 	if (rc)
593 		return rc;
594 
595 	rc = handle_mailbox_cmd_from_user(mds, &mbox_cmd, send.out.payload,
596 					  &send.out.size, &send.retval);
597 	if (rc)
598 		return rc;
599 
600 	if (copy_to_user(s, &send, sizeof(send)))
601 		return -EFAULT;
602 
603 	return 0;
604 }
605 
606 static int cxl_xfer_log(struct cxl_memdev_state *mds, uuid_t *uuid,
607 			u32 *size, u8 *out)
608 {
609 	u32 remaining = *size;
610 	u32 offset = 0;
611 
612 	while (remaining) {
613 		u32 xfer_size = min_t(u32, remaining, mds->payload_size);
614 		struct cxl_mbox_cmd mbox_cmd;
615 		struct cxl_mbox_get_log log;
616 		int rc;
617 
618 		log = (struct cxl_mbox_get_log) {
619 			.uuid = *uuid,
620 			.offset = cpu_to_le32(offset),
621 			.length = cpu_to_le32(xfer_size),
622 		};
623 
624 		mbox_cmd = (struct cxl_mbox_cmd) {
625 			.opcode = CXL_MBOX_OP_GET_LOG,
626 			.size_in = sizeof(log),
627 			.payload_in = &log,
628 			.size_out = xfer_size,
629 			.payload_out = out,
630 		};
631 
632 		rc = cxl_internal_send_cmd(mds, &mbox_cmd);
633 
634 		/*
635 		 * The output payload length that indicates the number
636 		 * of valid bytes can be smaller than the Log buffer
637 		 * size.
638 		 */
639 		if (rc == -EIO && mbox_cmd.size_out < xfer_size) {
640 			offset += mbox_cmd.size_out;
641 			break;
642 		}
643 
644 		if (rc < 0)
645 			return rc;
646 
647 		out += xfer_size;
648 		remaining -= xfer_size;
649 		offset += xfer_size;
650 	}
651 
652 	*size = offset;
653 
654 	return 0;
655 }
656 
657 /**
658  * cxl_walk_cel() - Walk through the Command Effects Log.
659  * @mds: The driver data for the operation
660  * @size: Length of the Command Effects Log.
661  * @cel: CEL
662  *
663  * Iterate over each entry in the CEL and determine if the driver supports the
664  * command. If so, the command is enabled for the device and can be used later.
665  */
666 static void cxl_walk_cel(struct cxl_memdev_state *mds, size_t size, u8 *cel)
667 {
668 	struct cxl_cel_entry *cel_entry;
669 	const int cel_entries = size / sizeof(*cel_entry);
670 	struct device *dev = mds->cxlds.dev;
671 	int i;
672 
673 	cel_entry = (struct cxl_cel_entry *) cel;
674 
675 	for (i = 0; i < cel_entries; i++) {
676 		u16 opcode = le16_to_cpu(cel_entry[i].opcode);
677 		struct cxl_mem_command *cmd = cxl_mem_find_command(opcode);
678 
679 		if (!cmd && !cxl_is_poison_command(opcode)) {
680 			dev_dbg(dev,
681 				"Opcode 0x%04x unsupported by driver\n", opcode);
682 			continue;
683 		}
684 
685 		if (cmd)
686 			set_bit(cmd->info.id, mds->enabled_cmds);
687 
688 		if (cxl_is_poison_command(opcode))
689 			cxl_set_poison_cmd_enabled(&mds->poison, opcode);
690 
691 		dev_dbg(dev, "Opcode 0x%04x enabled\n", opcode);
692 	}
693 }
694 
695 static struct cxl_mbox_get_supported_logs *cxl_get_gsl(struct cxl_memdev_state *mds)
696 {
697 	struct cxl_mbox_get_supported_logs *ret;
698 	struct cxl_mbox_cmd mbox_cmd;
699 	int rc;
700 
701 	ret = kvmalloc(mds->payload_size, GFP_KERNEL);
702 	if (!ret)
703 		return ERR_PTR(-ENOMEM);
704 
705 	mbox_cmd = (struct cxl_mbox_cmd) {
706 		.opcode = CXL_MBOX_OP_GET_SUPPORTED_LOGS,
707 		.size_out = mds->payload_size,
708 		.payload_out = ret,
709 		/* At least the record number field must be valid */
710 		.min_out = 2,
711 	};
712 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
713 	if (rc < 0) {
714 		kvfree(ret);
715 		return ERR_PTR(rc);
716 	}
717 
718 
719 	return ret;
720 }
721 
722 enum {
723 	CEL_UUID,
724 	VENDOR_DEBUG_UUID,
725 };
726 
727 /* See CXL 2.0 Table 170. Get Log Input Payload */
728 static const uuid_t log_uuid[] = {
729 	[CEL_UUID] = DEFINE_CXL_CEL_UUID,
730 	[VENDOR_DEBUG_UUID] = DEFINE_CXL_VENDOR_DEBUG_UUID,
731 };
732 
733 /**
734  * cxl_enumerate_cmds() - Enumerate commands for a device.
735  * @mds: The driver data for the operation
736  *
737  * Returns 0 if enumerate completed successfully.
738  *
739  * CXL devices have optional support for certain commands. This function will
740  * determine the set of supported commands for the hardware and update the
741  * enabled_cmds bitmap in the @mds.
742  */
743 int cxl_enumerate_cmds(struct cxl_memdev_state *mds)
744 {
745 	struct cxl_mbox_get_supported_logs *gsl;
746 	struct device *dev = mds->cxlds.dev;
747 	struct cxl_mem_command *cmd;
748 	int i, rc;
749 
750 	gsl = cxl_get_gsl(mds);
751 	if (IS_ERR(gsl))
752 		return PTR_ERR(gsl);
753 
754 	rc = -ENOENT;
755 	for (i = 0; i < le16_to_cpu(gsl->entries); i++) {
756 		u32 size = le32_to_cpu(gsl->entry[i].size);
757 		uuid_t uuid = gsl->entry[i].uuid;
758 		u8 *log;
759 
760 		dev_dbg(dev, "Found LOG type %pU of size %d", &uuid, size);
761 
762 		if (!uuid_equal(&uuid, &log_uuid[CEL_UUID]))
763 			continue;
764 
765 		log = kvmalloc(size, GFP_KERNEL);
766 		if (!log) {
767 			rc = -ENOMEM;
768 			goto out;
769 		}
770 
771 		rc = cxl_xfer_log(mds, &uuid, &size, log);
772 		if (rc) {
773 			kvfree(log);
774 			goto out;
775 		}
776 
777 		cxl_walk_cel(mds, size, log);
778 		kvfree(log);
779 
780 		/* In case CEL was bogus, enable some default commands. */
781 		cxl_for_each_cmd(cmd)
782 			if (cmd->flags & CXL_CMD_FLAG_FORCE_ENABLE)
783 				set_bit(cmd->info.id, mds->enabled_cmds);
784 
785 		/* Found the required CEL */
786 		rc = 0;
787 	}
788 out:
789 	kvfree(gsl);
790 	return rc;
791 }
792 EXPORT_SYMBOL_NS_GPL(cxl_enumerate_cmds, CXL);
793 
794 /*
795  * General Media Event Record
796  * CXL rev 3.0 Section 8.2.9.2.1.1; Table 8-43
797  */
798 static const uuid_t gen_media_event_uuid =
799 	UUID_INIT(0xfbcd0a77, 0xc260, 0x417f,
800 		  0x85, 0xa9, 0x08, 0x8b, 0x16, 0x21, 0xeb, 0xa6);
801 
802 /*
803  * DRAM Event Record
804  * CXL rev 3.0 section 8.2.9.2.1.2; Table 8-44
805  */
806 static const uuid_t dram_event_uuid =
807 	UUID_INIT(0x601dcbb3, 0x9c06, 0x4eab,
808 		  0xb8, 0xaf, 0x4e, 0x9b, 0xfb, 0x5c, 0x96, 0x24);
809 
810 /*
811  * Memory Module Event Record
812  * CXL rev 3.0 section 8.2.9.2.1.3; Table 8-45
813  */
814 static const uuid_t mem_mod_event_uuid =
815 	UUID_INIT(0xfe927475, 0xdd59, 0x4339,
816 		  0xa5, 0x86, 0x79, 0xba, 0xb1, 0x13, 0xb7, 0x74);
817 
818 static void cxl_event_trace_record(const struct cxl_memdev *cxlmd,
819 				   enum cxl_event_log_type type,
820 				   struct cxl_event_record_raw *record)
821 {
822 	uuid_t *id = &record->hdr.id;
823 
824 	if (uuid_equal(id, &gen_media_event_uuid)) {
825 		struct cxl_event_gen_media *rec =
826 				(struct cxl_event_gen_media *)record;
827 
828 		trace_cxl_general_media(cxlmd, type, rec);
829 	} else if (uuid_equal(id, &dram_event_uuid)) {
830 		struct cxl_event_dram *rec = (struct cxl_event_dram *)record;
831 
832 		trace_cxl_dram(cxlmd, type, rec);
833 	} else if (uuid_equal(id, &mem_mod_event_uuid)) {
834 		struct cxl_event_mem_module *rec =
835 				(struct cxl_event_mem_module *)record;
836 
837 		trace_cxl_memory_module(cxlmd, type, rec);
838 	} else {
839 		/* For unknown record types print just the header */
840 		trace_cxl_generic_event(cxlmd, type, record);
841 	}
842 }
843 
844 static int cxl_clear_event_record(struct cxl_memdev_state *mds,
845 				  enum cxl_event_log_type log,
846 				  struct cxl_get_event_payload *get_pl)
847 {
848 	struct cxl_mbox_clear_event_payload *payload;
849 	u16 total = le16_to_cpu(get_pl->record_count);
850 	u8 max_handles = CXL_CLEAR_EVENT_MAX_HANDLES;
851 	size_t pl_size = struct_size(payload, handles, max_handles);
852 	struct cxl_mbox_cmd mbox_cmd;
853 	u16 cnt;
854 	int rc = 0;
855 	int i;
856 
857 	/* Payload size may limit the max handles */
858 	if (pl_size > mds->payload_size) {
859 		max_handles = (mds->payload_size - sizeof(*payload)) /
860 			      sizeof(__le16);
861 		pl_size = struct_size(payload, handles, max_handles);
862 	}
863 
864 	payload = kvzalloc(pl_size, GFP_KERNEL);
865 	if (!payload)
866 		return -ENOMEM;
867 
868 	*payload = (struct cxl_mbox_clear_event_payload) {
869 		.event_log = log,
870 	};
871 
872 	mbox_cmd = (struct cxl_mbox_cmd) {
873 		.opcode = CXL_MBOX_OP_CLEAR_EVENT_RECORD,
874 		.payload_in = payload,
875 		.size_in = pl_size,
876 	};
877 
878 	/*
879 	 * Clear Event Records uses u8 for the handle cnt while Get Event
880 	 * Record can return up to 0xffff records.
881 	 */
882 	i = 0;
883 	for (cnt = 0; cnt < total; cnt++) {
884 		payload->handles[i++] = get_pl->records[cnt].hdr.handle;
885 		dev_dbg(mds->cxlds.dev, "Event log '%d': Clearing %u\n", log,
886 			le16_to_cpu(payload->handles[i]));
887 
888 		if (i == max_handles) {
889 			payload->nr_recs = i;
890 			rc = cxl_internal_send_cmd(mds, &mbox_cmd);
891 			if (rc)
892 				goto free_pl;
893 			i = 0;
894 		}
895 	}
896 
897 	/* Clear what is left if any */
898 	if (i) {
899 		payload->nr_recs = i;
900 		mbox_cmd.size_in = struct_size(payload, handles, i);
901 		rc = cxl_internal_send_cmd(mds, &mbox_cmd);
902 		if (rc)
903 			goto free_pl;
904 	}
905 
906 free_pl:
907 	kvfree(payload);
908 	return rc;
909 }
910 
911 static void cxl_mem_get_records_log(struct cxl_memdev_state *mds,
912 				    enum cxl_event_log_type type)
913 {
914 	struct cxl_memdev *cxlmd = mds->cxlds.cxlmd;
915 	struct device *dev = mds->cxlds.dev;
916 	struct cxl_get_event_payload *payload;
917 	struct cxl_mbox_cmd mbox_cmd;
918 	u8 log_type = type;
919 	u16 nr_rec;
920 
921 	mutex_lock(&mds->event.log_lock);
922 	payload = mds->event.buf;
923 
924 	mbox_cmd = (struct cxl_mbox_cmd) {
925 		.opcode = CXL_MBOX_OP_GET_EVENT_RECORD,
926 		.payload_in = &log_type,
927 		.size_in = sizeof(log_type),
928 		.payload_out = payload,
929 		.size_out = mds->payload_size,
930 		.min_out = struct_size(payload, records, 0),
931 	};
932 
933 	do {
934 		int rc, i;
935 
936 		rc = cxl_internal_send_cmd(mds, &mbox_cmd);
937 		if (rc) {
938 			dev_err_ratelimited(dev,
939 				"Event log '%d': Failed to query event records : %d",
940 				type, rc);
941 			break;
942 		}
943 
944 		nr_rec = le16_to_cpu(payload->record_count);
945 		if (!nr_rec)
946 			break;
947 
948 		for (i = 0; i < nr_rec; i++)
949 			cxl_event_trace_record(cxlmd, type,
950 					       &payload->records[i]);
951 
952 		if (payload->flags & CXL_GET_EVENT_FLAG_OVERFLOW)
953 			trace_cxl_overflow(cxlmd, type, payload);
954 
955 		rc = cxl_clear_event_record(mds, type, payload);
956 		if (rc) {
957 			dev_err_ratelimited(dev,
958 				"Event log '%d': Failed to clear events : %d",
959 				type, rc);
960 			break;
961 		}
962 	} while (nr_rec);
963 
964 	mutex_unlock(&mds->event.log_lock);
965 }
966 
967 /**
968  * cxl_mem_get_event_records - Get Event Records from the device
969  * @mds: The driver data for the operation
970  * @status: Event Status register value identifying which events are available.
971  *
972  * Retrieve all event records available on the device, report them as trace
973  * events, and clear them.
974  *
975  * See CXL rev 3.0 @8.2.9.2.2 Get Event Records
976  * See CXL rev 3.0 @8.2.9.2.3 Clear Event Records
977  */
978 void cxl_mem_get_event_records(struct cxl_memdev_state *mds, u32 status)
979 {
980 	dev_dbg(mds->cxlds.dev, "Reading event logs: %x\n", status);
981 
982 	if (status & CXLDEV_EVENT_STATUS_FATAL)
983 		cxl_mem_get_records_log(mds, CXL_EVENT_TYPE_FATAL);
984 	if (status & CXLDEV_EVENT_STATUS_FAIL)
985 		cxl_mem_get_records_log(mds, CXL_EVENT_TYPE_FAIL);
986 	if (status & CXLDEV_EVENT_STATUS_WARN)
987 		cxl_mem_get_records_log(mds, CXL_EVENT_TYPE_WARN);
988 	if (status & CXLDEV_EVENT_STATUS_INFO)
989 		cxl_mem_get_records_log(mds, CXL_EVENT_TYPE_INFO);
990 }
991 EXPORT_SYMBOL_NS_GPL(cxl_mem_get_event_records, CXL);
992 
993 /**
994  * cxl_mem_get_partition_info - Get partition info
995  * @mds: The driver data for the operation
996  *
997  * Retrieve the current partition info for the device specified.  The active
998  * values are the current capacity in bytes.  If not 0, the 'next' values are
999  * the pending values, in bytes, which take affect on next cold reset.
1000  *
1001  * Return: 0 if no error: or the result of the mailbox command.
1002  *
1003  * See CXL @8.2.9.5.2.1 Get Partition Info
1004  */
1005 static int cxl_mem_get_partition_info(struct cxl_memdev_state *mds)
1006 {
1007 	struct cxl_mbox_get_partition_info pi;
1008 	struct cxl_mbox_cmd mbox_cmd;
1009 	int rc;
1010 
1011 	mbox_cmd = (struct cxl_mbox_cmd) {
1012 		.opcode = CXL_MBOX_OP_GET_PARTITION_INFO,
1013 		.size_out = sizeof(pi),
1014 		.payload_out = &pi,
1015 	};
1016 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
1017 	if (rc)
1018 		return rc;
1019 
1020 	mds->active_volatile_bytes =
1021 		le64_to_cpu(pi.active_volatile_cap) * CXL_CAPACITY_MULTIPLIER;
1022 	mds->active_persistent_bytes =
1023 		le64_to_cpu(pi.active_persistent_cap) * CXL_CAPACITY_MULTIPLIER;
1024 	mds->next_volatile_bytes =
1025 		le64_to_cpu(pi.next_volatile_cap) * CXL_CAPACITY_MULTIPLIER;
1026 	mds->next_persistent_bytes =
1027 		le64_to_cpu(pi.next_volatile_cap) * CXL_CAPACITY_MULTIPLIER;
1028 
1029 	return 0;
1030 }
1031 
1032 /**
1033  * cxl_dev_state_identify() - Send the IDENTIFY command to the device.
1034  * @mds: The driver data for the operation
1035  *
1036  * Return: 0 if identify was executed successfully or media not ready.
1037  *
1038  * This will dispatch the identify command to the device and on success populate
1039  * structures to be exported to sysfs.
1040  */
1041 int cxl_dev_state_identify(struct cxl_memdev_state *mds)
1042 {
1043 	/* See CXL 2.0 Table 175 Identify Memory Device Output Payload */
1044 	struct cxl_mbox_identify id;
1045 	struct cxl_mbox_cmd mbox_cmd;
1046 	u32 val;
1047 	int rc;
1048 
1049 	if (!mds->cxlds.media_ready)
1050 		return 0;
1051 
1052 	mbox_cmd = (struct cxl_mbox_cmd) {
1053 		.opcode = CXL_MBOX_OP_IDENTIFY,
1054 		.size_out = sizeof(id),
1055 		.payload_out = &id,
1056 	};
1057 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
1058 	if (rc < 0)
1059 		return rc;
1060 
1061 	mds->total_bytes =
1062 		le64_to_cpu(id.total_capacity) * CXL_CAPACITY_MULTIPLIER;
1063 	mds->volatile_only_bytes =
1064 		le64_to_cpu(id.volatile_capacity) * CXL_CAPACITY_MULTIPLIER;
1065 	mds->persistent_only_bytes =
1066 		le64_to_cpu(id.persistent_capacity) * CXL_CAPACITY_MULTIPLIER;
1067 	mds->partition_align_bytes =
1068 		le64_to_cpu(id.partition_align) * CXL_CAPACITY_MULTIPLIER;
1069 
1070 	mds->lsa_size = le32_to_cpu(id.lsa_size);
1071 	memcpy(mds->firmware_version, id.fw_revision,
1072 	       sizeof(id.fw_revision));
1073 
1074 	if (test_bit(CXL_POISON_ENABLED_LIST, mds->poison.enabled_cmds)) {
1075 		val = get_unaligned_le24(id.poison_list_max_mer);
1076 		mds->poison.max_errors = min_t(u32, val, CXL_POISON_LIST_MAX);
1077 	}
1078 
1079 	return 0;
1080 }
1081 EXPORT_SYMBOL_NS_GPL(cxl_dev_state_identify, CXL);
1082 
1083 static int add_dpa_res(struct device *dev, struct resource *parent,
1084 		       struct resource *res, resource_size_t start,
1085 		       resource_size_t size, const char *type)
1086 {
1087 	int rc;
1088 
1089 	res->name = type;
1090 	res->start = start;
1091 	res->end = start + size - 1;
1092 	res->flags = IORESOURCE_MEM;
1093 	if (resource_size(res) == 0) {
1094 		dev_dbg(dev, "DPA(%s): no capacity\n", res->name);
1095 		return 0;
1096 	}
1097 	rc = request_resource(parent, res);
1098 	if (rc) {
1099 		dev_err(dev, "DPA(%s): failed to track %pr (%d)\n", res->name,
1100 			res, rc);
1101 		return rc;
1102 	}
1103 
1104 	dev_dbg(dev, "DPA(%s): %pr\n", res->name, res);
1105 
1106 	return 0;
1107 }
1108 
1109 int cxl_mem_create_range_info(struct cxl_memdev_state *mds)
1110 {
1111 	struct cxl_dev_state *cxlds = &mds->cxlds;
1112 	struct device *dev = cxlds->dev;
1113 	int rc;
1114 
1115 	if (!cxlds->media_ready) {
1116 		cxlds->dpa_res = DEFINE_RES_MEM(0, 0);
1117 		cxlds->ram_res = DEFINE_RES_MEM(0, 0);
1118 		cxlds->pmem_res = DEFINE_RES_MEM(0, 0);
1119 		return 0;
1120 	}
1121 
1122 	cxlds->dpa_res =
1123 		(struct resource)DEFINE_RES_MEM(0, mds->total_bytes);
1124 
1125 	if (mds->partition_align_bytes == 0) {
1126 		rc = add_dpa_res(dev, &cxlds->dpa_res, &cxlds->ram_res, 0,
1127 				 mds->volatile_only_bytes, "ram");
1128 		if (rc)
1129 			return rc;
1130 		return add_dpa_res(dev, &cxlds->dpa_res, &cxlds->pmem_res,
1131 				   mds->volatile_only_bytes,
1132 				   mds->persistent_only_bytes, "pmem");
1133 	}
1134 
1135 	rc = cxl_mem_get_partition_info(mds);
1136 	if (rc) {
1137 		dev_err(dev, "Failed to query partition information\n");
1138 		return rc;
1139 	}
1140 
1141 	rc = add_dpa_res(dev, &cxlds->dpa_res, &cxlds->ram_res, 0,
1142 			 mds->active_volatile_bytes, "ram");
1143 	if (rc)
1144 		return rc;
1145 	return add_dpa_res(dev, &cxlds->dpa_res, &cxlds->pmem_res,
1146 			   mds->active_volatile_bytes,
1147 			   mds->active_persistent_bytes, "pmem");
1148 }
1149 EXPORT_SYMBOL_NS_GPL(cxl_mem_create_range_info, CXL);
1150 
1151 int cxl_set_timestamp(struct cxl_memdev_state *mds)
1152 {
1153 	struct cxl_mbox_cmd mbox_cmd;
1154 	struct cxl_mbox_set_timestamp_in pi;
1155 	int rc;
1156 
1157 	pi.timestamp = cpu_to_le64(ktime_get_real_ns());
1158 	mbox_cmd = (struct cxl_mbox_cmd) {
1159 		.opcode = CXL_MBOX_OP_SET_TIMESTAMP,
1160 		.size_in = sizeof(pi),
1161 		.payload_in = &pi,
1162 	};
1163 
1164 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
1165 	/*
1166 	 * Command is optional. Devices may have another way of providing
1167 	 * a timestamp, or may return all 0s in timestamp fields.
1168 	 * Don't report an error if this command isn't supported
1169 	 */
1170 	if (rc && (mbox_cmd.return_code != CXL_MBOX_CMD_RC_UNSUPPORTED))
1171 		return rc;
1172 
1173 	return 0;
1174 }
1175 EXPORT_SYMBOL_NS_GPL(cxl_set_timestamp, CXL);
1176 
1177 int cxl_mem_get_poison(struct cxl_memdev *cxlmd, u64 offset, u64 len,
1178 		       struct cxl_region *cxlr)
1179 {
1180 	struct cxl_memdev_state *mds = to_cxl_memdev_state(cxlmd->cxlds);
1181 	struct cxl_mbox_poison_out *po;
1182 	struct cxl_mbox_poison_in pi;
1183 	struct cxl_mbox_cmd mbox_cmd;
1184 	int nr_records = 0;
1185 	int rc;
1186 
1187 	rc = mutex_lock_interruptible(&mds->poison.lock);
1188 	if (rc)
1189 		return rc;
1190 
1191 	po = mds->poison.list_out;
1192 	pi.offset = cpu_to_le64(offset);
1193 	pi.length = cpu_to_le64(len / CXL_POISON_LEN_MULT);
1194 
1195 	mbox_cmd = (struct cxl_mbox_cmd) {
1196 		.opcode = CXL_MBOX_OP_GET_POISON,
1197 		.size_in = sizeof(pi),
1198 		.payload_in = &pi,
1199 		.size_out = mds->payload_size,
1200 		.payload_out = po,
1201 		.min_out = struct_size(po, record, 0),
1202 	};
1203 
1204 	do {
1205 		rc = cxl_internal_send_cmd(mds, &mbox_cmd);
1206 		if (rc)
1207 			break;
1208 
1209 		for (int i = 0; i < le16_to_cpu(po->count); i++)
1210 			trace_cxl_poison(cxlmd, cxlr, &po->record[i],
1211 					 po->flags, po->overflow_ts,
1212 					 CXL_POISON_TRACE_LIST);
1213 
1214 		/* Protect against an uncleared _FLAG_MORE */
1215 		nr_records = nr_records + le16_to_cpu(po->count);
1216 		if (nr_records >= mds->poison.max_errors) {
1217 			dev_dbg(&cxlmd->dev, "Max Error Records reached: %d\n",
1218 				nr_records);
1219 			break;
1220 		}
1221 	} while (po->flags & CXL_POISON_FLAG_MORE);
1222 
1223 	mutex_unlock(&mds->poison.lock);
1224 	return rc;
1225 }
1226 EXPORT_SYMBOL_NS_GPL(cxl_mem_get_poison, CXL);
1227 
1228 static void free_poison_buf(void *buf)
1229 {
1230 	kvfree(buf);
1231 }
1232 
1233 /* Get Poison List output buffer is protected by mds->poison.lock */
1234 static int cxl_poison_alloc_buf(struct cxl_memdev_state *mds)
1235 {
1236 	mds->poison.list_out = kvmalloc(mds->payload_size, GFP_KERNEL);
1237 	if (!mds->poison.list_out)
1238 		return -ENOMEM;
1239 
1240 	return devm_add_action_or_reset(mds->cxlds.dev, free_poison_buf,
1241 					mds->poison.list_out);
1242 }
1243 
1244 int cxl_poison_state_init(struct cxl_memdev_state *mds)
1245 {
1246 	int rc;
1247 
1248 	if (!test_bit(CXL_POISON_ENABLED_LIST, mds->poison.enabled_cmds))
1249 		return 0;
1250 
1251 	rc = cxl_poison_alloc_buf(mds);
1252 	if (rc) {
1253 		clear_bit(CXL_POISON_ENABLED_LIST, mds->poison.enabled_cmds);
1254 		return rc;
1255 	}
1256 
1257 	mutex_init(&mds->poison.lock);
1258 	return 0;
1259 }
1260 EXPORT_SYMBOL_NS_GPL(cxl_poison_state_init, CXL);
1261 
1262 struct cxl_memdev_state *cxl_memdev_state_create(struct device *dev)
1263 {
1264 	struct cxl_memdev_state *mds;
1265 
1266 	mds = devm_kzalloc(dev, sizeof(*mds), GFP_KERNEL);
1267 	if (!mds) {
1268 		dev_err(dev, "No memory available\n");
1269 		return ERR_PTR(-ENOMEM);
1270 	}
1271 
1272 	mutex_init(&mds->mbox_mutex);
1273 	mutex_init(&mds->event.log_lock);
1274 	mds->cxlds.dev = dev;
1275 
1276 	return mds;
1277 }
1278 EXPORT_SYMBOL_NS_GPL(cxl_memdev_state_create, CXL);
1279 
1280 void __init cxl_mbox_init(void)
1281 {
1282 	struct dentry *mbox_debugfs;
1283 
1284 	mbox_debugfs = cxl_debugfs_create_dir("mbox");
1285 	debugfs_create_bool("raw_allow_all", 0600, mbox_debugfs,
1286 			    &cxl_raw_allow_all);
1287 }
1288