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