xref: /linux/drivers/cxl/pci.c (revision df2798bc778acadcd87d7ff98a4db47197defc5f)
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/pci-doe.h>
12 #include <linux/aer.h>
13 #include <linux/io.h>
14 #include "cxlmem.h"
15 #include "cxlpci.h"
16 #include "cxl.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 /**
89  * __cxl_pci_mbox_send_cmd() - Execute a mailbox command
90  * @cxlds: The device state to communicate with.
91  * @mbox_cmd: Command to send to the memory device.
92  *
93  * Context: Any context. Expects mbox_mutex to be held.
94  * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
95  *         Caller should check the return code in @mbox_cmd to make sure it
96  *         succeeded.
97  *
98  * This is a generic form of the CXL mailbox send command thus only using the
99  * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
100  * devices, and perhaps other types of CXL devices may have further information
101  * available upon error conditions. Driver facilities wishing to send mailbox
102  * commands should use the wrapper command.
103  *
104  * The CXL spec allows for up to two mailboxes. The intention is for the primary
105  * mailbox to be OS controlled and the secondary mailbox to be used by system
106  * firmware. This allows the OS and firmware to communicate with the device and
107  * not need to coordinate with each other. The driver only uses the primary
108  * mailbox.
109  */
110 static int __cxl_pci_mbox_send_cmd(struct cxl_dev_state *cxlds,
111 				   struct cxl_mbox_cmd *mbox_cmd)
112 {
113 	void __iomem *payload = cxlds->regs.mbox + CXLDEV_MBOX_PAYLOAD_OFFSET;
114 	struct device *dev = cxlds->dev;
115 	u64 cmd_reg, status_reg;
116 	size_t out_len;
117 	int rc;
118 
119 	lockdep_assert_held(&cxlds->mbox_mutex);
120 
121 	/*
122 	 * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
123 	 *   1. Caller reads MB Control Register to verify doorbell is clear
124 	 *   2. Caller writes Command Register
125 	 *   3. Caller writes Command Payload Registers if input payload is non-empty
126 	 *   4. Caller writes MB Control Register to set doorbell
127 	 *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
128 	 *   6. Caller reads MB Status Register to fetch Return code
129 	 *   7. If command successful, Caller reads Command Register to get Payload Length
130 	 *   8. If output payload is non-empty, host reads Command Payload Registers
131 	 *
132 	 * Hardware is free to do whatever it wants before the doorbell is rung,
133 	 * and isn't allowed to change anything after it clears the doorbell. As
134 	 * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
135 	 * also happen in any order (though some orders might not make sense).
136 	 */
137 
138 	/* #1 */
139 	if (cxl_doorbell_busy(cxlds)) {
140 		u64 md_status =
141 			readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
142 
143 		cxl_cmd_err(cxlds->dev, mbox_cmd, md_status,
144 			    "mailbox queue busy");
145 		return -EBUSY;
146 	}
147 
148 	cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
149 			     mbox_cmd->opcode);
150 	if (mbox_cmd->size_in) {
151 		if (WARN_ON(!mbox_cmd->payload_in))
152 			return -EINVAL;
153 
154 		cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
155 				      mbox_cmd->size_in);
156 		memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
157 	}
158 
159 	/* #2, #3 */
160 	writeq(cmd_reg, cxlds->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
161 
162 	/* #4 */
163 	dev_dbg(dev, "Sending command: 0x%04x\n", mbox_cmd->opcode);
164 	writel(CXLDEV_MBOX_CTRL_DOORBELL,
165 	       cxlds->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET);
166 
167 	/* #5 */
168 	rc = cxl_pci_mbox_wait_for_doorbell(cxlds);
169 	if (rc == -ETIMEDOUT) {
170 		u64 md_status = readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
171 
172 		cxl_cmd_err(cxlds->dev, mbox_cmd, md_status, "mailbox timeout");
173 		return rc;
174 	}
175 
176 	/* #6 */
177 	status_reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_STATUS_OFFSET);
178 	mbox_cmd->return_code =
179 		FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
180 
181 	if (mbox_cmd->return_code != CXL_MBOX_CMD_RC_SUCCESS) {
182 		dev_dbg(dev, "Mailbox operation had an error: %s\n",
183 			cxl_mbox_cmd_rc2str(mbox_cmd));
184 		return 0; /* completed but caller must check return_code */
185 	}
186 
187 	/* #7 */
188 	cmd_reg = readq(cxlds->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
189 	out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
190 
191 	/* #8 */
192 	if (out_len && mbox_cmd->payload_out) {
193 		/*
194 		 * Sanitize the copy. If hardware misbehaves, out_len per the
195 		 * spec can actually be greater than the max allowed size (21
196 		 * bits available but spec defined 1M max). The caller also may
197 		 * have requested less data than the hardware supplied even
198 		 * within spec.
199 		 */
200 		size_t n = min3(mbox_cmd->size_out, cxlds->payload_size, out_len);
201 
202 		memcpy_fromio(mbox_cmd->payload_out, payload, n);
203 		mbox_cmd->size_out = n;
204 	} else {
205 		mbox_cmd->size_out = 0;
206 	}
207 
208 	return 0;
209 }
210 
211 static int cxl_pci_mbox_send(struct cxl_dev_state *cxlds, struct cxl_mbox_cmd *cmd)
212 {
213 	int rc;
214 
215 	mutex_lock_io(&cxlds->mbox_mutex);
216 	rc = __cxl_pci_mbox_send_cmd(cxlds, cmd);
217 	mutex_unlock(&cxlds->mbox_mutex);
218 
219 	return rc;
220 }
221 
222 static int cxl_pci_setup_mailbox(struct cxl_dev_state *cxlds)
223 {
224 	const int cap = readl(cxlds->regs.mbox + CXLDEV_MBOX_CAPS_OFFSET);
225 	unsigned long timeout;
226 	u64 md_status;
227 
228 	timeout = jiffies + mbox_ready_timeout * HZ;
229 	do {
230 		md_status = readq(cxlds->regs.memdev + CXLMDEV_STATUS_OFFSET);
231 		if (md_status & CXLMDEV_MBOX_IF_READY)
232 			break;
233 		if (msleep_interruptible(100))
234 			break;
235 	} while (!time_after(jiffies, timeout));
236 
237 	if (!(md_status & CXLMDEV_MBOX_IF_READY)) {
238 		cxl_err(cxlds->dev, md_status,
239 			"timeout awaiting mailbox ready");
240 		return -ETIMEDOUT;
241 	}
242 
243 	/*
244 	 * A command may be in flight from a previous driver instance,
245 	 * think kexec, do one doorbell wait so that
246 	 * __cxl_pci_mbox_send_cmd() can assume that it is the only
247 	 * source for future doorbell busy events.
248 	 */
249 	if (cxl_pci_mbox_wait_for_doorbell(cxlds) != 0) {
250 		cxl_err(cxlds->dev, md_status, "timeout awaiting mailbox idle");
251 		return -ETIMEDOUT;
252 	}
253 
254 	cxlds->mbox_send = cxl_pci_mbox_send;
255 	cxlds->payload_size =
256 		1 << FIELD_GET(CXLDEV_MBOX_CAP_PAYLOAD_SIZE_MASK, cap);
257 
258 	/*
259 	 * CXL 2.0 8.2.8.4.3 Mailbox Capabilities Register
260 	 *
261 	 * If the size is too small, mandatory commands will not work and so
262 	 * there's no point in going forward. If the size is too large, there's
263 	 * no harm is soft limiting it.
264 	 */
265 	cxlds->payload_size = min_t(size_t, cxlds->payload_size, SZ_1M);
266 	if (cxlds->payload_size < 256) {
267 		dev_err(cxlds->dev, "Mailbox is too small (%zub)",
268 			cxlds->payload_size);
269 		return -ENXIO;
270 	}
271 
272 	dev_dbg(cxlds->dev, "Mailbox payload sized %zu",
273 		cxlds->payload_size);
274 
275 	return 0;
276 }
277 
278 static int cxl_map_regblock(struct pci_dev *pdev, struct cxl_register_map *map)
279 {
280 	struct device *dev = &pdev->dev;
281 
282 	map->base = ioremap(map->resource, map->max_size);
283 	if (!map->base) {
284 		dev_err(dev, "failed to map registers\n");
285 		return -ENOMEM;
286 	}
287 
288 	dev_dbg(dev, "Mapped CXL Memory Device resource %pa\n", &map->resource);
289 	return 0;
290 }
291 
292 static void cxl_unmap_regblock(struct pci_dev *pdev,
293 			       struct cxl_register_map *map)
294 {
295 	iounmap(map->base);
296 	map->base = NULL;
297 }
298 
299 static int cxl_probe_regs(struct pci_dev *pdev, struct cxl_register_map *map)
300 {
301 	struct cxl_component_reg_map *comp_map;
302 	struct cxl_device_reg_map *dev_map;
303 	struct device *dev = &pdev->dev;
304 	void __iomem *base = map->base;
305 
306 	switch (map->reg_type) {
307 	case CXL_REGLOC_RBI_COMPONENT:
308 		comp_map = &map->component_map;
309 		cxl_probe_component_regs(dev, base, comp_map);
310 		if (!comp_map->hdm_decoder.valid) {
311 			dev_err(dev, "HDM decoder registers not found\n");
312 			return -ENXIO;
313 		}
314 
315 		if (!comp_map->ras.valid)
316 			dev_dbg(dev, "RAS registers not found\n");
317 
318 		dev_dbg(dev, "Set up component registers\n");
319 		break;
320 	case CXL_REGLOC_RBI_MEMDEV:
321 		dev_map = &map->device_map;
322 		cxl_probe_device_regs(dev, base, dev_map);
323 		if (!dev_map->status.valid || !dev_map->mbox.valid ||
324 		    !dev_map->memdev.valid) {
325 			dev_err(dev, "registers not found: %s%s%s\n",
326 				!dev_map->status.valid ? "status " : "",
327 				!dev_map->mbox.valid ? "mbox " : "",
328 				!dev_map->memdev.valid ? "memdev " : "");
329 			return -ENXIO;
330 		}
331 
332 		dev_dbg(dev, "Probing device registers...\n");
333 		break;
334 	default:
335 		break;
336 	}
337 
338 	return 0;
339 }
340 
341 static int cxl_setup_regs(struct pci_dev *pdev, enum cxl_regloc_type type,
342 			  struct cxl_register_map *map)
343 {
344 	int rc;
345 
346 	rc = cxl_find_regblock(pdev, type, map);
347 	if (rc)
348 		return rc;
349 
350 	rc = cxl_map_regblock(pdev, map);
351 	if (rc)
352 		return rc;
353 
354 	rc = cxl_probe_regs(pdev, map);
355 	cxl_unmap_regblock(pdev, map);
356 
357 	return rc;
358 }
359 
360 static void cxl_pci_destroy_doe(void *mbs)
361 {
362 	xa_destroy(mbs);
363 }
364 
365 static void devm_cxl_pci_create_doe(struct cxl_dev_state *cxlds)
366 {
367 	struct device *dev = cxlds->dev;
368 	struct pci_dev *pdev = to_pci_dev(dev);
369 	u16 off = 0;
370 
371 	xa_init(&cxlds->doe_mbs);
372 	if (devm_add_action(&pdev->dev, cxl_pci_destroy_doe, &cxlds->doe_mbs)) {
373 		dev_err(dev, "Failed to create XArray for DOE's\n");
374 		return;
375 	}
376 
377 	/*
378 	 * Mailbox creation is best effort.  Higher layers must determine if
379 	 * the lack of a mailbox for their protocol is a device failure or not.
380 	 */
381 	pci_doe_for_each_off(pdev, off) {
382 		struct pci_doe_mb *doe_mb;
383 
384 		doe_mb = pcim_doe_create_mb(pdev, off);
385 		if (IS_ERR(doe_mb)) {
386 			dev_err(dev, "Failed to create MB object for MB @ %x\n",
387 				off);
388 			continue;
389 		}
390 
391 		if (!pci_request_config_region_exclusive(pdev, off,
392 							 PCI_DOE_CAP_SIZEOF,
393 							 dev_name(dev)))
394 			pci_err(pdev, "Failed to exclude DOE registers\n");
395 
396 		if (xa_insert(&cxlds->doe_mbs, off, doe_mb, GFP_KERNEL)) {
397 			dev_err(dev, "xa_insert failed to insert MB @ %x\n",
398 				off);
399 			continue;
400 		}
401 
402 		dev_dbg(dev, "Created DOE mailbox @%x\n", off);
403 	}
404 }
405 
406 /*
407  * Assume that any RCIEP that emits the CXL memory expander class code
408  * is an RCD
409  */
410 static bool is_cxl_restricted(struct pci_dev *pdev)
411 {
412 	return pci_pcie_type(pdev) == PCI_EXP_TYPE_RC_END;
413 }
414 
415 static void disable_aer(void *pdev)
416 {
417 	pci_disable_pcie_error_reporting(pdev);
418 }
419 
420 static int cxl_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
421 {
422 	struct cxl_register_map map;
423 	struct cxl_memdev *cxlmd;
424 	struct cxl_dev_state *cxlds;
425 	int rc;
426 
427 	/*
428 	 * Double check the anonymous union trickery in struct cxl_regs
429 	 * FIXME switch to struct_group()
430 	 */
431 	BUILD_BUG_ON(offsetof(struct cxl_regs, memdev) !=
432 		     offsetof(struct cxl_regs, device_regs.memdev));
433 
434 	rc = pcim_enable_device(pdev);
435 	if (rc)
436 		return rc;
437 
438 	cxlds = cxl_dev_state_create(&pdev->dev);
439 	if (IS_ERR(cxlds))
440 		return PTR_ERR(cxlds);
441 	pci_set_drvdata(pdev, cxlds);
442 
443 	cxlds->rcd = is_cxl_restricted(pdev);
444 	cxlds->serial = pci_get_dsn(pdev);
445 	cxlds->cxl_dvsec = pci_find_dvsec_capability(
446 		pdev, PCI_DVSEC_VENDOR_ID_CXL, CXL_DVSEC_PCIE_DEVICE);
447 	if (!cxlds->cxl_dvsec)
448 		dev_warn(&pdev->dev,
449 			 "Device DVSEC not present, skip CXL.mem init\n");
450 
451 	rc = cxl_setup_regs(pdev, CXL_REGLOC_RBI_MEMDEV, &map);
452 	if (rc)
453 		return rc;
454 
455 	rc = cxl_map_device_regs(&pdev->dev, &cxlds->regs.device_regs, &map);
456 	if (rc)
457 		return rc;
458 
459 	/*
460 	 * If the component registers can't be found, the cxl_pci driver may
461 	 * still be useful for management functions so don't return an error.
462 	 */
463 	cxlds->component_reg_phys = CXL_RESOURCE_NONE;
464 	rc = cxl_setup_regs(pdev, CXL_REGLOC_RBI_COMPONENT, &map);
465 	if (rc)
466 		dev_warn(&pdev->dev, "No component registers (%d)\n", rc);
467 
468 	cxlds->component_reg_phys = map.resource;
469 
470 	devm_cxl_pci_create_doe(cxlds);
471 
472 	rc = cxl_map_component_regs(&pdev->dev, &cxlds->regs.component,
473 				    &map, BIT(CXL_CM_CAP_CAP_ID_RAS));
474 	if (rc)
475 		dev_dbg(&pdev->dev, "Failed to map RAS capability.\n");
476 
477 	rc = cxl_pci_setup_mailbox(cxlds);
478 	if (rc)
479 		return rc;
480 
481 	rc = cxl_enumerate_cmds(cxlds);
482 	if (rc)
483 		return rc;
484 
485 	rc = cxl_dev_state_identify(cxlds);
486 	if (rc)
487 		return rc;
488 
489 	rc = cxl_mem_create_range_info(cxlds);
490 	if (rc)
491 		return rc;
492 
493 	cxlmd = devm_cxl_add_memdev(cxlds);
494 	if (IS_ERR(cxlmd))
495 		return PTR_ERR(cxlmd);
496 
497 	if (cxlds->regs.ras) {
498 		pci_enable_pcie_error_reporting(pdev);
499 		rc = devm_add_action_or_reset(&pdev->dev, disable_aer, pdev);
500 		if (rc)
501 			return rc;
502 	}
503 	pci_save_state(pdev);
504 
505 	return rc;
506 }
507 
508 static const struct pci_device_id cxl_mem_pci_tbl[] = {
509 	/* PCI class code for CXL.mem Type-3 Devices */
510 	{ PCI_DEVICE_CLASS((PCI_CLASS_MEMORY_CXL << 8 | CXL_MEMORY_PROGIF), ~0)},
511 	{ /* terminate list */ },
512 };
513 MODULE_DEVICE_TABLE(pci, cxl_mem_pci_tbl);
514 
515 static pci_ers_result_t cxl_slot_reset(struct pci_dev *pdev)
516 {
517 	struct cxl_dev_state *cxlds = pci_get_drvdata(pdev);
518 	struct cxl_memdev *cxlmd = cxlds->cxlmd;
519 	struct device *dev = &cxlmd->dev;
520 
521 	dev_info(&pdev->dev, "%s: restart CXL.mem after slot reset\n",
522 		 dev_name(dev));
523 	pci_restore_state(pdev);
524 	if (device_attach(dev) <= 0)
525 		return PCI_ERS_RESULT_DISCONNECT;
526 	return PCI_ERS_RESULT_RECOVERED;
527 }
528 
529 static void cxl_error_resume(struct pci_dev *pdev)
530 {
531 	struct cxl_dev_state *cxlds = pci_get_drvdata(pdev);
532 	struct cxl_memdev *cxlmd = cxlds->cxlmd;
533 	struct device *dev = &cxlmd->dev;
534 
535 	dev_info(&pdev->dev, "%s: error resume %s\n", dev_name(dev),
536 		 dev->driver ? "successful" : "failed");
537 }
538 
539 static const struct pci_error_handlers cxl_error_handlers = {
540 	.error_detected	= cxl_error_detected,
541 	.slot_reset	= cxl_slot_reset,
542 	.resume		= cxl_error_resume,
543 	.cor_error_detected	= cxl_cor_error_detected,
544 };
545 
546 static struct pci_driver cxl_pci_driver = {
547 	.name			= KBUILD_MODNAME,
548 	.id_table		= cxl_mem_pci_tbl,
549 	.probe			= cxl_pci_probe,
550 	.err_handler		= &cxl_error_handlers,
551 	.driver	= {
552 		.probe_type	= PROBE_PREFER_ASYNCHRONOUS,
553 	},
554 };
555 
556 MODULE_LICENSE("GPL v2");
557 module_pci_driver(cxl_pci_driver);
558 MODULE_IMPORT_NS(CXL);
559