xref: /openbmc/linux/drivers/cxl/pci.c (revision 22c9bb1ed13ea3b8e8ee320573fa9f4573db1d53)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2020 Intel Corporation. All rights reserved. */
3 #include <linux/io-64-nonatomic-lo-hi.h>
4 #include <linux/moduleparam.h>
5 #include <linux/module.h>
6 #include <linux/delay.h>
7 #include <linux/sizes.h>
8 #include <linux/mutex.h>
9 #include <linux/list.h>
10 #include <linux/pci.h>
11 #include <linux/aer.h>
12 #include <linux/io.h>
13 #include "cxlmem.h"
14 #include "cxlpci.h"
15 #include "cxl.h"
16 #include "pmu.h"
17 
18 /**
19  * DOC: cxl pci
20  *
21  * This implements the PCI exclusive functionality for a CXL device as it is
22  * defined by the Compute Express Link specification. CXL devices may surface
23  * certain functionality even if it isn't CXL enabled. While this driver is
24  * focused around the PCI specific aspects of a CXL device, it binds to the
25  * specific CXL memory device class code, and therefore the implementation of
26  * cxl_pci is focused around CXL memory devices.
27  *
28  * The driver has several responsibilities, mainly:
29  *  - Create the memX device and register on the CXL bus.
30  *  - Enumerate device's register interface and map them.
31  *  - Registers nvdimm bridge device with cxl_core.
32  *  - Registers a CXL mailbox with cxl_core.
33  */
34 
35 #define cxl_doorbell_busy(cxlds)                                                \
36 	(readl((cxlds)->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET) &                  \
37 	 CXLDEV_MBOX_CTRL_DOORBELL)
38 
39 /* CXL 2.0 - 8.2.8.4 */
40 #define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
41 
42 /*
43  * CXL 2.0 ECN "Add Mailbox Ready Time" defines a capability field to
44  * dictate how long to wait for the mailbox to become ready. The new
45  * field allows the device to tell software the amount of time to wait
46  * before mailbox ready. This field per the spec theoretically allows
47  * for up to 255 seconds. 255 seconds is unreasonably long, its longer
48  * than the maximum SATA port link recovery wait. Default to 60 seconds
49  * until someone builds a CXL device that needs more time in practice.
50  */
51 static unsigned short mbox_ready_timeout = 60;
52 module_param(mbox_ready_timeout, ushort, 0644);
53 MODULE_PARM_DESC(mbox_ready_timeout, "seconds to wait for mailbox ready");
54 
55 static int cxl_pci_mbox_wait_for_doorbell(struct cxl_dev_state *cxlds)
56 {
57 	const unsigned long start = jiffies;
58 	unsigned long end = start;
59 
60 	while (cxl_doorbell_busy(cxlds)) {
61 		end = jiffies;
62 
63 		if (time_after(end, start + CXL_MAILBOX_TIMEOUT_MS)) {
64 			/* Check again in case preempted before timeout test */
65 			if (!cxl_doorbell_busy(cxlds))
66 				break;
67 			return -ETIMEDOUT;
68 		}
69 		cpu_relax();
70 	}
71 
72 	dev_dbg(cxlds->dev, "Doorbell wait took %dms",
73 		jiffies_to_msecs(end) - jiffies_to_msecs(start));
74 	return 0;
75 }
76 
77 #define cxl_err(dev, status, msg)                                        \
78 	dev_err_ratelimited(dev, msg ", device state %s%s\n",                  \
79 			    status & CXLMDEV_DEV_FATAL ? " fatal" : "",        \
80 			    status & CXLMDEV_FW_HALT ? " firmware-halt" : "")
81 
82 #define cxl_cmd_err(dev, cmd, status, msg)                               \
83 	dev_err_ratelimited(dev, msg " (opcode: %#x), device state %s%s\n",    \
84 			    (cmd)->opcode,                                     \
85 			    status & CXLMDEV_DEV_FATAL ? " fatal" : "",        \
86 			    status & CXLMDEV_FW_HALT ? " firmware-halt" : "")
87 
88 struct cxl_dev_id {
89 	struct cxl_dev_state *cxlds;
90 };
91 
92 static int cxl_request_irq(struct cxl_dev_state *cxlds, int irq,
93 			   irq_handler_t handler, irq_handler_t thread_fn)
94 {
95 	struct device *dev = cxlds->dev;
96 	struct cxl_dev_id *dev_id;
97 
98 	/* dev_id must be globally unique and must contain the cxlds */
99 	dev_id = devm_kzalloc(dev, sizeof(*dev_id), GFP_KERNEL);
100 	if (!dev_id)
101 		return -ENOMEM;
102 	dev_id->cxlds = cxlds;
103 
104 	return devm_request_threaded_irq(dev, irq, handler, thread_fn,
105 					 IRQF_SHARED | IRQF_ONESHOT,
106 					 NULL, dev_id);
107 }
108 
109 static bool cxl_mbox_background_complete(struct cxl_dev_state *cxlds)
110 {
111 	u64 reg;
112 
113 	reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_BG_CMD_STATUS_OFFSET);
114 	return FIELD_GET(CXLDEV_MBOX_BG_CMD_COMMAND_PCT_MASK, reg) == 100;
115 }
116 
117 static irqreturn_t cxl_pci_mbox_irq(int irq, void *id)
118 {
119 	u64 reg;
120 	u16 opcode;
121 	struct cxl_dev_id *dev_id = id;
122 	struct cxl_dev_state *cxlds = dev_id->cxlds;
123 	struct cxl_memdev_state *mds = to_cxl_memdev_state(cxlds);
124 
125 	if (!cxl_mbox_background_complete(cxlds))
126 		return IRQ_NONE;
127 
128 	reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_BG_CMD_STATUS_OFFSET);
129 	opcode = FIELD_GET(CXLDEV_MBOX_BG_CMD_COMMAND_OPCODE_MASK, reg);
130 	if (opcode == CXL_MBOX_OP_SANITIZE) {
131 		mutex_lock(&mds->mbox_mutex);
132 		if (mds->security.sanitize_node)
133 			mod_delayed_work(system_wq, &mds->security.poll_dwork, 0);
134 		mutex_unlock(&mds->mbox_mutex);
135 	} else {
136 		/* short-circuit the wait in __cxl_pci_mbox_send_cmd() */
137 		rcuwait_wake_up(&mds->mbox_wait);
138 	}
139 
140 	return IRQ_HANDLED;
141 }
142 
143 /*
144  * Sanitization operation polling mode.
145  */
146 static void cxl_mbox_sanitize_work(struct work_struct *work)
147 {
148 	struct cxl_memdev_state *mds =
149 		container_of(work, typeof(*mds), security.poll_dwork.work);
150 	struct cxl_dev_state *cxlds = &mds->cxlds;
151 
152 	mutex_lock(&mds->mbox_mutex);
153 	if (cxl_mbox_background_complete(cxlds)) {
154 		mds->security.poll_tmo_secs = 0;
155 		if (mds->security.sanitize_node)
156 			sysfs_notify_dirent(mds->security.sanitize_node);
157 
158 		dev_dbg(cxlds->dev, "Sanitization operation ended\n");
159 	} else {
160 		int timeout = mds->security.poll_tmo_secs + 10;
161 
162 		mds->security.poll_tmo_secs = min(15 * 60, timeout);
163 		schedule_delayed_work(&mds->security.poll_dwork, timeout * HZ);
164 	}
165 	mutex_unlock(&mds->mbox_mutex);
166 }
167 
168 /**
169  * __cxl_pci_mbox_send_cmd() - Execute a mailbox command
170  * @mds: The memory device driver data
171  * @mbox_cmd: Command to send to the memory device.
172  *
173  * Context: Any context. Expects mbox_mutex to be held.
174  * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
175  *         Caller should check the return code in @mbox_cmd to make sure it
176  *         succeeded.
177  *
178  * This is a generic form of the CXL mailbox send command thus only using the
179  * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
180  * devices, and perhaps other types of CXL devices may have further information
181  * available upon error conditions. Driver facilities wishing to send mailbox
182  * commands should use the wrapper command.
183  *
184  * The CXL spec allows for up to two mailboxes. The intention is for the primary
185  * mailbox to be OS controlled and the secondary mailbox to be used by system
186  * firmware. This allows the OS and firmware to communicate with the device and
187  * not need to coordinate with each other. The driver only uses the primary
188  * mailbox.
189  */
190 static int __cxl_pci_mbox_send_cmd(struct cxl_memdev_state *mds,
191 				   struct cxl_mbox_cmd *mbox_cmd)
192 {
193 	struct cxl_dev_state *cxlds = &mds->cxlds;
194 	void __iomem *payload = cxlds->regs.mbox + CXLDEV_MBOX_PAYLOAD_OFFSET;
195 	struct device *dev = cxlds->dev;
196 	u64 cmd_reg, status_reg;
197 	size_t out_len;
198 	int rc;
199 
200 	lockdep_assert_held(&mds->mbox_mutex);
201 
202 	/*
203 	 * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
204 	 *   1. Caller reads MB Control Register to verify doorbell is clear
205 	 *   2. Caller writes Command Register
206 	 *   3. Caller writes Command Payload Registers if input payload is non-empty
207 	 *   4. Caller writes MB Control Register to set doorbell
208 	 *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
209 	 *   6. Caller reads MB Status Register to fetch Return code
210 	 *   7. If command successful, Caller reads Command Register to get Payload Length
211 	 *   8. If output payload is non-empty, host reads Command Payload Registers
212 	 *
213 	 * Hardware is free to do whatever it wants before the doorbell is rung,
214 	 * and isn't allowed to change anything after it clears the doorbell. As
215 	 * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
216 	 * also happen in any order (though some orders might not make sense).
217 	 */
218 
219 	/* #1 */
220 	if (cxl_doorbell_busy(cxlds)) {
221 		u64 md_status =
222 			readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
223 
224 		cxl_cmd_err(cxlds->dev, mbox_cmd, md_status,
225 			    "mailbox queue busy");
226 		return -EBUSY;
227 	}
228 
229 	/*
230 	 * With sanitize polling, hardware might be done and the poller still
231 	 * not be in sync. Ensure no new command comes in until so. Keep the
232 	 * hardware semantics and only allow device health status.
233 	 */
234 	if (mds->security.poll_tmo_secs > 0) {
235 		if (mbox_cmd->opcode != CXL_MBOX_OP_GET_HEALTH_INFO)
236 			return -EBUSY;
237 	}
238 
239 	cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
240 			     mbox_cmd->opcode);
241 	if (mbox_cmd->size_in) {
242 		if (WARN_ON(!mbox_cmd->payload_in))
243 			return -EINVAL;
244 
245 		cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
246 				      mbox_cmd->size_in);
247 		memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
248 	}
249 
250 	/* #2, #3 */
251 	writeq(cmd_reg, cxlds->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
252 
253 	/* #4 */
254 	dev_dbg(dev, "Sending command: 0x%04x\n", mbox_cmd->opcode);
255 	writel(CXLDEV_MBOX_CTRL_DOORBELL,
256 	       cxlds->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET);
257 
258 	/* #5 */
259 	rc = cxl_pci_mbox_wait_for_doorbell(cxlds);
260 	if (rc == -ETIMEDOUT) {
261 		u64 md_status = readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
262 
263 		cxl_cmd_err(cxlds->dev, mbox_cmd, md_status, "mailbox timeout");
264 		return rc;
265 	}
266 
267 	/* #6 */
268 	status_reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_STATUS_OFFSET);
269 	mbox_cmd->return_code =
270 		FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
271 
272 	/*
273 	 * Handle the background command in a synchronous manner.
274 	 *
275 	 * All other mailbox commands will serialize/queue on the mbox_mutex,
276 	 * which we currently hold. Furthermore this also guarantees that
277 	 * cxl_mbox_background_complete() checks are safe amongst each other,
278 	 * in that no new bg operation can occur in between.
279 	 *
280 	 * Background operations are timesliced in accordance with the nature
281 	 * of the command. In the event of timeout, the mailbox state is
282 	 * indeterminate until the next successful command submission and the
283 	 * driver can get back in sync with the hardware state.
284 	 */
285 	if (mbox_cmd->return_code == CXL_MBOX_CMD_RC_BACKGROUND) {
286 		u64 bg_status_reg;
287 		int i, timeout;
288 
289 		/*
290 		 * Sanitization is a special case which monopolizes the device
291 		 * and cannot be timesliced. Handle asynchronously instead,
292 		 * and allow userspace to poll(2) for completion.
293 		 */
294 		if (mbox_cmd->opcode == CXL_MBOX_OP_SANITIZE) {
295 			/* give first timeout a second */
296 			timeout = 1;
297 			mds->security.poll_tmo_secs = timeout;
298 			schedule_delayed_work(&mds->security.poll_dwork,
299 					      timeout * HZ);
300 			dev_dbg(dev, "Sanitization operation started\n");
301 			goto success;
302 		}
303 
304 		dev_dbg(dev, "Mailbox background operation (0x%04x) started\n",
305 			mbox_cmd->opcode);
306 
307 		timeout = mbox_cmd->poll_interval_ms;
308 		for (i = 0; i < mbox_cmd->poll_count; i++) {
309 			if (rcuwait_wait_event_timeout(&mds->mbox_wait,
310 				       cxl_mbox_background_complete(cxlds),
311 				       TASK_UNINTERRUPTIBLE,
312 				       msecs_to_jiffies(timeout)) > 0)
313 				break;
314 		}
315 
316 		if (!cxl_mbox_background_complete(cxlds)) {
317 			dev_err(dev, "timeout waiting for background (%d ms)\n",
318 				timeout * mbox_cmd->poll_count);
319 			return -ETIMEDOUT;
320 		}
321 
322 		bg_status_reg = readq(cxlds->regs.mbox +
323 				      CXLDEV_MBOX_BG_CMD_STATUS_OFFSET);
324 		mbox_cmd->return_code =
325 			FIELD_GET(CXLDEV_MBOX_BG_CMD_COMMAND_RC_MASK,
326 				  bg_status_reg);
327 		dev_dbg(dev,
328 			"Mailbox background operation (0x%04x) completed\n",
329 			mbox_cmd->opcode);
330 	}
331 
332 	if (mbox_cmd->return_code != CXL_MBOX_CMD_RC_SUCCESS) {
333 		dev_dbg(dev, "Mailbox operation had an error: %s\n",
334 			cxl_mbox_cmd_rc2str(mbox_cmd));
335 		return 0; /* completed but caller must check return_code */
336 	}
337 
338 success:
339 	/* #7 */
340 	cmd_reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
341 	out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
342 
343 	/* #8 */
344 	if (out_len && mbox_cmd->payload_out) {
345 		/*
346 		 * Sanitize the copy. If hardware misbehaves, out_len per the
347 		 * spec can actually be greater than the max allowed size (21
348 		 * bits available but spec defined 1M max). The caller also may
349 		 * have requested less data than the hardware supplied even
350 		 * within spec.
351 		 */
352 		size_t n;
353 
354 		n = min3(mbox_cmd->size_out, mds->payload_size, out_len);
355 		memcpy_fromio(mbox_cmd->payload_out, payload, n);
356 		mbox_cmd->size_out = n;
357 	} else {
358 		mbox_cmd->size_out = 0;
359 	}
360 
361 	return 0;
362 }
363 
364 static int cxl_pci_mbox_send(struct cxl_memdev_state *mds,
365 			     struct cxl_mbox_cmd *cmd)
366 {
367 	int rc;
368 
369 	mutex_lock_io(&mds->mbox_mutex);
370 	rc = __cxl_pci_mbox_send_cmd(mds, cmd);
371 	mutex_unlock(&mds->mbox_mutex);
372 
373 	return rc;
374 }
375 
376 static int cxl_pci_setup_mailbox(struct cxl_memdev_state *mds)
377 {
378 	struct cxl_dev_state *cxlds = &mds->cxlds;
379 	const int cap = readl(cxlds->regs.mbox + CXLDEV_MBOX_CAPS_OFFSET);
380 	struct device *dev = cxlds->dev;
381 	unsigned long timeout;
382 	int irq, msgnum;
383 	u64 md_status;
384 	u32 ctrl;
385 
386 	timeout = jiffies + mbox_ready_timeout * HZ;
387 	do {
388 		md_status = readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
389 		if (md_status & CXLMDEV_MBOX_IF_READY)
390 			break;
391 		if (msleep_interruptible(100))
392 			break;
393 	} while (!time_after(jiffies, timeout));
394 
395 	if (!(md_status & CXLMDEV_MBOX_IF_READY)) {
396 		cxl_err(dev, md_status, "timeout awaiting mailbox ready");
397 		return -ETIMEDOUT;
398 	}
399 
400 	/*
401 	 * A command may be in flight from a previous driver instance,
402 	 * think kexec, do one doorbell wait so that
403 	 * __cxl_pci_mbox_send_cmd() can assume that it is the only
404 	 * source for future doorbell busy events.
405 	 */
406 	if (cxl_pci_mbox_wait_for_doorbell(cxlds) != 0) {
407 		cxl_err(dev, md_status, "timeout awaiting mailbox idle");
408 		return -ETIMEDOUT;
409 	}
410 
411 	mds->mbox_send = cxl_pci_mbox_send;
412 	mds->payload_size =
413 		1 << FIELD_GET(CXLDEV_MBOX_CAP_PAYLOAD_SIZE_MASK, cap);
414 
415 	/*
416 	 * CXL 2.0 8.2.8.4.3 Mailbox Capabilities Register
417 	 *
418 	 * If the size is too small, mandatory commands will not work and so
419 	 * there's no point in going forward. If the size is too large, there's
420 	 * no harm is soft limiting it.
421 	 */
422 	mds->payload_size = min_t(size_t, mds->payload_size, SZ_1M);
423 	if (mds->payload_size < 256) {
424 		dev_err(dev, "Mailbox is too small (%zub)",
425 			mds->payload_size);
426 		return -ENXIO;
427 	}
428 
429 	dev_dbg(dev, "Mailbox payload sized %zu", mds->payload_size);
430 
431 	rcuwait_init(&mds->mbox_wait);
432 	INIT_DELAYED_WORK(&mds->security.poll_dwork, cxl_mbox_sanitize_work);
433 
434 	/* background command interrupts are optional */
435 	if (!(cap & CXLDEV_MBOX_CAP_BG_CMD_IRQ))
436 		return 0;
437 
438 	msgnum = FIELD_GET(CXLDEV_MBOX_CAP_IRQ_MSGNUM_MASK, cap);
439 	irq = pci_irq_vector(to_pci_dev(cxlds->dev), msgnum);
440 	if (irq < 0)
441 		return 0;
442 
443 	if (cxl_request_irq(cxlds, irq, NULL, cxl_pci_mbox_irq))
444 		return 0;
445 
446 	dev_dbg(cxlds->dev, "Mailbox interrupts enabled\n");
447 	/* enable background command mbox irq support */
448 	ctrl = readl(cxlds->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET);
449 	ctrl |= CXLDEV_MBOX_CTRL_BG_CMD_IRQ;
450 	writel(ctrl, cxlds->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET);
451 
452 	return 0;
453 }
454 
455 /*
456  * Assume that any RCIEP that emits the CXL memory expander class code
457  * is an RCD
458  */
459 static bool is_cxl_restricted(struct pci_dev *pdev)
460 {
461 	return pci_pcie_type(pdev) == PCI_EXP_TYPE_RC_END;
462 }
463 
464 static int cxl_rcrb_get_comp_regs(struct pci_dev *pdev,
465 				  struct cxl_register_map *map)
466 {
467 	struct cxl_port *port;
468 	struct cxl_dport *dport;
469 	resource_size_t component_reg_phys;
470 
471 	*map = (struct cxl_register_map) {
472 		.dev = &pdev->dev,
473 		.resource = CXL_RESOURCE_NONE,
474 	};
475 
476 	port = cxl_pci_find_port(pdev, &dport);
477 	if (!port)
478 		return -EPROBE_DEFER;
479 
480 	component_reg_phys = cxl_rcd_component_reg_phys(&pdev->dev, dport);
481 
482 	put_device(&port->dev);
483 
484 	if (component_reg_phys == CXL_RESOURCE_NONE)
485 		return -ENXIO;
486 
487 	map->resource = component_reg_phys;
488 	map->reg_type = CXL_REGLOC_RBI_COMPONENT;
489 	map->max_size = CXL_COMPONENT_REG_BLOCK_SIZE;
490 
491 	return 0;
492 }
493 
494 static int cxl_pci_setup_regs(struct pci_dev *pdev, enum cxl_regloc_type type,
495 			      struct cxl_register_map *map)
496 {
497 	int rc;
498 
499 	rc = cxl_find_regblock(pdev, type, map);
500 
501 	/*
502 	 * If the Register Locator DVSEC does not exist, check if it
503 	 * is an RCH and try to extract the Component Registers from
504 	 * an RCRB.
505 	 */
506 	if (rc && type == CXL_REGLOC_RBI_COMPONENT && is_cxl_restricted(pdev))
507 		rc = cxl_rcrb_get_comp_regs(pdev, map);
508 
509 	if (rc)
510 		return rc;
511 
512 	return cxl_setup_regs(map);
513 }
514 
515 static int cxl_pci_ras_unmask(struct pci_dev *pdev)
516 {
517 	struct cxl_dev_state *cxlds = pci_get_drvdata(pdev);
518 	void __iomem *addr;
519 	u32 orig_val, val, mask;
520 	u16 cap;
521 	int rc;
522 
523 	if (!cxlds->regs.ras) {
524 		dev_dbg(&pdev->dev, "No RAS registers.\n");
525 		return 0;
526 	}
527 
528 	/* BIOS has PCIe AER error control */
529 	if (!pcie_aer_is_native(pdev))
530 		return 0;
531 
532 	rc = pcie_capability_read_word(pdev, PCI_EXP_DEVCTL, &cap);
533 	if (rc)
534 		return rc;
535 
536 	if (cap & PCI_EXP_DEVCTL_URRE) {
537 		addr = cxlds->regs.ras + CXL_RAS_UNCORRECTABLE_MASK_OFFSET;
538 		orig_val = readl(addr);
539 
540 		mask = CXL_RAS_UNCORRECTABLE_MASK_MASK |
541 		       CXL_RAS_UNCORRECTABLE_MASK_F256B_MASK;
542 		val = orig_val & ~mask;
543 		writel(val, addr);
544 		dev_dbg(&pdev->dev,
545 			"Uncorrectable RAS Errors Mask: %#x -> %#x\n",
546 			orig_val, val);
547 	}
548 
549 	if (cap & PCI_EXP_DEVCTL_CERE) {
550 		addr = cxlds->regs.ras + CXL_RAS_CORRECTABLE_MASK_OFFSET;
551 		orig_val = readl(addr);
552 		val = orig_val & ~CXL_RAS_CORRECTABLE_MASK_MASK;
553 		writel(val, addr);
554 		dev_dbg(&pdev->dev, "Correctable RAS Errors Mask: %#x -> %#x\n",
555 			orig_val, val);
556 	}
557 
558 	return 0;
559 }
560 
561 static void free_event_buf(void *buf)
562 {
563 	kvfree(buf);
564 }
565 
566 /*
567  * There is a single buffer for reading event logs from the mailbox.  All logs
568  * share this buffer protected by the mds->event_log_lock.
569  */
570 static int cxl_mem_alloc_event_buf(struct cxl_memdev_state *mds)
571 {
572 	struct cxl_get_event_payload *buf;
573 
574 	buf = kvmalloc(mds->payload_size, GFP_KERNEL);
575 	if (!buf)
576 		return -ENOMEM;
577 	mds->event.buf = buf;
578 
579 	return devm_add_action_or_reset(mds->cxlds.dev, free_event_buf, buf);
580 }
581 
582 static int cxl_alloc_irq_vectors(struct pci_dev *pdev)
583 {
584 	int nvecs;
585 
586 	/*
587 	 * Per CXL 3.0 3.1.1 CXL.io Endpoint a function on a CXL device must
588 	 * not generate INTx messages if that function participates in
589 	 * CXL.cache or CXL.mem.
590 	 *
591 	 * Additionally pci_alloc_irq_vectors() handles calling
592 	 * pci_free_irq_vectors() automatically despite not being called
593 	 * pcim_*.  See pci_setup_msi_context().
594 	 */
595 	nvecs = pci_alloc_irq_vectors(pdev, 1, CXL_PCI_DEFAULT_MAX_VECTORS,
596 				      PCI_IRQ_MSIX | PCI_IRQ_MSI);
597 	if (nvecs < 1) {
598 		dev_dbg(&pdev->dev, "Failed to alloc irq vectors: %d\n", nvecs);
599 		return -ENXIO;
600 	}
601 	return 0;
602 }
603 
604 static irqreturn_t cxl_event_thread(int irq, void *id)
605 {
606 	struct cxl_dev_id *dev_id = id;
607 	struct cxl_dev_state *cxlds = dev_id->cxlds;
608 	struct cxl_memdev_state *mds = to_cxl_memdev_state(cxlds);
609 	u32 status;
610 
611 	do {
612 		/*
613 		 * CXL 3.0 8.2.8.3.1: The lower 32 bits are the status;
614 		 * ignore the reserved upper 32 bits
615 		 */
616 		status = readl(cxlds->regs.status + CXLDEV_DEV_EVENT_STATUS_OFFSET);
617 		/* Ignore logs unknown to the driver */
618 		status &= CXLDEV_EVENT_STATUS_ALL;
619 		if (!status)
620 			break;
621 		cxl_mem_get_event_records(mds, status);
622 		cond_resched();
623 	} while (status);
624 
625 	return IRQ_HANDLED;
626 }
627 
628 static int cxl_event_req_irq(struct cxl_dev_state *cxlds, u8 setting)
629 {
630 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
631 	int irq;
632 
633 	if (FIELD_GET(CXLDEV_EVENT_INT_MODE_MASK, setting) != CXL_INT_MSI_MSIX)
634 		return -ENXIO;
635 
636 	irq =  pci_irq_vector(pdev,
637 			      FIELD_GET(CXLDEV_EVENT_INT_MSGNUM_MASK, setting));
638 	if (irq < 0)
639 		return irq;
640 
641 	return cxl_request_irq(cxlds, irq, NULL, cxl_event_thread);
642 }
643 
644 static int cxl_event_get_int_policy(struct cxl_memdev_state *mds,
645 				    struct cxl_event_interrupt_policy *policy)
646 {
647 	struct cxl_mbox_cmd mbox_cmd = {
648 		.opcode = CXL_MBOX_OP_GET_EVT_INT_POLICY,
649 		.payload_out = policy,
650 		.size_out = sizeof(*policy),
651 	};
652 	int rc;
653 
654 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
655 	if (rc < 0)
656 		dev_err(mds->cxlds.dev,
657 			"Failed to get event interrupt policy : %d", rc);
658 
659 	return rc;
660 }
661 
662 static int cxl_event_config_msgnums(struct cxl_memdev_state *mds,
663 				    struct cxl_event_interrupt_policy *policy)
664 {
665 	struct cxl_mbox_cmd mbox_cmd;
666 	int rc;
667 
668 	*policy = (struct cxl_event_interrupt_policy) {
669 		.info_settings = CXL_INT_MSI_MSIX,
670 		.warn_settings = CXL_INT_MSI_MSIX,
671 		.failure_settings = CXL_INT_MSI_MSIX,
672 		.fatal_settings = CXL_INT_MSI_MSIX,
673 	};
674 
675 	mbox_cmd = (struct cxl_mbox_cmd) {
676 		.opcode = CXL_MBOX_OP_SET_EVT_INT_POLICY,
677 		.payload_in = policy,
678 		.size_in = sizeof(*policy),
679 	};
680 
681 	rc = cxl_internal_send_cmd(mds, &mbox_cmd);
682 	if (rc < 0) {
683 		dev_err(mds->cxlds.dev, "Failed to set event interrupt policy : %d",
684 			rc);
685 		return rc;
686 	}
687 
688 	/* Retrieve final interrupt settings */
689 	return cxl_event_get_int_policy(mds, policy);
690 }
691 
692 static int cxl_event_irqsetup(struct cxl_memdev_state *mds)
693 {
694 	struct cxl_dev_state *cxlds = &mds->cxlds;
695 	struct cxl_event_interrupt_policy policy;
696 	int rc;
697 
698 	rc = cxl_event_config_msgnums(mds, &policy);
699 	if (rc)
700 		return rc;
701 
702 	rc = cxl_event_req_irq(cxlds, policy.info_settings);
703 	if (rc) {
704 		dev_err(cxlds->dev, "Failed to get interrupt for event Info log\n");
705 		return rc;
706 	}
707 
708 	rc = cxl_event_req_irq(cxlds, policy.warn_settings);
709 	if (rc) {
710 		dev_err(cxlds->dev, "Failed to get interrupt for event Warn log\n");
711 		return rc;
712 	}
713 
714 	rc = cxl_event_req_irq(cxlds, policy.failure_settings);
715 	if (rc) {
716 		dev_err(cxlds->dev, "Failed to get interrupt for event Failure log\n");
717 		return rc;
718 	}
719 
720 	rc = cxl_event_req_irq(cxlds, policy.fatal_settings);
721 	if (rc) {
722 		dev_err(cxlds->dev, "Failed to get interrupt for event Fatal log\n");
723 		return rc;
724 	}
725 
726 	return 0;
727 }
728 
729 static bool cxl_event_int_is_fw(u8 setting)
730 {
731 	u8 mode = FIELD_GET(CXLDEV_EVENT_INT_MODE_MASK, setting);
732 
733 	return mode == CXL_INT_FW;
734 }
735 
736 static int cxl_event_config(struct pci_host_bridge *host_bridge,
737 			    struct cxl_memdev_state *mds)
738 {
739 	struct cxl_event_interrupt_policy policy;
740 	int rc;
741 
742 	/*
743 	 * When BIOS maintains CXL error reporting control, it will process
744 	 * event records.  Only one agent can do so.
745 	 */
746 	if (!host_bridge->native_cxl_error)
747 		return 0;
748 
749 	rc = cxl_mem_alloc_event_buf(mds);
750 	if (rc)
751 		return rc;
752 
753 	rc = cxl_event_get_int_policy(mds, &policy);
754 	if (rc)
755 		return rc;
756 
757 	if (cxl_event_int_is_fw(policy.info_settings) ||
758 	    cxl_event_int_is_fw(policy.warn_settings) ||
759 	    cxl_event_int_is_fw(policy.failure_settings) ||
760 	    cxl_event_int_is_fw(policy.fatal_settings)) {
761 		dev_err(mds->cxlds.dev,
762 			"FW still in control of Event Logs despite _OSC settings\n");
763 		return -EBUSY;
764 	}
765 
766 	rc = cxl_event_irqsetup(mds);
767 	if (rc)
768 		return rc;
769 
770 	cxl_mem_get_event_records(mds, CXLDEV_EVENT_STATUS_ALL);
771 
772 	return 0;
773 }
774 
775 static int cxl_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
776 {
777 	struct pci_host_bridge *host_bridge = pci_find_host_bridge(pdev->bus);
778 	struct cxl_memdev_state *mds;
779 	struct cxl_dev_state *cxlds;
780 	struct cxl_register_map map;
781 	struct cxl_memdev *cxlmd;
782 	int i, rc, pmu_count;
783 
784 	/*
785 	 * Double check the anonymous union trickery in struct cxl_regs
786 	 * FIXME switch to struct_group()
787 	 */
788 	BUILD_BUG_ON(offsetof(struct cxl_regs, memdev) !=
789 		     offsetof(struct cxl_regs, device_regs.memdev));
790 
791 	rc = pcim_enable_device(pdev);
792 	if (rc)
793 		return rc;
794 	pci_set_master(pdev);
795 
796 	mds = cxl_memdev_state_create(&pdev->dev);
797 	if (IS_ERR(mds))
798 		return PTR_ERR(mds);
799 	cxlds = &mds->cxlds;
800 	pci_set_drvdata(pdev, cxlds);
801 
802 	cxlds->rcd = is_cxl_restricted(pdev);
803 	cxlds->serial = pci_get_dsn(pdev);
804 	cxlds->cxl_dvsec = pci_find_dvsec_capability(
805 		pdev, PCI_DVSEC_VENDOR_ID_CXL, CXL_DVSEC_PCIE_DEVICE);
806 	if (!cxlds->cxl_dvsec)
807 		dev_warn(&pdev->dev,
808 			 "Device DVSEC not present, skip CXL.mem init\n");
809 
810 	rc = cxl_pci_setup_regs(pdev, CXL_REGLOC_RBI_MEMDEV, &map);
811 	if (rc)
812 		return rc;
813 
814 	rc = cxl_map_device_regs(&map, &cxlds->regs.device_regs);
815 	if (rc)
816 		return rc;
817 
818 	/*
819 	 * If the component registers can't be found, the cxl_pci driver may
820 	 * still be useful for management functions so don't return an error.
821 	 */
822 	cxlds->component_reg_phys = CXL_RESOURCE_NONE;
823 	rc = cxl_pci_setup_regs(pdev, CXL_REGLOC_RBI_COMPONENT, &map);
824 	if (rc)
825 		dev_warn(&pdev->dev, "No component registers (%d)\n", rc);
826 	else if (!map.component_map.ras.valid)
827 		dev_dbg(&pdev->dev, "RAS registers not found\n");
828 
829 	cxlds->component_reg_phys = map.resource;
830 
831 	rc = cxl_map_component_regs(&map, &cxlds->regs.component,
832 				    BIT(CXL_CM_CAP_CAP_ID_RAS));
833 	if (rc)
834 		dev_dbg(&pdev->dev, "Failed to map RAS capability.\n");
835 
836 	rc = cxl_await_media_ready(cxlds);
837 	if (rc == 0)
838 		cxlds->media_ready = true;
839 	else
840 		dev_warn(&pdev->dev, "Media not active (%d)\n", rc);
841 
842 	rc = cxl_alloc_irq_vectors(pdev);
843 	if (rc)
844 		return rc;
845 
846 	rc = cxl_pci_setup_mailbox(mds);
847 	if (rc)
848 		return rc;
849 
850 	rc = cxl_enumerate_cmds(mds);
851 	if (rc)
852 		return rc;
853 
854 	rc = cxl_set_timestamp(mds);
855 	if (rc)
856 		return rc;
857 
858 	rc = cxl_poison_state_init(mds);
859 	if (rc)
860 		return rc;
861 
862 	rc = cxl_dev_state_identify(mds);
863 	if (rc)
864 		return rc;
865 
866 	rc = cxl_mem_create_range_info(mds);
867 	if (rc)
868 		return rc;
869 
870 	cxlmd = devm_cxl_add_memdev(&pdev->dev, cxlds);
871 	if (IS_ERR(cxlmd))
872 		return PTR_ERR(cxlmd);
873 
874 	rc = devm_cxl_setup_fw_upload(&pdev->dev, mds);
875 	if (rc)
876 		return rc;
877 
878 	pmu_count = cxl_count_regblock(pdev, CXL_REGLOC_RBI_PMU);
879 	for (i = 0; i < pmu_count; i++) {
880 		struct cxl_pmu_regs pmu_regs;
881 
882 		rc = cxl_find_regblock_instance(pdev, CXL_REGLOC_RBI_PMU, &map, i);
883 		if (rc) {
884 			dev_dbg(&pdev->dev, "Could not find PMU regblock\n");
885 			break;
886 		}
887 
888 		rc = cxl_map_pmu_regs(pdev, &pmu_regs, &map);
889 		if (rc) {
890 			dev_dbg(&pdev->dev, "Could not map PMU regs\n");
891 			break;
892 		}
893 
894 		rc = devm_cxl_pmu_add(cxlds->dev, &pmu_regs, cxlmd->id, i, CXL_PMU_MEMDEV);
895 		if (rc) {
896 			dev_dbg(&pdev->dev, "Could not add PMU instance\n");
897 			break;
898 		}
899 	}
900 
901 	rc = cxl_event_config(host_bridge, mds);
902 	if (rc)
903 		return rc;
904 
905 	rc = cxl_pci_ras_unmask(pdev);
906 	if (rc)
907 		dev_dbg(&pdev->dev, "No RAS reporting unmasked\n");
908 
909 	pci_save_state(pdev);
910 
911 	return rc;
912 }
913 
914 static const struct pci_device_id cxl_mem_pci_tbl[] = {
915 	/* PCI class code for CXL.mem Type-3 Devices */
916 	{ PCI_DEVICE_CLASS((PCI_CLASS_MEMORY_CXL << 8 | CXL_MEMORY_PROGIF), ~0)},
917 	{ /* terminate list */ },
918 };
919 MODULE_DEVICE_TABLE(pci, cxl_mem_pci_tbl);
920 
921 static pci_ers_result_t cxl_slot_reset(struct pci_dev *pdev)
922 {
923 	struct cxl_dev_state *cxlds = pci_get_drvdata(pdev);
924 	struct cxl_memdev *cxlmd = cxlds->cxlmd;
925 	struct device *dev = &cxlmd->dev;
926 
927 	dev_info(&pdev->dev, "%s: restart CXL.mem after slot reset\n",
928 		 dev_name(dev));
929 	pci_restore_state(pdev);
930 	if (device_attach(dev) <= 0)
931 		return PCI_ERS_RESULT_DISCONNECT;
932 	return PCI_ERS_RESULT_RECOVERED;
933 }
934 
935 static void cxl_error_resume(struct pci_dev *pdev)
936 {
937 	struct cxl_dev_state *cxlds = pci_get_drvdata(pdev);
938 	struct cxl_memdev *cxlmd = cxlds->cxlmd;
939 	struct device *dev = &cxlmd->dev;
940 
941 	dev_info(&pdev->dev, "%s: error resume %s\n", dev_name(dev),
942 		 dev->driver ? "successful" : "failed");
943 }
944 
945 static const struct pci_error_handlers cxl_error_handlers = {
946 	.error_detected	= cxl_error_detected,
947 	.slot_reset	= cxl_slot_reset,
948 	.resume		= cxl_error_resume,
949 	.cor_error_detected	= cxl_cor_error_detected,
950 };
951 
952 static struct pci_driver cxl_pci_driver = {
953 	.name			= KBUILD_MODNAME,
954 	.id_table		= cxl_mem_pci_tbl,
955 	.probe			= cxl_pci_probe,
956 	.err_handler		= &cxl_error_handlers,
957 	.driver	= {
958 		.probe_type	= PROBE_PREFER_ASYNCHRONOUS,
959 	},
960 };
961 
962 MODULE_LICENSE("GPL v2");
963 module_pci_driver(cxl_pci_driver);
964 MODULE_IMPORT_NS(CXL);
965