Skip to contentSkip to conversation

PCI/CXL: Add CXL reset support for Type 2 devices

PATCH In review Srirangan Madhavan 6 participants 64 messages Nov 5 – Nov 20

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

v17 cover PCI/CXL: Add CXL reset support for Type 2 devices

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

    /sys/bus/pci/devices/.../reset_method
    /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

Changes from v16 [1]:
- Publish the PCI HDM cache under the PCI device lock instead of cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming) [6][7]
- Wait for the reset timeout the device advertises, up to 100 seconds, instead of clamping it to 20 seconds, so Control2 is not accessed while the device may still be resetting (Richard) [8]
- State that userspace is expected to offline CXL.mem users before reset, and what the HPA reservation does and does not cover (Richard) [9]
- Enable bus mastering after the IOMMU is restored on CXL bus reset (Richard) [10]
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard) [11]
- Initialize the zero-size HDM decoder end to base - 1 and document the zero-size case (Richard) [12]
- Set Lock On Commit after programming the decoder registers and before Commit when recommitting a locked decoder (Alison) [13]
- Record Normalized Addressing in the cached decoder when region discovery sets it, and note the short window before that update (Sashiko) [15]
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() (Sashiko)
[15]
- Add the missing context-analysis annotations on the region quiesce lock and unlock and on __cxl_reset_execute() (Sashiko) [15]
- Use an explicit pci_dev_put() in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko) [15]
- Check for VFs and multifunction devices before the CXL DVSEC lookups in the two reset methods, to avoid repeated capability walks while probing VFs (Joshua) [18]
- Fold the CXL bus reset cache flush patch into this series (Dave); the series is now 19 patches
- Added Richard's Reviewed-by tags to patches 6-10, 14 and 16
- Specified the reviewer behind each change in the changelogs, per Alison [14]

Earlier revision history is in the v16 [1] and v15 [2] cover letters.

Attribution for Dave Jiang's reference branch is still open. Since I am unsure about [16] I have not yet added the right tags. The patches link to his branch below the separator for now.

The v15 discussion on the scope check is still pending [17].

HDM caching requires CXL.cache, CXL.mem, CXL Reset and Reset Memory Clear capabilities. CXL bus reset state restoration uses that cache.

CXL Reset requires a registered CPU cache clean/invalidate provider and matching firmware, such as the separate SMCCC provider series [3]. Without that provider, cxl_reset can be advertised while execution returns -ENOTTY, unless the test-only CXL_REGION_INVALIDATION_TEST bypass is enabled.

The KUnit suite checks HDM range boundaries, zero-size and uncommitted state, lock and target-type decoding, and 12-way interleave.

Testing: v17 was tested on an ARM64 target with v5 of the SMCCC cache provider series [3] applied. Reset loops passed for both cxl_reset and cxl_bus after running bidirectional host-device traffic. The cxl_hdm_unpack_kunit suite passes.

[1] https://lore.kernel.org/linux-cxl/[email protected]/
[2] https://lore.kernel.org/linux-cxl/[email protected]/
[3] https://lore.kernel.org/linux-arm-kernel/[email protected]/
[4] https://computeexpresslink.org/wp-content/uploads/2026/02/CXL-Specification_rev4p0_ver1p0_2026February26_clean_evalcopy_v2.pdf
[5] https://lore.kernel.org/all/[email protected]/
[6] https://lore.kernel.org/linux-cxl/[email protected]/
[7] https://lore.kernel.org/linux-cxl/[email protected]/T/#m7f8d0e51d4cfe09fefcebd93d49dcb916be9198a
[8] https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/
[9] https://lore.kernel.org/linux-cxl/auQRSOGWEDzB_qjF@MWDK4CY14F/
[10] https://lore.kernel.org/linux-cxl/auRhJa-nzR0CnKf3@MWDK4CY14F/
[11] https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/
[12] https://lore.kernel.org/linux-cxl/auQ27s1rSCcbdRJ3@MWDK4CY14F/
[13] https://lore.kernel.org/linux-cxl/[email protected]/
[14] https://lore.kernel.org/linux-cxl/[email protected]/
[15] https://sashiko.dev/#/patchset/[email protected]
[16] https://lore.kernel.org/linux-cxl/[email protected]/T/#m2f61467417f422316cb15b976773944dcdcb48c7
[17] https://lore.kernel.org/linux-cxl/[email protected]/T/#m4f62ed0f038f2d136158c74c1c6c338129266131
[18] https://lore.kernel.org/linux-cxl/[email protected]/

Srirangan Madhavan (19):
cxl: Clarify decoder interleave limit
cxl: Share CXL port upstream PCI device lookup
cxl: Move decoder declarations to shared header
cxl: Embed decoder configuration in a standalone structure
cxl: Introduce endpoint HDM decoder settings
cxl: Move HDM decoder helpers to built-in code
cxl: Share HDM decoder register unpacking
cxl: Move cxl_rwsem into built-in code
cxl: Refresh cached PCI HDM decoder settings
cxl: Build register block helpers into the kernel PCI/CXL: Cache endpoint HDM state during PCI enumeration PCI/CXL: Add CXL Device Reset sequencing
cxl: Validate and synchronize HDM ranges around reset PCI/CXL: Reject reset with unsafe function scope PCI/CXL: Restore CXL state after PCI reset PCI/CXL: Expose CXL Reset as a PCI reset method PCI/CXL: Restore CXL state after CXL bus reset PCI/CXL: Flush host and device caches for CXL bus reset
cxl: Add KUnit checks for HDM decoder unpacking

 MAINTAINERS                          |   1 +
 drivers/cxl/.kunitconfig             |   4 +
 drivers/cxl/Kconfig                  |  18 +-
 drivers/cxl/Makefile                 |   1 +
 drivers/cxl/acpi.c                   |  26 +-
 drivers/cxl/core/Makefile            |   2 +-
 drivers/cxl/core/atl.c               |   4 +-
 drivers/cxl/core/core.h              |  15 +
 drivers/cxl/core/hdm.c               | 273 +++-----
 drivers/cxl/core/hdm_regs.c          | 437 +++++++++++++
 drivers/cxl/core/hdm_state.c         | 402 ++++++++++++
 drivers/cxl/core/pci.c               |  85 ++-
 drivers/cxl/core/port.c              |  68 +-
 drivers/cxl/core/region.c            | 116 ++--
 drivers/cxl/core/regs.c              |   9 +
 drivers/cxl/cxl.h                    |  46 +-
 drivers/cxl/pci.c                    |   2 +-
 drivers/cxl/port.c                   |   4 +-
 drivers/cxl/tests/Makefile           |   5 +
 drivers/cxl/tests/hdm_unpack_kunit.c |  91 +++
 drivers/pci/Makefile                 |   1 +
 drivers/pci/bus.c                    |   1 +
 drivers/pci/cxl.c                    | 907 +++++++++++++++++++++++++++
 drivers/pci/pci.c                    |  27 +-
 drivers/pci/pci.h                    |  44 ++
 drivers/pci/probe.c                  |   1 +
 include/cxl/cxl.h                    |  59 +-
 include/cxl/hdm.h                    | 109 ++++
 include/cxl/pci.h                    |  13 +
 include/linux/pci.h                  |   8 +-
 include/uapi/linux/pci_regs.h        |  14 +
 tools/testing/cxl/Kbuild             |   1 -
 tools/testing/cxl/test/cxl.c         | 158 +++--
 33 files changed, 2526 insertions(+), 426 deletions(-)
 create mode 100644 drivers/cxl/.kunitconfig
 create mode 100644 drivers/cxl/core/hdm_regs.c
 create mode 100644 drivers/cxl/core/hdm_state.c
 create mode 100644 drivers/cxl/tests/Makefile
 create mode 100644 drivers/cxl/tests/hdm_unpack_kunit.c
 create mode 100644 drivers/pci/cxl.c
 create mode 100644 include/cxl/hdm.h

base-commit: fef22d37d47043b63e4007f2f5fe762fa21fae0c

Signature · 1 line
2.43.0
#1 lore raw

PATCH v17 1/19 cxl: Clarify decoder interleave limit

CXL 2.0 added 16-way memory interleaving, making the comment that the specification supports only 8-way interleaving stale. Explain that 16 is the largest interleave a decoder can express, without changing the limit.

---
 drivers/cxl/cxl.h | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/cxl/cxl.h +1 -4
index 3ef0810ab86b..50af716f69df 100644
@@ -269,10 +269,7 @@ enum cxl_decoder_type {
 	CXL_DECODER_HOSTONLYMEM = 3,
 };
 
-/*
- * Current specification goes up to 8, double that seems a reasonable
- * software max for the foreseeable future
- */
+/* 16 is the largest interleave a decoder can express (CXL 4.0 8.2.4.20.7). */
 #define CXL_DECODER_MAX_INTERLEAVE 16
 
 #define CXL_QOS_CLASS_INVALID -1
Signature · 1 line
2.43.0
#3 lore raw

PATCH v17 2/19 cxl: Share CXL port upstream PCI device lookup

In reply to Srirangan Madhavan

read_cdat_data() resolves a CXL port's upstream device to its backing PCI device. HDM cache updates need the same mapping.

Factor the lookup into cxl_port_get_uport_pci_dev() and return a referenced PCI device to make caller ownership explicit.

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

---
Changes in v17:
- Use an explicit pci_dev_put() on a single exit path in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=2

---
 drivers/cxl/core/core.h |  1 +
 drivers/cxl/core/pci.c  | 24 ++++++------------------
 drivers/cxl/core/port.c | 26 ++++++++++++++++++++++++++
 3 files changed, 33 insertions(+), 18 deletions(-)
drivers/cxl/core/core.h +1 -0
index 35eaf636adc9..983d7690c3a5 100644
@@ -157,6 +157,7 @@ long cxl_pci_get_latency(struct pci_dev *pdev);
 int cxl_pci_get_bandwidth(struct pci_dev *pdev, struct access_coordinate *c);
 int cxl_port_get_switch_dport_bandwidth(struct cxl_port *port,
 					struct access_coordinate *c);
+struct pci_dev *cxl_port_get_uport_pci_dev(struct cxl_port *port);
 
 static inline struct device *port_to_host(struct cxl_port *port)
 {
drivers/cxl/core/pci.c +6 -18
index 9d807c1a002c..905892cfedef 100644
@@ -564,26 +564,13 @@ static unsigned char cdat_checksum(void *buf, size_t size)
  */
 void read_cdat_data(struct cxl_port *port)
 {
-	struct device *uport = port->uport_dev;
+	struct pci_dev *pdev = cxl_port_get_uport_pci_dev(port);
 	struct device *dev = &port->dev;
 	struct pci_doe_mb *doe_mb;
-	struct pci_dev *pdev = NULL;
-	struct cxl_memdev *cxlmd;
 	struct cdat_doe_rsp *buf;
 	size_t table_length, length;
 	int rc;
 
-	if (is_cxl_memdev(uport)) {
-		struct device *host;
-
-		cxlmd = to_cxl_memdev(uport);
-		host = cxlmd->dev.parent;
-		if (dev_is_pci(host))
-			pdev = to_pci_dev(host);
-	} else if (dev_is_pci(uport)) {
-		pdev = to_pci_dev(uport);
-	}
-
 	if (!pdev)
 		return;
 
@@ -591,14 +578,14 @@ void read_cdat_data(struct cxl_port *port)
 				      CXL_DOE_PROTOCOL_TABLE_ACCESS);
 	if (!doe_mb) {
 		dev_dbg(dev, "No CDAT mailbox\n");
-		return;
+		goto out;
 	}
 
 	port->cdat_available = true;
 
 	if (cxl_cdat_get_length(dev, doe_mb, &length)) {
 		dev_dbg(dev, "No CDAT length\n");
-		return;
+		goto out;
 	}
 
 	/*
@@ -624,12 +611,13 @@ void read_cdat_data(struct cxl_port *port)
 
 	port->cdat.table = buf->data;
 	port->cdat.length = length;
-
-	return;
+	goto out;
 err:
 	/* Don't leave table data allocated on error */
 	devm_kfree(dev, buf);
 	dev_err(dev, "Failed to read/validate CDAT.\n");
+out:
+	pci_dev_put(pdev);
 }
 EXPORT_SYMBOL_NS_GPL(read_cdat_data, "CXL");
 
drivers/cxl/core/port.c +26 -0
index 625e4aa427db..5dc2815d82d8 100644
@@ -34,6 +34,32 @@
 static DEFINE_IDA(cxl_port_ida);
 static DEFINE_XARRAY(cxl_root_buses);
 
+/**
+ * cxl_port_get_uport_pci_dev - get the PCI device for a port's upstream device
+ * @port: CXL port to map to a PCI device
+ *
+ * Return: A referenced PCI device, or NULL if the upstream device is not PCI.
+ * The caller must release the returned reference with pci_dev_put().
+ */
+struct pci_dev *cxl_port_get_uport_pci_dev(struct cxl_port *port)
+{
+	struct device *uport = port->uport_dev;
+	struct device *host;
+
+	if (is_cxl_memdev(uport)) {
+		struct cxl_memdev *cxlmd = to_cxl_memdev(uport);
+
+		host = cxlmd->dev.parent;
+	} else {
+		host = uport;
+	}
+
+	if (!host || !dev_is_pci(host))
+		return NULL;
+
+	return pci_dev_get(to_pci_dev(host));
+}
+
 /*
  * The terminal device in PCI is NULL and @platform_bus
  * for platform devices (for cxl_test)
Signature · 1 line
2.43.0
#8 lore raw

PATCH v17 3/19 cxl: Move decoder declarations to shared header

In reply to Srirangan Madhavan

Move the common decoder declarations to include/cxl/cxl.h for use by shared decoder settings. Preserve their layout and documentation.

---
 drivers/cxl/cxl.h | 38 --------------------------------------
 include/cxl/cxl.h | 42 +++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 39 deletions(-)
drivers/cxl/cxl.h +0 -38
index 50af716f69df..44ff3334648c 100644
@@ -264,46 +264,8 @@ int cxl_dport_map_rcd_linkcap(struct pci_dev *pdev, struct cxl_dport *dport);
 #define CXL_DECODER_F_NORMALIZED_ADDRESSING BIT(6)
 #define CXL_DECODER_F_RESET_MASK (CXL_DECODER_F_ENABLE | CXL_DECODER_F_LOCK)
 
-enum cxl_decoder_type {
-	CXL_DECODER_DEVMEM = 2,
-	CXL_DECODER_HOSTONLYMEM = 3,
-};
-
-/* 16 is the largest interleave a decoder can express (CXL 4.0 8.2.4.20.7). */
-#define CXL_DECODER_MAX_INTERLEAVE 16
-
 #define CXL_QOS_CLASS_INVALID -1
 
-/**
- * struct cxl_decoder - Common CXL HDM Decoder Attributes
- * @dev: this decoder's device
- * @id: kernel device name id
- * @hpa_range: Host physical address range mapped by this decoder
- * @interleave_ways: number of cxl_dports in this decode
- * @interleave_granularity: data stride per dport
- * @target_type: accelerator vs expander (type2 vs type3) selector
- * @region: currently assigned region for this decoder
- * @flags: memory type capabilities and locking
- * @target_map: cached copy of hardware port-id list, available at init
- *              before all @dport objects have been instantiated. While
- *              dport id is 8bit, CFMWS interleave targets are 32bits.
- * @commit: device/decoder-type specific callback to commit settings to hw
- * @reset: device/decoder-type specific callback to reset hw settings
-*/
-struct cxl_decoder {
-	struct device dev;
-	int id;
-	struct range hpa_range;
-	int interleave_ways;
-	int interleave_granularity;
-	enum cxl_decoder_type target_type;
-	struct cxl_region *region;
-	unsigned long flags;
-	u32 target_map[CXL_DECODER_MAX_INTERLEAVE];
-	int (*commit)(struct cxl_decoder *cxld);
-	void (*reset)(struct cxl_decoder *cxld);
-};
-
 /*
  * Track whether this decoder is free for userspace provisioning, reserved for
  * region autodiscovery, whether it is started connecting (awaiting other
include/cxl/cxl.h +41 -1

56 lines not on this page · raw message

Signature · 1 line
2.43.0
#14 lore raw

PATCH v17 6/19 cxl: Move HDM decoder helpers to built-in code

In reply to Srirangan Madhavan

The PCI core will restore HDM decoders after a reset, possibly while no CXL driver is loaded, so it cannot call into cxl_core.

Move the HDM register programming helpers from hdm.c to hdm_regs.c and build that file into the kernel whenever CXL_BUS is enabled, including when CXL_BUS is modular. Export only the symbols that cxl_core uses.

Keep the DPA lock assertion in the normal decoder programming caller so the register helpers do not depend on cxl_rwsem. Leave cxl_rwsem in cxl_core until built-in cache management needs it.

---
Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=e0b476ea99567fb5aa416eac0cf61bca20724880

---
 drivers/cxl/core/Makefile   |   1 +
 drivers/cxl/core/hdm.c      | 102 +------------------------------
 drivers/cxl/core/hdm_regs.c | 118 ++++++++++++++++++++++++++++++++++++
 3 files changed, 121 insertions(+), 100 deletions(-)
 create mode 100644 drivers/cxl/core/hdm_regs.c
drivers/cxl/core/Makefile +1 -0
index ce7213818d3c..6703c1729396 100644
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CXL_BUS) += cxl_core.o
+obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o
 obj-$(CONFIG_CXL_SUSPEND) += suspend.o
 
 ccflags-y += -I$(srctree)/drivers/cxl
drivers/cxl/core/hdm.c +2 -100

120 lines not on this page · raw message

drivers/cxl/core/hdm_regs.c new file +118 -0

118 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw

PATCH v17 5/19 cxl: Introduce endpoint HDM decoder settings

In reply to Srirangan Madhavan

Keep common decoder configuration in cxl_decoder_config and represent endpoint DPA skip in cxl_endpoint_decoder_settings. Share range programming, but keep endpoint skip and switch target-list writes in their respective commit paths.

Separate commit initiation from completion waiting so reset restoration can reuse register programming without changing normal DPA-lock policy.

---
 drivers/cxl/core/core.h |  8 ++++
 drivers/cxl/core/hdm.c  | 95 ++++++++++++++++++++++++++++-------------
 include/cxl/hdm.h       | 19 +++++++++
 3 files changed, 92 insertions(+), 30 deletions(-)
 create mode 100644 include/cxl/hdm.h
drivers/cxl/core/core.h +8 -0
index 983d7690c3a5..fb14b222f3ca 100644
@@ -7,6 +7,8 @@
 #include <cxl/mailbox.h>
 #include <linux/rwsem.h>
 
+struct cxl_endpoint_decoder_settings;
+
 extern const struct device_type cxl_nvdimm_bridge_type;
 extern const struct device_type cxl_nvdimm_type;
 extern const struct device_type cxl_pmu_type;
@@ -139,6 +141,12 @@ struct cxl_rwsem {
 
 extern struct cxl_rwsem cxl_rwsem;
 
+void cxl_commit_start_endpoint(const struct cxl_endpoint_decoder_settings *settings,
+			       void __iomem *hdm);
+void cxl_commit_start_switch(const struct cxl_decoder_config *config,
+			     u64 targets, void __iomem *hdm);
+int cxld_await_commit(void __iomem *hdm, int id);
+
 int cxl_memdev_init(void);
 void cxl_memdev_exit(void);
 void cxl_mbox_init(void);
drivers/cxl/core/hdm.c +65 -30

152 lines not on this page · raw message

include/cxl/hdm.h new file +19 -0
new file mode 100644
index 000000000000..219b9bb67440
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#ifndef __CXL_HDM_H__
+#define __CXL_HDM_H__
+
+#include <linux/types.h>
+#include <cxl/cxl.h>
+
+/**
+ * struct cxl_endpoint_decoder_settings - endpoint HDM decoder programming
+ * @config: common decoder configuration
+ * @skip: length of DPA space skipped before this decoder's DPA mapping
+ */
+struct cxl_endpoint_decoder_settings {
+	struct cxl_decoder_config config;
+	u64 skip;
+};
+
+#endif /* __CXL_HDM_H__ */
Signature · 1 line
2.43.0
#10 lore raw

PATCH v17 4/19 cxl: Embed decoder configuration in a standalone structure

In reply to Srirangan Madhavan

Define cxl_decoder_config independently and embed it in cxl_decoder. Update decoder field accesses without changing behavior, so reset snapshots can reuse the configuration type without struct_group_tagged().

---
 drivers/cxl/acpi.c           |  26 +++---
 drivers/cxl/core/atl.c       |   4 +-
 drivers/cxl/core/hdm.c       | 114 ++++++++++++-------------
 drivers/cxl/core/pci.c       |   8 +-
 drivers/cxl/core/port.c      |  42 +++++-----
 drivers/cxl/core/region.c    | 102 +++++++++++-----------
 drivers/cxl/cxl.h            |   2 +-
 drivers/cxl/pci.c            |   2 +-
 drivers/cxl/port.c           |   4 +-
 include/cxl/cxl.h            |  29 +++++--
 tools/testing/cxl/test/cxl.c | 158 +++++++++++++++++------------------
 11 files changed, 249 insertions(+), 242 deletions(-)
drivers/cxl/acpi.c +13 -13
index 3b818adbd38b..692a4e067678 100644
@@ -109,16 +109,16 @@ static int cxl_parse_cxims(union acpi_subtable_headers *header, void *arg,
 		return rc;
 
 	/* Does this CXIMS entry apply to the given CXL Window? */
-	if (hbig != cxld->interleave_granularity)
+	if (hbig != cxld->config.interleave_granularity)
 		return 0;
 
 	/* IW 1,3 do not use xormaps and skip this parsing entirely */
-	if (is_power_of_2(cxld->interleave_ways))
+	if (is_power_of_2(cxld->config.interleave_ways))
 		/* 2, 4, 8, 16 way */
-		nr_maps = ilog2(cxld->interleave_ways);
+		nr_maps = ilog2(cxld->config.interleave_ways);
 	else
 		/* 6, 12 way */
-		nr_maps = ilog2(cxld->interleave_ways / 3);
+		nr_maps = ilog2(cxld->config.interleave_ways / 3);
 
 	if (cxims->nr_xormaps < nr_maps) {
 		dev_dbg(dev, "CXIMS nr_xormaps[%d] expected[%d]\n",
@@ -363,7 +363,7 @@ static int add_or_reset_cxl_resource(struct resource *parent, struct resource *r
 static void cxl_setup_extended_linear_cache(struct cxl_root_decoder *cxlrd)
 {
 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
-	struct range *hpa = &cxld->hpa_range;
+	struct range *hpa = &cxld->config.hpa_range;
 	resource_size_t size = range_len(hpa);
 	resource_size_t start = hpa->start;
 	resource_size_t cache_size;
@@ -436,13 +436,13 @@ static int __cxl_parse_cfmws(struct acpi_cedt_cfmws *cfmws,
 		return PTR_ERR(cxlrd);
 
 	cxld = &cxlrd->cxlsd.cxld;
-	cxld->flags = cfmws_to_decoder_flags(cfmws->restrictions);
-	cxld->target_type = CXL_DECODER_HOSTONLYMEM;
-	cxld->hpa_range = (struct range) {
+	cxld->config.flags = cfmws_to_decoder_flags(cfmws->restrictions);
+	cxld->config.target_type = CXL_DECODER_HOSTONLYMEM;
+	cxld->config.hpa_range = (struct range) {
 		.start = cfmws->base_hpa,
 		.end = cfmws->base_hpa + cfmws->window_size - 1,
 	};
-	cxld->interleave_ways = ways;
+	cxld->config.interleave_ways = ways;
 	for (i = 0; i < ways; i++)
 		cxld->target_map[i] = cfmws->interleave_targets[i];
 	/*
@@ -451,7 +451,7 @@ static int __cxl_parse_cfmws(struct acpi_cedt_cfmws *cfmws,
 	 */
 	if (ways == 1)
 		ig = CXL_DECODER_MIN_GRANULARITY;
-	cxld->interleave_granularity = ig;
+	cxld->config.interleave_granularity = ig;
 
 	if (cfmws->interleave_arithmetic == ACPI_CEDT_CFMWS_ARITHMETIC_XOR) {
 		if (ways != 1 && ways != 3) {
@@ -752,7 +752,7 @@ static int add_root_nvdimm_bridge(struct device *match, void *data)
 		return 0;
 
 	cxld = to_cxl_decoder(match);
-	if (!(cxld->flags & CXL_DECODER_F_PMEM))
+	if (!(cxld->config.flags & CXL_DECODER_F_PMEM))
 		return 0;
 
 	cxl_nvb = devm_cxl_add_nvdimm_bridge(host, root_port);
@@ -869,8 +869,8 @@ static int pair_cxl_resource(struct device *dev, void *data)
 		struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
 		struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
 		struct resource res = {
-			.start = cxld->hpa_range.start,
-			.end = cxld->hpa_range.end,
+			.start = cxld->config.hpa_range.start,
+			.end = cxld->config.hpa_range.end,
 			.flags = IORESOURCE_MEM,
 		};
 
drivers/cxl/core/atl.c +2 -2
index 310668786189..07ce7c50c47a 100644
@@ -172,8 +172,8 @@ static int cxl_prm_setup_root(struct cxl_root *cxl_root, void *data)
 	 *
 	 * Indicate that Normalized Addressing is enabled.
 	 */
-	cxld->flags |= CXL_DECODER_F_LOCK;
-	cxld->flags |= CXL_DECODER_F_NORMALIZED_ADDRESSING;
+	cxld->config.flags |= CXL_DECODER_F_LOCK;
+	cxld->config.flags |= CXL_DECODER_F_NORMALIZED_ADDRESSING;
 
 	ctx->hpa_range = hpa_range;
 	ctx->interleave_ways = ways;
drivers/cxl/core/hdm.c +57 -57

330 lines not on this page · raw message

drivers/cxl/core/pci.c +4 -4
index 905892cfedef..f72cd8f50e77 100644
@@ -231,10 +231,10 @@ static int dvsec_range_allowed(struct device *dev, const void *arg)
 
 	cxld = to_cxl_decoder(dev);
 
-	if (!(cxld->flags & CXL_DECODER_F_RAM))
+	if (!(cxld->config.flags & CXL_DECODER_F_RAM))
 		return 0;
 
-	return range_contains(&cxld->hpa_range, dev_range);
+	return range_contains(&cxld->config.hpa_range, dev_range);
 }
 
 static void disable_hdm(void *_cxlhdm)
@@ -668,12 +668,12 @@ static int __cxl_endpoint_decoder_reset_detected(struct device *dev, void *data)
 		return 0;
 
 	cxld = to_cxl_decoder(dev);
-	if ((cxld->flags & CXL_DECODER_F_ENABLE) == 0)
+	if ((cxld->config.flags & CXL_DECODER_F_ENABLE) == 0)
 		return 0;
 
 	cxlhdm = dev_get_drvdata(&port->dev);
 	hdm = cxlhdm->regs.hdm_decoder;
-	ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(cxld->id));
+	ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(cxld->config.id));
 
 	return !FIELD_GET(CXL_HDM_DECODER0_CTRL_COMMITTED, ctrl);
 }
drivers/cxl/core/port.c +21 -21

150 lines not on this page · raw message

drivers/cxl/core/region.c +51 -51

280 lines not on this page · raw message

drivers/cxl/cxl.h +1 -1
index 44ff3334648c..688350c7c5fb 100644
@@ -281,7 +281,7 @@ enum cxl_decoder_state {
  * struct cxl_endpoint_decoder - Endpoint  / SPA to DPA decoder
  * @cxld: base cxl_decoder_object
  * @dpa_res: actively claimed DPA span of this decoder
- * @skip: offset into @dpa_res where @cxld.hpa_range maps
+ * @skip: offset into @dpa_res where @cxld.config.hpa_range maps
  * @state: autodiscovery state
  * @part: partition index this decoder maps
  * @pos: interleave position in @cxld.region
drivers/cxl/pci.c +1 -1
index c7c91e8dc51d..9a0cbcd230b2 100644
@@ -966,7 +966,7 @@ static int cxl_endpoint_decoder_clear_reset_flags(struct device *dev, void *data
 		return 0;
 
 	cxled = to_cxl_endpoint_decoder(dev);
-	cxled->cxld.flags &= ~CXL_DECODER_F_RESET_MASK;
+	cxled->cxld.config.flags &= ~CXL_DECODER_F_RESET_MASK;
 
 	return 0;
 }
drivers/cxl/port.c +2 -2
index c12fd0b89883..b369d3e3876d 100644
@@ -40,7 +40,7 @@ static int discover_region(struct device *dev, void *unused)
 		return 0;
 
 	cxled = to_cxl_endpoint_decoder(dev);
-	if ((cxled->cxld.flags & CXL_DECODER_F_ENABLE) == 0)
+	if ((cxled->cxld.config.flags & CXL_DECODER_F_ENABLE) == 0)
 		return 0;
 
 	if (cxled->state != CXL_DECODER_STATE_AUTO)
@@ -56,7 +56,7 @@ static int discover_region(struct device *dev, void *unused)
 	rc = cxl_add_to_region(cxled);
 	if (rc)
 		dev_dbg(dev, "failed to add to region: %#llx-%#llx\n",
-			cxled->cxld.hpa_range.start, cxled->cxld.hpa_range.end);
+			cxled->cxld.config.hpa_range.start, cxled->cxld.config.hpa_range.end);
 
 	return 0;
 }
include/cxl/cxl.h +20 -9
index 613dab8150c7..6d6e564be27a 100644
@@ -36,15 +36,31 @@ enum cxl_decoder_type {
 #define CXL_DECODER_MAX_INTERLEAVE 16
 
 /**
- * struct cxl_decoder - Common CXL HDM Decoder Attributes
- * @dev: this decoder's device
+ * struct cxl_decoder_config - common CXL decoder configuration and state
  * @id: kernel device name id
  * @hpa_range: Host physical address range mapped by this decoder
  * @interleave_ways: number of cxl_dports in this decode
  * @interleave_granularity: data stride per dport
  * @target_type: accelerator vs expander (type2 vs type3) selector
- * @region: currently assigned region for this decoder
  * @flags: memory type capabilities and locking
+ *
+ * This is not a complete snapshot of the hardware registers. Switch target
+ * lists and endpoint DPA skip values are not tracked in this common structure.
+ */
+struct cxl_decoder_config {
+	int id;
+	struct range hpa_range;
+	int interleave_ways;
+	int interleave_granularity;
+	enum cxl_decoder_type target_type;
+	unsigned long flags;
+};
+
+/**
+ * struct cxl_decoder - Common CXL HDM Decoder Attributes
+ * @dev: this decoder's device
+ * @config: common decoder configuration and state
+ * @region: currently assigned region for this decoder
  * @target_map: cached copy of hardware port-id list, available at init
  *              before all @dport objects have been instantiated. While
  *              dport id is 8bit, CFMWS interleave targets are 32bits.
@@ -53,13 +69,8 @@ enum cxl_decoder_type {
 */
 struct cxl_decoder {
 	struct device dev;
-	int id;
-	struct range hpa_range;
-	int interleave_ways;
-	int interleave_granularity;
-	enum cxl_decoder_type target_type;
+	struct cxl_decoder_config config;
 	struct cxl_region *region;
-	unsigned long flags;
 	u32 target_map[CXL_DECODER_MAX_INTERLEAVE];
 	int (*commit)(struct cxl_decoder *cxld);
 	void (*reset)(struct cxl_decoder *cxld);
tools/testing/cxl/test/cxl.c +77 -81

346 lines not on this page · raw message

Signature · 1 line
2.43.0
#16 lore raw

PATCH v17 7/19 cxl: Share HDM decoder register unpacking

In reply to Srirangan Madhavan

Factor common HDM register parsing into cxl_hdm_unpack_decoder(). Validate range and interleave parameters in locals before publishing the decoder configuration, including enable and lock flags. Reject nonzero ranges whose end overflows the address space while preserving the zero-size range representation.

Read decoder base and size registers low then high through a shared helper used by enumeration and the reset snapshot.

Read switch target lists and endpoint DPA skip in their respective branches of init_hdm_decoder().

Preserve the decoder ID allocated by cxl_decoder_init() when publishing the parsed configuration.

---
Changes in v17:
- Initialize the zero-size end to base - 1 and document the zero-size case, removing a branch (Richard)
https://lore.kernel.org/linux-cxl/auQ27s1rSCcbdRJ3@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=7d6ed7faf7d8e14abce8ae23902d5323738868d2

---
 drivers/cxl/core/core.h     |  5 +++
 drivers/cxl/core/hdm.c      | 65 ++++++++------------------------
 drivers/cxl/core/hdm_regs.c | 74 +++++++++++++++++++++++++++++++++++++
 3 files changed, 95 insertions(+), 49 deletions(-)
drivers/cxl/core/core.h +5 -0
index fb14b222f3ca..ea539f00e55d 100644
@@ -147,6 +147,11 @@ void cxl_commit_start_switch(const struct cxl_decoder_config *config,
 			     u64 targets, void __iomem *hdm);
 int cxld_await_commit(void __iomem *hdm, int id);
 
+int cxl_hdm_unpack_decoder(struct cxl_decoder_config *config, int id,
+			   u32 ctrl, u64 base, u64 size);
+int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
+			 int id, u32 ctrl);
+
 int cxl_memdev_init(void);
 void cxl_memdev_exit(void);
 void cxl_mbox_init(void);
drivers/cxl/core/hdm.c +16 -49

98 lines not on this page · raw message

drivers/cxl/core/hdm_regs.c +74 -0

77 lines not on this page · raw message

Signature · 1 line
2.43.0
#19 lore raw

PATCH v17 8/19 cxl: Move cxl_rwsem into built-in code

In reply to Srirangan Madhavan

Keep the region and DPA locks available to built-in CXL state management when cxl_core is modular.

---
 drivers/cxl/core/Makefile    |  2 +-
 drivers/cxl/core/hdm.c       |  5 -----
 drivers/cxl/core/hdm_state.c | 15 +++++++++++++++
 3 files changed, 16 insertions(+), 6 deletions(-)
 create mode 100644 drivers/cxl/core/hdm_state.c
drivers/cxl/core/Makefile +1 -1
index 6703c1729396..9971efb237fb 100644
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CXL_BUS) += cxl_core.o
-obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o
+obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o
 obj-$(CONFIG_CXL_SUSPEND) += suspend.o
 
 ccflags-y += -I$(srctree)/drivers/cxl
drivers/cxl/core/hdm.c +0 -5
index 5b5f5f22ea32..85f9abf58a42 100644
@@ -17,11 +17,6 @@
  * for enumerating these registers and capabilities.
  */
 
-struct cxl_rwsem cxl_rwsem = {
-	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
-	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
-};
-
 static int add_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld)
 {
 	int rc;
drivers/cxl/core/hdm_state.c new file +15 -0
new file mode 100644
index 000000000000..c9cc019902ef
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/export.h>
+#include <linux/rwsem.h>
+
+#include <cxl/hdm.h>
+
+#include "cxl.h"
+#include "core.h"
+
+struct cxl_rwsem cxl_rwsem = {
+	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
+	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
+};
+EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
Signature · 1 line
2.43.0
#22 lore raw

PATCH v17 9/19 cxl: Refresh cached PCI HDM decoder settings

In reply to Srirangan Madhavan

Early PCI discovery creates the HDM cache, while later CXL enumeration and decoder operations provide updated programming state.

Refresh the PCI snapshot when decoders are enumerated, committed, or reset so reset recovery need not walk the CXL topology. Keep cache access and locking in the built-in HDM state helpers. Ignore updates when no cache exists and reject decoder-count mismatches.

Use CXL_RESET for the PCI HDM cache. Shared HDM register helpers do not require it.

Skip cache checks and updates for DVSEC-emulated decoders, which do not use HDM registers. Keep cached global control when MMIO reads return all ones.

Non-PCI mock ports have no upstream PCI device, so the cache helpers ignore them. This avoids test wrappers and a circular dependency between cxl_core and cxl_mock.

---
Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=50a88f5194e5df38590d413f925d8d5afa8a8488

---
 drivers/cxl/Kconfig          |  5 ++++
 drivers/cxl/core/core.h      |  1 +
 drivers/cxl/core/hdm.c       | 34 +++++++++++++++++++--
 drivers/cxl/core/hdm_state.c | 57 ++++++++++++++++++++++++++++++++++++
 drivers/cxl/core/pci.c       | 24 +++++++++++++++
 include/cxl/cxl.h            |  1 +
 include/cxl/hdm.h            | 32 ++++++++++++++++++++
 include/linux/pci.h          |  6 ++++
 8 files changed, 158 insertions(+), 2 deletions(-)
drivers/cxl/Kconfig +5 -0
index 80aeb0d556bd..8b08bfdc4982 100644
@@ -6,6 +6,7 @@ menuconfig CXL_BUS
 	select FW_UPLOAD
 	select PCI_DOE
 	select FIRMWARE_TABLE
+	select CXL_RESET
 	select NUMA_KEEP_MEMINFO if NUMA_MEMBLKS
 	select FWCTL if CXL_FEATURES
 	help
@@ -244,3 +245,7 @@ config CXL_ATL
 	depends on ACPI_PRMT && AMD_NB
 
 endif
+
+# CXL_BUS requires the PCI HDM cache and built-in state helpers, even when modular.
+config CXL_RESET
+	bool
drivers/cxl/core/core.h +1 -0
index ea539f00e55d..e34d574f6594 100644
@@ -224,6 +224,7 @@ static inline void devm_cxl_dport_ras_setup(struct cxl_dport *dport) { }
 int cxl_gpf_port_setup(struct cxl_dport *dport);
 
 struct cxl_hdm;
+int cxl_hdm_check_decoder_count(struct cxl_hdm *cxlhdm);
 int cxl_hdm_decode_init(struct cxl_dev_state *cxlds, struct cxl_hdm *cxlhdm,
 			struct cxl_endpoint_dvsec_info *info);
 int cxl_port_get_possible_dports(struct cxl_port *port);
drivers/cxl/core/hdm.c +32 -2
index 85f9abf58a42..ec387070d7ad 100644
@@ -725,6 +725,24 @@ static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt)
 		*tgt |= FIELD_PREP(GENMASK_ULL(63, 56), t[7]->port_id);
 }
 
+static void cxl_hdm_refresh_decoder(struct cxl_hdm *cxlhdm,
+				    struct cxl_decoder *cxld)
+{
+	void __iomem *hdm = cxlhdm->regs.hdm_decoder;
+	struct pci_dev *pdev __free(pci_dev_put) = NULL;
+
+	if (!hdm)
+		return;
+	if (!is_endpoint_decoder(&cxld->dev))
+		return;
+
+	pdev = cxl_port_get_uport_pci_dev(cxlhdm->port);
+	if (!pdev)
+		return;
+	cxl_hdm_cache_refresh_decoder(pdev, hdm,
+				      to_cxl_endpoint_decoder(&cxld->dev));
+}
+
 static void
 cxl_endpoint_decoder_snapshot(struct cxl_endpoint_decoder *cxled,
 			      struct cxl_endpoint_decoder_settings *settings)
@@ -805,6 +823,7 @@ static int cxl_decoder_commit(struct cxl_decoder *cxld)
 	}
 	port->commit_end++;
 	cxld->config.flags |= CXL_DECODER_F_ENABLE;
+	cxl_hdm_refresh_decoder(cxlhdm, cxld);
 
 	return 0;
 }
@@ -877,6 +896,7 @@ static void cxl_decoder_reset(struct cxl_decoder *cxld)
 	writel(0, hdm + CXL_HDM_DECODER0_BASE_LOW_OFFSET(id));
 
 	cxld->config.flags &= ~CXL_DECODER_F_ENABLE;
+	cxl_hdm_refresh_decoder(cxlhdm, cxld);
 
 	/* Userspace is now responsible for reconfiguring this decoder */
 	if (is_endpoint_decoder(&cxld->dev)) {
@@ -1079,13 +1099,21 @@ static int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm,
 {
 	void __iomem *hdm = cxlhdm->regs.hdm_decoder;
 	struct cxl_port *port = cxlhdm->port;
-	int i;
+	/* DVSEC-emulated decoders do not describe the cached HDM registers. */
+	bool emulated = should_emulate_decoders(info);
 	u64 dpa_base = 0;
+	int i, rc;
+
+	if (is_cxl_endpoint(port) && hdm && !emulated) {
+		rc = cxl_hdm_check_decoder_count(cxlhdm);
+		if (rc)
+			return rc;
+	}
 
 	cxl_settle_decoders(cxlhdm);
 
 	for (i = 0; i < cxlhdm->decoder_count; i++) {
-		int rc, target_count = cxlhdm->target_count;
+		int target_count = cxlhdm->target_count;
 		struct cxl_decoder *cxld;
 
 		if (is_cxl_endpoint(port)) {
@@ -1120,6 +1148,8 @@ static int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm,
 			put_device(&cxld->dev);
 			return rc;
 		}
+		if (!emulated)
+			cxl_hdm_refresh_decoder(cxlhdm, cxld);
 		rc = add_hdm_decoder(port, cxld);
 		if (rc) {
 			dev_warn(&port->dev,
drivers/cxl/core/hdm_state.c +57 -0

66 lines not on this page · raw message

drivers/cxl/core/pci.c +24 -0
index f72cd8f50e77..5272013548c7 100644
@@ -6,6 +6,7 @@
 #include <linux/delay.h>
 #include <linux/pci.h>
 #include <linux/pci-doe.h>
+#include <cxl/hdm.h>
 #include <cxl/pci.h>
 #include <linux/aer.h>
 #include <cxlpci.h>
@@ -180,6 +181,29 @@ int cxl_await_media_ready(struct cxl_dev_state *cxlds)
 }
 EXPORT_SYMBOL_NS_GPL(cxl_await_media_ready, "CXL");
 
+/**
+ * cxl_hdm_check_decoder_count() - check enumeration against the PCI HDM cache
+ * @cxlhdm: HDM capability containing the decoder count to check
+ *
+ * Take cxl_rwsem.dpa for read while comparing the cached count. Call only
+ * for hardware HDM decoders, since DVSEC-emulated ranges do not describe
+ * the HDM registers represented by the cache.
+ *
+ * Return: 0 if the counts match or no upstream PCI device or cache exists,
+ * or -ENXIO if the cached and enumerated decoder counts differ.
+ */
+int cxl_hdm_check_decoder_count(struct cxl_hdm *cxlhdm)
+{
+	struct pci_dev *pdev __free(pci_dev_put) =
+		cxl_port_get_uport_pci_dev(cxlhdm->port);
+
+	if (!pdev)
+		return 0;
+
+	return cxl_hdm_cache_check_decoder_count(pdev, cxlhdm->decoder_count);
+}
+EXPORT_SYMBOL_NS_GPL(cxl_hdm_check_decoder_count, "CXL");
+
 static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)
 {
 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
include/cxl/cxl.h +1 -0
index 6d6e564be27a..341a7c52894a 100644
@@ -26,6 +26,7 @@ enum cxl_devtype {
 };
 
 struct cxl_region;
+struct cxl_hdm_info;
 
 enum cxl_decoder_type {
 	CXL_DECODER_DEVMEM = 2,
include/cxl/hdm.h +32 -0
index 219b9bb67440..06e9aa4479c2 100644
@@ -6,6 +6,9 @@
 #include <linux/types.h>
 #include <cxl/cxl.h>
 
+struct pci_dev;
+struct cxl_endpoint_decoder;
+
 /**
  * struct cxl_endpoint_decoder_settings - endpoint HDM decoder programming
  * @config: common decoder configuration
@@ -16,4 +19,33 @@ struct cxl_endpoint_decoder_settings {
 	u64 skip;
 };
 
+/**
+ * struct cxl_hdm_info - cached CXL HDM state for a PCI device
+ * @decoder_count: number of entries in @settings
+ * @hdm_bar: PCI BAR containing the HDM decoder capability
+ * @hdm_offset: offset of the HDM decoder capability in @hdm_bar
+ * @hdm_size: size of the HDM decoder register block
+ * @global_ctrl: HDM decoder global control register
+ * @dvsec_ctrl: CXL DVSEC control register
+ * @dvsec_ctrl_valid: whether @dvsec_ctrl contains valid state
+ * @settings: per-endpoint-decoder programming state
+ *
+ * Publication through pci_dev.hdm and all mutable fields are protected by
+ * cxl_rwsem.dpa.
+ */
+struct cxl_hdm_info {
+	int decoder_count;
+	int hdm_bar;
+	resource_size_t hdm_offset;
+	resource_size_t hdm_size;
+	u32 global_ctrl;
+	u16 dvsec_ctrl;
+	bool dvsec_ctrl_valid;
+	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
+};
+
+void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
+				   struct cxl_endpoint_decoder *cxled);
+int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+
 #endif /* __CXL_HDM_H__ */
include/linux/pci.h +6 -0
index d31a8d107b1e..7bb37fcb556d 100644
@@ -339,6 +339,9 @@ struct pcie_link_state;
 struct pci_sriov;
 struct pci_p2pdma;
 struct rcec_ea;
+#ifdef CONFIG_CXL_RESET
+struct cxl_hdm_info;
+#endif
 
 /* struct pci_dev - describes a PCI device
  *
@@ -566,6 +569,9 @@ struct pci_dev {
 #ifdef CONFIG_PCI_DOE
 	struct xarray	doe_mbs;	/* Data Object Exchange mailboxes */
 #endif
+#ifdef CONFIG_CXL_RESET
+	struct cxl_hdm_info *hdm;	/* CXL HDM decoder state */
+#endif
 #ifdef CONFIG_PCI_NPEM
 	struct npem	*npem;		/* Native PCIe Enclosure Management */
 #endif
Signature · 1 line
2.43.0
#25 lore raw

PATCH v17 10/19 cxl: Build register block helpers into the kernel

In reply to Srirangan Madhavan

Build register discovery with the built-in HDM helpers so PCI enumeration can use it even when cxl_core is modular. Export the interfaces used by cxl_core and preserve the BAR and offset in the register map.

---
 drivers/cxl/core/Makefile |  3 +--
 drivers/cxl/core/regs.c   |  9 +++++++++
 drivers/cxl/cxl.h         |  3 ---
 include/cxl/cxl.h         |  5 +++++
 include/cxl/pci.h         | 13 +++++++++++++
 tools/testing/cxl/Kbuild  |  1 -
 6 files changed, 28 insertions(+), 6 deletions(-)
drivers/cxl/core/Makefile +1 -2
index 9971efb237fb..9a77e68d44ce 100644
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CXL_BUS) += cxl_core.o
-obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o
+obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o regs.o
 obj-$(CONFIG_CXL_SUSPEND) += suspend.o
 
 ccflags-y += -I$(srctree)/drivers/cxl
@@ -8,7 +8,6 @@ CFLAGS_trace.o = -DTRACE_INCLUDE_PATH=. -I$(src)
 
 cxl_core-y := port.o
 cxl_core-y += pmem.o
-cxl_core-y += regs.o
 cxl_core-y += memdev.o
 cxl_core-y += mbox.o
 cxl_core-y += pci.o
drivers/cxl/core/regs.c +9 -0
index 20c2d9fbcfe7..def3c20d1a7a 100644
@@ -200,6 +200,7 @@ void __iomem *devm_cxl_iomap_block(struct device *dev, resource_size_t addr,
 
 	return ret_val;
 }
+EXPORT_SYMBOL_FOR_MODULES(devm_cxl_iomap_block, "cxl_core");
 
 int cxl_map_component_regs(const struct cxl_register_map *map,
 			   struct cxl_component_regs *regs,
@@ -285,6 +286,8 @@ static bool cxl_decode_regblock(struct pci_dev *pdev, u32 reg_lo, u32 reg_hi,
 	}
 
 	map->reg_type = reg_type;
+	map->bar = bar;
+	map->bar_offset = offset;
 	map->resource = pci_resource_start(pdev, bar) + offset;
 	map->max_size = pci_resource_len(pdev, bar) - offset;
 	return true;
@@ -309,6 +312,7 @@ static int __cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_ty
 	*map = (struct cxl_register_map) {
 		.host = &pdev->dev,
 		.resource = CXL_RESOURCE_NONE,
+		.bar = -1,
 	};
 
 	regloc = pci_find_dvsec_capability(pdev, PCI_VENDOR_ID_CXL,
@@ -339,6 +343,8 @@ static int __cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_ty
 	}
 
 	map->resource = CXL_RESOURCE_NONE;
+	map->bar = -1;
+	map->bar_offset = 0;
 	if (index == CXL_INSTANCES_COUNT)
 		return instance;
 
@@ -518,6 +524,7 @@ u16 cxl_rcrb_to_aer(struct device *dev, resource_size_t rcrb)
 
 	return offset;
 }
+EXPORT_SYMBOL_NS_GPL(cxl_rcrb_to_aer, "CXL");
 
 static resource_size_t cxl_rcrb_to_linkcap(struct device *dev, struct cxl_dport *dport)
 {
@@ -634,6 +641,7 @@ resource_size_t __rcrb_to_component(struct device *dev, struct cxl_rcrb_info *ri
 
 	return component_reg_phys;
 }
+EXPORT_SYMBOL_NS_GPL(__rcrb_to_component, "CXL");
 
 resource_size_t cxl_rcd_component_reg_phys(struct device *dev,
 					   struct cxl_dport *dport)
@@ -642,3 +650,4 @@ resource_size_t cxl_rcd_component_reg_phys(struct device *dev,
 		return CXL_RESOURCE_NONE;
 	return __rcrb_to_component(dev, &dport->rcrb, CXL_RCRB_UPSTREAM);
 }
+EXPORT_SYMBOL_NS_GPL(cxl_rcd_component_reg_phys, "CXL");
drivers/cxl/cxl.h +0 -3
index 688350c7c5fb..ad4e80be2bd7 100644
@@ -239,9 +239,6 @@ enum cxl_regloc_type;
 int cxl_count_regblock(struct pci_dev *pdev, enum cxl_regloc_type type);
 int cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_type type,
 			       struct cxl_register_map *map, unsigned int index);
-int cxl_find_regblock(struct pci_dev *pdev, enum cxl_regloc_type type,
-		      struct cxl_register_map *map);
-int cxl_setup_regs(struct cxl_register_map *map);
 struct cxl_dport;
 int cxl_dport_map_rcd_linkcap(struct pci_dev *pdev, struct cxl_dport *dport);
 
include/cxl/cxl.h +5 -0
index 341a7c52894a..ea23bc15d00e 100644
@@ -27,6 +27,7 @@ enum cxl_devtype {
 
 struct cxl_region;
 struct cxl_hdm_info;
+struct pci_dev;
 
 enum cxl_decoder_type {
 	CXL_DECODER_DEVMEM = 2,
@@ -150,6 +151,8 @@ struct cxl_pmu_reg_map {
  * @base: virtual base of the register-block-BAR + @block_offset
  * @resource: physical resource base of the register block
  * @max_size: maximum mapping size to perform register search
+ * @bar: PCI BAR containing the register block
+ * @bar_offset: register block offset relative to @bar
  * @reg_type: see enum cxl_regloc_type
  * @component_map: cxl_reg_map for component registers
  * @device_map: cxl_reg_maps for device registers
@@ -160,6 +163,8 @@ struct cxl_register_map {
 	void __iomem *base;
 	resource_size_t resource;
 	resource_size_t max_size;
+	int bar;
+	resource_size_t bar_offset;
 	u8 reg_type;
 	union {
 		struct cxl_component_reg_map component_map;
include/cxl/pci.h +13 -0
index 3e0000015871..b15d7e415e27 100644
@@ -4,6 +4,8 @@
 #ifndef __CXL_CXL_PCI_H__
 #define __CXL_CXL_PCI_H__
 
+#include <linux/types.h>
+
 /* Register Block Identifier (RBI) */
 enum cxl_regloc_type {
 	CXL_REGLOC_RBI_EMPTY = 0,
@@ -19,4 +21,15 @@ struct pci_dev;
 
 int cxl_pci_setup_regs(struct pci_dev *pdev, enum cxl_regloc_type type,
 		       struct cxl_register_map *map);
+int cxl_find_regblock(struct pci_dev *pdev, enum cxl_regloc_type type,
+		      struct cxl_register_map *map);
+int cxl_setup_regs(struct cxl_register_map *map);
+/*
+ * CXL r4.0 sec 8.1.3.1: a CXL.mem capable device reports one or two HDM
+ * ranges. 00b is illegal when Mem_Capable is set and 11b is reserved.
+ */
+static inline bool cxl_dvsec_hdm_count_valid(unsigned int hdm_count)
+{
+	return hdm_count == 1 || hdm_count == 2;
+}
 #endif
tools/testing/cxl/Kbuild +0 -1
index 2be1df80fcc9..e80500f457a9 100644
@@ -55,7 +55,6 @@ obj-m += cxl_core.o
 
 cxl_core-y := $(CXL_CORE_SRC)/port.o
 cxl_core-y += $(CXL_CORE_SRC)/pmem.o
-cxl_core-y += $(CXL_CORE_SRC)/regs.o
 cxl_core-y += $(CXL_CORE_SRC)/memdev.o
 cxl_core-y += $(CXL_CORE_SRC)/mbox.o
 cxl_core-y += $(CXL_CORE_SRC)/pci.o
Signature · 1 line
2.43.0
#28 lore raw

PATCH v17 11/19 PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Srirangan Madhavan

Cache HDM state in pci_dev->hdm after BAR resource setup and before driver binding, so reset can restore it without a bound CXL driver.

Limit caching to devices that advertise CXL.cache, CXL.mem, CXL Reset, and Reset Memory Clear. Save their HDM register location, decoder settings, and Device DVSEC state.

Validate capability reads and decoder counts, and restore PCI_COMMAND after temporary MMIO access, reporting restoration failures. Publish the cache under the PCI device lock and protect later updates with the DPA lock.

Assisted-by LLM

---
Changes in v17:
- Publish the cache under the PCI device lock without taking cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming)
https://lore.kernel.org/linux-cxl/[email protected]/
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() before it is written back or cached (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=11
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard)
https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b12baa1105f33cc1a10f9c9c0c6376194397d9f3

---
 MAINTAINERS                   |   1 +
 drivers/cxl/core/hdm_regs.c   |  96 +++++++++++++++
 drivers/cxl/core/hdm_state.c  |  37 +++++-
 drivers/cxl/core/pci.c        |  29 +++--
 drivers/pci/Makefile          |   1 +
 drivers/pci/bus.c             |   1 +
 drivers/pci/cxl.c             | 225 ++++++++++++++++++++++++++++++++++
 drivers/pci/pci.h             |   8 ++
 drivers/pci/probe.c           |   1 +
 include/cxl/hdm.h             |   9 ++
 include/uapi/linux/pci_regs.h |   2 +
 11 files changed, 399 insertions(+), 11 deletions(-)
 create mode 100644 drivers/pci/cxl.c
MAINTAINERS +1 -0
index c2414447892c..b874340b0265 100644
@@ -6572,6 +6572,7 @@ S:	Maintained
 F:	Documentation/driver-api/cxl
 F:	Documentation/userspace-api/fwctl/fwctl-cxl.rst
 F:	drivers/cxl/
+F:	drivers/pci/cxl.c
 F:	include/cxl/
 F:	include/uapi/linux/cxl_mem.h
 F:	tools/testing/cxl/
drivers/cxl/core/hdm_regs.c +96 -0

105 lines not on this page · raw message

drivers/cxl/core/hdm_state.c +36 -1
index d4c2be1ef833..9def4a7439c9 100644
@@ -1,21 +1,37 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/cleanup.h>
 #include <linux/export.h>
 #include <linux/io.h>
 #include <linux/pci.h>
 #include <linux/rwsem.h>
+#include <linux/slab.h>
 
 #include <cxl/hdm.h>
-
 #include "cxl.h"
 #include "core.h"
 
+/*
+ * CXL state that must stay available while no CXL driver is bound: the CXL
+ * locks and the per-device HDM cache filled during PCI enumeration.
+ */
 struct cxl_rwsem cxl_rwsem = {
 	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
 	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
 };
 EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
 
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl)
+{
+	guard(rwsem_write)(&cxl_rwsem.dpa);
+	if (!pdev->hdm)
+		return;
+
+	pdev->hdm->dvsec_ctrl = ctrl;
+	pdev->hdm->dvsec_ctrl_valid = true;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_set_dvsec_ctrl, "cxl_core");
+
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled)
 {
@@ -70,3 +86,22 @@ int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count)
 	return 0;
 }
 EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_check_decoder_count, "cxl_core");
+
+/**
+ * cxl_hdm_cache_release() - unpublish and free cached HDM state
+ * @slot: cache pointer owned by the device
+ *
+ * Take the DPA write lock to exclude readers while clearing @slot, then
+ * free the unpublished cache after releasing the lock.
+ */
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot)
+{
+	struct cxl_hdm_info *info;
+
+	scoped_guard(rwsem_write, &cxl_rwsem.dpa) {
+		info = *slot;
+		/* Unpublish before freeing so readers cannot see stale state. */
+		*slot = NULL;
+	}
+	kfree(info);
+}
drivers/cxl/core/pci.c +19 -10
index 5272013548c7..ea5327cd627f 100644
@@ -209,22 +209,31 @@ static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)
 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
 	int d = cxlds->cxl_dvsec;
 	u16 ctrl;
-	int rc;
+	int rc, ret = 1;
 
 	rc = pci_read_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, &ctrl);
 	if (rc)
 		return pcibios_err_to_errno(rc);
+	/* An all-ones read must not be written back or cached. */
+	if (PCI_POSSIBLE_ERROR(ctrl))
+		return -ENODEV;
 
-	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) == val)
-		return 1;
-	ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
-	ctrl |= val;
+	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) != val) {
+		ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
+		ctrl |= val;
 
-	rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
-	if (rc)
-		return pcibios_err_to_errno(rc);
+		rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		ret = 0;
+	}
 
-	return 0;
+	/*
+	 * Refresh the PCI-core cache from the live register even when
+	 * MEM_ENABLE already matched: a reset restores the cached value.
+	 */
+	cxl_hdm_cache_set_dvsec_ctrl(pdev, ctrl);
+	return ret;
 }
 
 static void clear_mem_enable(void *cxlds)
@@ -314,7 +323,7 @@ int cxl_dvsec_rr_decode(struct cxl_dev_state *cxlds,
 	 * capable, there is no point in continuing to enable CXL.mem.
 	 */
 	hdm_count = FIELD_GET(PCI_DVSEC_CXL_HDM_COUNT, cap);
-	if (!hdm_count || hdm_count > 2)
+	if (!cxl_dvsec_hdm_count_valid(hdm_count))
 		return -EINVAL;
 
 	/*
drivers/pci/Makefile +1 -0
index 41ebc3b9a518..7a5d9f7297e9 100644
@@ -34,6 +34,7 @@ obj-$(CONFIG_PCI_P2PDMA)	+= p2pdma.o
 obj-$(CONFIG_XEN_PCIDEV_FRONTEND) += xen-pcifront.o
 obj-$(CONFIG_VGA_ARB)		+= vgaarb.o
 obj-$(CONFIG_PCI_DOE)		+= doe.o
+obj-$(CONFIG_CXL_RESET)		+= cxl.o
 obj-$(CONFIG_PCI_IDE)		+= ide.o
 obj-$(CONFIG_PCI_TSM)		+= tsm.o
 obj-$(CONFIG_PCI_DYNAMIC_OF_NODES) += of_property.o
drivers/pci/bus.c +1 -0
index 655ed53436d3..aad567fb7c56 100644
@@ -359,6 +359,7 @@ void pci_bus_add_device(struct pci_dev *dev)
 
 	/* Save config space for error recoverability */
 	pci_save_state(dev);
+	pci_cxl_hdm_cache_init(dev);
 
 	/*
 	 * Enable runtime PM, which potentially allows the device to
drivers/pci/cxl.c new file +225 -0

225 lines not on this page · raw message

drivers/pci/pci.h +8 -0
index ba3c3fddddc2..9e218f236e66 100644
@@ -730,6 +730,14 @@ static inline void pci_doe_destroy(struct pci_dev *pdev) { }
 static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #endif
 
+#ifdef CONFIG_CXL_RESET
+void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
+void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
+#else
+static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
+static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
+#endif
+
 #ifdef CONFIG_PCI_NPEM
 void pci_npem_create(struct pci_dev *dev);
 void pci_npem_remove(struct pci_dev *dev);
drivers/pci/probe.c +1 -0
index 27008e2ea5af..cb52357344ed 100644
@@ -2484,6 +2484,7 @@ static void pci_release_dev(struct device *dev)
 	struct pci_dev *pci_dev;
 
 	pci_dev = to_pci_dev(dev);
+	pci_cxl_hdm_cache_release(pci_dev);
 	pci_release_capabilities(pci_dev);
 	pci_release_of_node(pci_dev);
 	pcibios_release_device(pci_dev);
include/cxl/hdm.h +9 -0
index 06e9aa4479c2..0604dcc439c9 100644
@@ -26,6 +26,7 @@ struct cxl_endpoint_decoder_settings {
  * @hdm_offset: offset of the HDM decoder capability in @hdm_bar
  * @hdm_size: size of the HDM decoder register block
  * @global_ctrl: HDM decoder global control register
+ * @dvsec: config space offset of the CXL Device DVSEC
  * @dvsec_ctrl: CXL DVSEC control register
  * @dvsec_ctrl_valid: whether @dvsec_ctrl contains valid state
  * @settings: per-endpoint-decoder programming state
@@ -39,13 +40,21 @@ struct cxl_hdm_info {
 	resource_size_t hdm_offset;
 	resource_size_t hdm_size;
 	u32 global_ctrl;
+	u16 dvsec;
 	u16 dvsec_ctrl;
 	bool dvsec_ctrl_valid;
 	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
 };
+struct device;
 
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+				 resource_size_t size);
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+		       struct cxl_hdm_info *info);
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl);
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled);
 int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
 
 #endif /* __CXL_HDM_H__ */
include/uapi/linux/pci_regs.h +2 -0
index facaa324bd86..ca3e77b72d87 100644
@@ -1352,6 +1352,8 @@
 #define   PCI_DVSEC_CXL_CACHE_CAPABLE			_BITUL(0)
 #define   PCI_DVSEC_CXL_MEM_CAPABLE			_BITUL(2)
 #define   PCI_DVSEC_CXL_HDM_COUNT			__GENMASK(5, 4)
+#define   PCI_DVSEC_CXL_RST_CAPABLE			_BITUL(7)
+#define   PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE		_BITUL(11)
 #define  PCI_DVSEC_CXL_CTRL				0xC
 #define   PCI_DVSEC_CXL_MEM_ENABLE			_BITUL(2)
 #define  PCI_DVSEC_CXL_RANGE_SIZE_HIGH(i)		(0x18 + (i * 0x10))
Signature · 1 line
2.43.0
#39 lore raw

PATCH v17 13/19 cxl: Validate and synchronize HDM ranges around reset

In reply to Srirangan Madhavan

Refuse reset unless enabled system-physical HDM ranges can be reserved exclusively and CPU-cache invalidation is available. Invalidate before reset and again before ending IOMMU exclusion, holding range reservations until the second invalidation completes. A later patch places state restoration before the second invalidation.

Userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges: the reset fails while a conflicting resource is claimed, and no one can claim the range during the reset. It cannot see accesses by code that uses the range without claiming it, which the offline expectation also covers.

Reject normalized-addressing decoders because their cached ranges are not system physical addresses. Record Normalized Addressing in the cache when region discovery sets it, since the cache is filled earlier. A reset that takes its snapshot between endpoint probe and that update can still miss it.

Ignore zero-size decoders because they map no address range. Refuse reset when the device decodes memory through its DVSEC ranges instead of HDM decoders, since the cache holds no range to reserve for that memory.

Hold the global cxl_rwsem.region write lock across snapshot, reset and restoration to keep the decoder state and reserved ranges stable. This also blocks region and decoder sysfs, region probe, poison operations, sanitize and region-aware event tracing across CXL devices. The Memory Clear wait lasts up to the timeout the device advertises, at most 100 seconds; cache flushes and other reset work extend the hold.

Allow the existing CXL_REGION_INVALIDATION_TEST option to bypass missing CPU cache invalidation for test environments without a provider.

Assisted-by LLM

---
Changes in v17:
- State that userspace is expected to offline CXL.mem users before reset, and what the HPA reservation does and does not cover (Richard)
https://lore.kernel.org/linux-cxl/auQRSOGWEDzB_qjF@MWDK4CY14F/
- Record Normalized Addressing in the cached decoder when region discovery sets it, and note the short window before that update (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=13
- Annotate cxl_region_quiesce_lock()/unlock() and __cxl_reset_execute() for context analysis (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=15
- Describe the region lock hold as bounded by the advertised reset timeout, at most 100 seconds, plus cache flushes (Richard)
https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=5944c6e61f14c0dd28d54537be15edb2cadb0e8b

---
 drivers/cxl/Kconfig          |   3 +-
 drivers/cxl/core/hdm_state.c | 266 ++++++++++++++++++++++++++++++++++-
 drivers/cxl/core/region.c    |  14 ++
 drivers/pci/cxl.c            |  87 ++++++++++--
 include/cxl/hdm.h            |  47 ++++++-
 5 files changed, 406 insertions(+), 11 deletions(-)
drivers/cxl/Kconfig +2 -1
index 8b08bfdc4982..e927e69a3f7b 100644
@@ -226,7 +226,8 @@ config CXL_REGION_INVALIDATION_TEST
 	  invalidation mechanism. For example usage of wbinvd is restricted to
 	  bare metal x86. However, for testing purposes toggling this option
 	  can disable that data integrity safety and proceed with enabling
-	  regions when there might be conflicting contents in the CPU cache.
+	  regions or performing CXL reset when there might be conflicting
+	  contents in the CPU cache.
 
 	  If unsure, or if this kernel is meant for production environments,
 	  say N.
drivers/cxl/core/hdm_state.c +265 -1

289 lines not on this page · raw message

drivers/cxl/core/region.c +14 -0
index 8cfc06df3134..b06dd9b901f0 100644
@@ -12,6 +12,7 @@
 #include <linux/idr.h>
 #include <linux/memory-tiers.h>
 #include <linux/string_choices.h>
+#include <cxl/hdm.h>
 #include <cxlmem.h>
 #include <cxl.h>
 #include "core.h"
@@ -3840,6 +3841,19 @@ int cxl_add_to_region(struct cxl_endpoint_decoder *cxled)
 	if (IS_ERR(cxlrd))
 		return PTR_ERR(cxlrd);
 
+	/*
+	 * Translation setup may have marked the decoder as Normalized
+	 * Addressing, after the PCI cache was filled. Record it for reset.
+	 */
+	if (cxled->cxld.config.flags & CXL_DECODER_F_NORMALIZED_ADDRESSING) {
+		struct pci_dev *pdev __free(pci_dev_put) =
+			cxl_port_get_uport_pci_dev(cxled_to_port(cxled));
+
+		if (pdev)
+			cxl_hdm_cache_set_normalized(pdev,
+						     cxled->cxld.config.id);
+	}
+
 	/*
 	 * Ensure that, if multiple threads race to construct_region()
 	 * for the HPA range, one does the construction and the others
drivers/pci/cxl.c +79 -8

138 lines not on this page · raw message

include/cxl/hdm.h +46 -1

69 lines not on this page · raw message

Signature · 1 line
2.43.0
#43 lore raw

PATCH v17 14/19 PCI/CXL: Reject reset with unsafe function scope

In reply to Srirangan Madhavan

The per-device PCI reset interface must not reset sibling functions. Reject cxl_reset and cxl_bus for VFs, multifunction devices, and PFs with enabled VFs.

---
Changes in v17:
- Move the function-scope checks ahead of the CXL DVSEC lookups, so a VF returns -ENOTTY without config reads during reset-method probing (Joshua)
https://lore.kernel.org/linux-cxl/[email protected]/

---
 drivers/pci/cxl.c | 3 +++
 drivers/pci/pci.c | 7 +++++++
 2 files changed, 10 insertions(+)
drivers/pci/cxl.c +3 -0
index af8ec8db20f1..c07266ab0133 100644
@@ -501,6 +501,9 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	u16 dvsec, cap, ctrl;
 	int rc;
 
+	if (pdev->is_virtfn || pdev->multifunction || pci_num_vf(pdev))
+		return -ENOTTY;
+
 	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
 	if (rc)
 		return rc;
drivers/pci/pci.c +7 -0
index b2879a6be5f8..aef976d0c850 100644
@@ -5018,6 +5018,13 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	u16 dvsec, reg, val;
 	int rc;
 
+	/*
+	 * Reject VFs and multifunction devices before walking the bridge's
+	 * capabilities: every VF behind the same bridge would repeat the walk.
+	 */
+	if (dev->is_virtfn || dev->multifunction || pci_num_vf(dev))
+		return -ENOTTY;
+
 	bridge = pci_upstream_bridge(dev);
 	if (!bridge)
 		return -ENOTTY;
Signature · 1 line
2.43.0
#45 lore raw

PATCH v17 15/19 PCI/CXL: Restore CXL state after PCI reset

In reply to Srirangan Madhavan

Restore the PCI configuration needed for HDM access, followed by cached HDM decoder and CXL Device DVSEC state. Set Lock On Commit before recommitting a cleared locked decoder; leave surviving locked state unchanged.

Stop at the first restoration failure and preserve a disabled PCI command snapshot. Keep IOMMU exclusion active through restoration and post-reset cache invalidation.

Program the decoders from built-in CXL code that takes only a mapped register block, and keep PCI state handling in drivers/pci/cxl.c.

The restore helper structure and diagnostics follow Dave Jiang's reference implementation on his cxl-type2-reset branch.

Assisted-by LLM

---
Changes in v17:
- Set Lock On Commit after programming the decoder registers and before Commit when recommitting a locked decoder, so the lock takes effect at commit (Alison)
https://lore.kernel.org/linux-cxl/[email protected]/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=81fff5893a3140361cac625b09ada798afb92e03

---
 drivers/cxl/core/core.h     |   2 +-
 drivers/cxl/core/hdm.c      |   2 +-
 drivers/cxl/core/hdm_regs.c | 177 +++++++++++++++++++++++++++++++---
 drivers/pci/cxl.c           | 185 ++++++++++++++++++++++++++++++++++--
 include/cxl/hdm.h           |   2 +
 5 files changed, 346 insertions(+), 22 deletions(-)
drivers/cxl/core/core.h +1 -1
index e34d574f6594..9fc9fd6c771e 100644
@@ -145,7 +145,7 @@ void cxl_commit_start_endpoint(const struct cxl_endpoint_decoder_settings *setti
 			       void __iomem *hdm);
 void cxl_commit_start_switch(const struct cxl_decoder_config *config,
 			     u64 targets, void __iomem *hdm);
-int cxld_await_commit(void __iomem *hdm, int id);
+int cxld_await_commit(void __iomem *hdm, int id, bool committed);
 
 int cxl_hdm_unpack_decoder(struct cxl_decoder_config *config, int id,
 			   u32 ctrl, u64 base, u64 size);
drivers/cxl/core/hdm.c +1 -1
index ec387070d7ad..ad8cb1e76afb 100644
@@ -815,7 +815,7 @@ static int cxl_decoder_commit(struct cxl_decoder *cxld)
 	scoped_guard(rwsem_read, &cxl_rwsem.dpa)
 		setup_hw_decoder(cxld, hdm);
 
-	rc = cxld_await_commit(hdm, cxld->config.id);
+	rc = cxld_await_commit(hdm, cxld->config.id, true);
 	if (rc) {
 		dev_dbg(&port->dev, "%s: error %d committing decoder\n",
 			dev_name(&cxld->dev), rc);
drivers/cxl/core/hdm_regs.c +163 -14

225 lines not on this page · raw message

drivers/pci/cxl.c +179 -6

234 lines not on this page · raw message

include/cxl/hdm.h +2 -0
index 49b36a45c682..94a8f8a1a65a 100644
@@ -54,6 +54,8 @@ int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
 				 resource_size_t size);
 int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
 		       struct cxl_hdm_info *info);
+int cxl_hdm_restore_state(void __iomem *hdm,
+			  const struct cxl_hdm_info *snapshot);
 void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl);
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled);
Signature · 1 line
2.43.0
#47 lore raw

PATCH v17 16/19 PCI/CXL: Expose CXL Reset as a PCI reset method

In reply to Srirangan Madhavan

Register cxl_reset with the PCI reset-method interface and place it before FLR, which does not reset CXL.cache or CXL.mem protocol state.

Return -ENOTTY when device capabilities, function scope, cached HDM state, or required cache synchronization do not permit a safe reset.

---
 drivers/pci/cxl.c   | 12 +++++++++---
 drivers/pci/pci.c   |  1 +
 include/linux/pci.h |  2 +-
 3 files changed, 11 insertions(+), 4 deletions(-)
drivers/pci/cxl.c +9 -3
index 77d0e30841d9..c68b08f7f95b 100644
@@ -679,7 +679,7 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 
 	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
 	if (rc)
-		return rc;
+		return probe ? -ENOTTY : rc;
 	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||
 	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
 	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
@@ -688,9 +688,9 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 
 	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL, &ctrl);
 	if (rc)
-		return pcibios_err_to_errno(rc);
+		return probe ? -ENOTTY : pcibios_err_to_errno(rc);
 	if (PCI_POSSIBLE_ERROR(ctrl))
-		return -ENODEV;
+		return probe ? -ENOTTY : -ENODEV;
 	if (!(ctrl & PCI_DVSEC_CXL_CACHE_ENABLE) ||
 	    !(ctrl & PCI_DVSEC_CXL_MEM_ENABLE))
 		return -ENOTTY;
@@ -710,5 +710,11 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	    !IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST))
 		return -ENOTTY;
 
+	/* Raw reset callers may not have saved the PCI state needed for restore. */
+	if (!pdev->state_saved) {
+		pci_err(pdev, "CXL reset requires saved PCI state\n");
+		return -EINVAL;
+	}
+
 	return cxl_reset_execute(pdev, dvsec, cap);
 }
drivers/pci/pci.c +1 -0
index aef976d0c850..426b5ee38d04 100644
@@ -5152,6 +5152,7 @@ const struct pci_reset_fn_method pci_reset_fn_methods[] = {
 	{ },
 	{ pci_dev_specific_reset, .name = "device_specific" },
 	{ pci_dev_acpi_reset, .name = "acpi" },
+	{ cxl_reset_function, .name = "cxl_reset" },
 	{ pcie_reset_flr, .name = "flr" },
 	{ pci_af_flr, .name = "af_flr" },
 	{ pci_pm_reset, .name = "pm" },
include/linux/pci.h +1 -1
index 7bb37fcb556d..743b57ff885a 100644
@@ -52,7 +52,7 @@
 			       PCI_STATUS_PARITY)
 
 /* Number of reset methods used in pci_reset_fn_methods array in pci.c */
-#define PCI_NUM_RESET_METHODS 8
+#define PCI_NUM_RESET_METHODS 9
 
 #define PCI_RESET_PROBE		true
 #define PCI_RESET_DO_RESET	false
Signature · 1 line
2.43.0
#51 lore raw

PATCH v17 17/19 PCI/CXL: Restore CXL state after CXL bus reset

In reply to Srirangan Madhavan

CXL bus reset can clear HDM decoder programming and CXL Device DVSEC control state. Restore the cached state after a successful cxl_bus reset while IOMMU exclusion remains active.

Restore PCI configuration first so HDM MMIO is accessible, and preserve a disabled state if restoration fails.

Copy the cached state before the reset, then refresh its decoder settings from the cache under the CXL region quiesce once the reset completes. A region decommit during the reset updates the cache, and restoring the earlier decoders would leave the endpoint decoding an HPA range that the CXL core considers free. Keep global and DVSEC control from before the reset, since a refresh during the reset can read them as all-ones.

The prepare/restore interface and decoder-refresh structure follow Dave Jiang's cxl-type2-reset reference branch.

---
Changes in v17:
- Enable bus mastering only after the IOMMU is restored, via a separate cxl_restore_command_after_pci_reset() step (Richard)
https://lore.kernel.org/linux-cxl/auRhJa-nzR0CnKf3@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b93f0c8e67b198a63786fd3721b7177ab9df60be

---
 drivers/cxl/core/hdm_state.c | 31 +++++++++++++
 drivers/pci/cxl.c            | 85 ++++++++++++++++++++++++++++++++++++
 drivers/pci/pci.c            | 14 ++++++
 drivers/pci/pci.h            | 24 ++++++++++
 include/cxl/hdm.h            |  2 +
 5 files changed, 156 insertions(+)
drivers/cxl/core/hdm_state.c +31 -0
index 51df56377f7a..7e0903ce0b78 100644
@@ -182,6 +182,37 @@ struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot)
 	return copy;
 }
 
+/**
+ * cxl_hdm_cache_copy_decoders() - refresh the decoders of a snapshot
+ * @slot: cache pointer owned by the device
+ * @dst: snapshot of the same device from cxl_hdm_cache_snapshot()
+ *
+ * Copy only the per-decoder settings, which region commit and teardown keep
+ * current. Leave the rest of @dst, including global and DVSEC control, as
+ * captured: a refresh during a reset may have read those registers from a
+ * device that returned all-ones.
+ *
+ * Return: 0 on success, -ENXIO when nothing is published, or -EINVAL when
+ * @dst holds a different number of decoders.
+ */
+int cxl_hdm_cache_copy_decoders(struct cxl_hdm_info *const *slot,
+				struct cxl_hdm_info *dst)
+{
+	struct cxl_hdm_info *info;
+
+	lockdep_assert_held_write(&cxl_rwsem.region);
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	info = *slot;
+	if (!info)
+		return -ENXIO;
+	if (info->decoder_count != dst->decoder_count)
+		return -EINVAL;
+
+	memcpy(dst->settings, info->settings,
+	       flex_array_size(info, settings, info->decoder_count));
+	return 0;
+}
+
 void cxl_region_quiesce_lock(void)
 	__acquires(cxl_region_quiesce)
 	__context_unsafe(token maps to cxl_rwsem.region)
drivers/pci/cxl.c +85 -0

91 lines not on this page · raw message

drivers/pci/pci.c +14 -0
index 426b5ee38d04..1d4ba90a6976 100644
@@ -5014,8 +5014,10 @@ static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
 
 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 {
+	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
 	struct pci_dev *bridge;
 	u16 dvsec, reg, val;
+	u16 command;
 	int rc;
 
 	/*
@@ -5040,6 +5042,10 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	if (rc)
 		return -ENOTTY;
 
+	snapshot = pci_cxl_reset_prepare(dev);
+	if (IS_ERR(snapshot))
+		return PTR_ERR(snapshot);
+
 	rc = pci_dev_reset_iommu_prepare(dev);
 	if (rc) {
 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", rc);
@@ -5060,7 +5066,15 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
 				      reg);
 
+	if (!rc && snapshot)
+		rc = cxl_restore_state_after_pci_reset(dev, snapshot, &command);
+
 	pci_dev_reset_iommu_done(dev);
+
+	/* Enable bus mastering only once the IOMMU translates again. */
+	if (!rc && snapshot)
+		rc = cxl_restore_command_after_pci_reset(dev, command);
+
 	return rc;
 }
 
drivers/pci/pci.h +24 -0
index 743e65abd758..2f819e1fbead 100644
@@ -730,10 +730,16 @@ static inline void pci_doe_destroy(struct pci_dev *pdev) { }
 static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #endif
 
+struct cxl_hdm_info;
 #ifdef CONFIG_CXL_RESET
 void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
 void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
 int cxl_reset_function(struct pci_dev *pdev, bool probe);
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev);
+int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
+				      struct cxl_hdm_info *snapshot,
+				      u16 *command);
+int cxl_restore_command_after_pci_reset(struct pci_dev *pdev, u16 command);
 #else
 static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
 static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
@@ -741,6 +747,24 @@ static inline int cxl_reset_function(struct pci_dev *pdev, bool probe)
 {
 	return -ENOTTY;
 }
+
+static inline struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev)
+{
+	return NULL;
+}
+
+static inline int
+cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
+				  struct cxl_hdm_info *snapshot, u16 *command)
+{
+	return 0;
+}
+
+static inline int cxl_restore_command_after_pci_reset(struct pci_dev *pdev,
+						      u16 command)
+{
+	return 0;
+}
 #endif
 
 #ifdef CONFIG_PCI_NPEM
include/cxl/hdm.h +2 -0
index 94a8f8a1a65a..81767f21052a 100644
@@ -64,6 +64,8 @@ void cxl_hdm_cache_set_normalized(struct pci_dev *pdev, int id);
 void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
 bool cxl_hdm_cache_dvsec_decode(struct cxl_hdm_info *const *slot);
 struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot);
+int cxl_hdm_cache_copy_decoders(struct cxl_hdm_info *const *slot,
+				struct cxl_hdm_info *dst);
 
 /*
  * Region quiesce blocks CXL region commit and teardown, and with them decoder
Signature · 1 line
2.43.0
#54 lore raw

PATCH v17 18/19 PCI/CXL: Flush host and device caches for CXL bus reset

In reply to Srirangan Madhavan

CXL bus reset can reset a Type 2 device while its host and device caches still contain data for the device's HDM ranges. Flush the host caches, disable device caching, and trigger device cache writeback and invalidation when supported before reset. Invalidate the host caches again before ending IOMMU exclusion.

Hold the CXL region quiesce from snapshot through restoration so region commit and teardown cannot change the decoder state while the reset is in progress. Reserve the affected HPA ranges and preserve the device's cache policy across the operation.

If reset was not attempted, undo preparation without changing the saved PCI command unless cleanup fails. After an attempted reset, keep the device disabled on recovery failure and do not re-enable caching against unrestored HDM state. Enable bus mastering only after the IOMMU is restored, so that no DMA request reaches the blocking domain.

If no cached HDM state exists, retain the existing CXL bus reset path. For a device with cached state, reject the reset if its cache-maintenance state cannot be safely prepared or restored. An invalidation provider is required unless the existing test-only CXL_REGION_INVALIDATION_TEST bypass is enabled.

---
Changes in v17:
- New in this series: folded into the CXL reset series instead of being posted separately (Dave)

---
 drivers/pci/cxl.c | 166 +++++++++++++++++++++++++++++++++++++---------
 drivers/pci/pci.c |  11 +--
 drivers/pci/pci.h |  19 ++++--
 3 files changed, 154 insertions(+), 42 deletions(-)
drivers/pci/cxl.c +134 -32
index a9aa2e1c631d..c5cdad4b0590 100644
@@ -393,74 +393,174 @@ static int pci_cxl_restore_state(struct pci_dev *pdev,
 	return cxl_restore_state(pdev, snapshot);
 }
 
+static int cxl_reset_restore_cache_policy(struct pci_dev *pdev, int dvsec,
+					  u16 saved_ctrl2);
+static int cxl_reset_cache_prepare(struct pci_dev *pdev, int dvsec, u16 cap,
+				   const struct cxl_hdm_info *snapshot,
+				   struct cxl_pci_cache *cache);
+
 /**
- * pci_cxl_reset_prepare() - allocate HDM state storage ahead of a bus reset
+ * pci_cxl_reset_prepare() - prepare HDM state and caches before a bus reset
  * @pdev: device about to be reset
+ * @cachep: receives cache state owning the region quiesce on success
  *
- * Copy the cached HDM state before the reset, so that restoring cannot fail
- * for lack of memory. The decoder settings are refreshed when the state is
- * restored.
+ * Capture HDM state under the region quiesce, reserve its ranges, and complete
+ * host and device cache maintenance. Hold the quiesce through reset and
+ * cxl_restore_state_after_pci_reset(), which consumes *@cachep.
  *
- * Return: storage for cxl_restore_state_after_pci_reset(), to be freed with
- * kfree(); NULL when @pdev has no cached HDM state; or an ERR_PTR() on
- * failure.
+ * Return: snapshot to be freed with kfree(), NULL when no cached HDM state is
+ * present, or an ERR_PTR() on failure. A cached device without a valid DVSEC
+ * snapshot is rejected because its cache-maintenance scope is unknown.
+ * Only a successful non-NULL snapshot returns with the region quiesce held
+ * and *@cachep set. The caller must pass both to
+ * cxl_restore_state_after_pci_reset() even if reset is never attempted.
+ * The snapshot remains caller-owned. All other returns leave the quiesce
+ * unheld and *@cachep NULL.
  */
-struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev)
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev,
+					struct cxl_pci_cache **cachep)
 {
 	struct cxl_hdm_info *snapshot;
+	struct cxl_pci_cache *cache;
+	u16 dvsec, cap, command;
+	int rc;
 
 	device_lock_assert(&pdev->dev);
-	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
-	if (IS_ERR(snapshot))
-		return PTR_ERR(snapshot) == -ENXIO ? NULL : snapshot;
+	*cachep = NULL;
+	if (!pdev->hdm)
+		return NULL;
 
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc == -ENOTTY)
+		return ERR_PTR(-ENODEV);
+	if (rc)
+		return ERR_PTR(rc);
 	/* Raw reset callers may not have saved the PCI state needed for restore. */
 	if (!pdev->state_saved) {
 		pci_err(pdev, "CXL bus reset requires saved PCI state\n");
-		kfree(snapshot);
 		return ERR_PTR(-EINVAL);
 	}
 
+	cache = kzalloc_obj(*cache);
+	if (!cache)
+		return ERR_PTR(-ENOMEM);
+	cxl_region_quiesce_lock();
+	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
+	if (IS_ERR(snapshot)) {
+		rc = PTR_ERR(snapshot);
+		goto unlock;
+	}
+	if (!snapshot->dvsec_ctrl_valid) {
+		rc = -ENXIO;
+		goto free_snapshot;
+	}
+	if (cxl_hdm_cache_dvsec_decode(&pdev->hdm) ||
+	    (snapshot->dvsec_ctrl & PCI_DVSEC_CXL_CACHE_ENABLE &&
+	     !(cap & PCI_DVSEC_CXL_CACHE_WBI_CAPABLE))) {
+		rc = -EOPNOTSUPP;
+		goto free_snapshot;
+	}
+
+	if (cap & PCI_DVSEC_CXL_CACHE_CAPABLE) {
+		rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2,
+					  &cache->saved_ctrl2);
+		if (rc || PCI_POSSIBLE_ERROR(cache->saved_ctrl2)) {
+			rc = rc ? pcibios_err_to_errno(rc) : -ENODEV;
+			goto free_snapshot;
+		}
+	}
+
+	rc = cxl_reset_cache_prepare(pdev, dvsec, cap, snapshot, cache);
+	if (rc) {
+		if (cache->cache_disabled)
+			goto finish;
+		pci_err(pdev, "failed to prepare CXL bus reset ranges: %d\n", rc);
+		cxl_hdm_quiesce_destroy(&cache->quiesce);
+		goto free_snapshot;
+	}
+	if (!pci_wait_for_pending_transaction(pdev)) {
+		rc = -ETIMEDOUT;
+		goto finish;
+	}
+	*cachep = cache;
 	return snapshot;
+
+finish:
+	rc = cxl_restore_state_after_pci_reset(pdev, snapshot, cache, false, rc,
+					       &command);
+	kfree(snapshot);
+	return ERR_PTR(rc);
+free_snapshot:
+	kfree(snapshot);
+unlock:
+	cxl_region_quiesce_unlock();
+	kfree(cache);
+	return ERR_PTR(rc);
 }
 
 /**
- * cxl_restore_state_after_pci_reset() - restore CXL state after a bus reset
+ * cxl_restore_state_after_pci_reset() - finish a prepared reset and release its quiesce
  * @pdev: device that was reset
  * @snapshot: storage from pci_cxl_reset_prepare()
+ * @cache: quiesce state from pci_cxl_reset_prepare()
+ * @reset_attempted: reset helper was invoked and may have affected hardware
+ * @rc: preparation or PCI reset result
  * @command: returns the saved PCI_COMMAND value to apply once the IOMMU is
  *	     restored
  *
- * Under the region quiesce, refresh the decoder settings in @snapshot from the
- * cache and restore: first the PCI configuration needed to reach HDM MMIO,
- * then the HDM decoder and CXL Device DVSEC state. Leave @pdev disabled on
- * failure.
+ * Restore state through pci_cxl_restore_state(), complete host invalidation,
+ * and restore the cache policy changed by planned-reset preparation. When
+ * @reset_attempted is false, undo preparation without changing the saved PCI
+ * command, unless cleanup itself fails. After an attempted reset, keep caching
+ * and the device disabled if state restoration or host invalidation fails.
+ * A reset-helper error does not prove that hardware was untouched.
+ * Unplanned recovery uses pci_cxl_restore_state() directly and owns its own
+ * quiesce and cache-maintenance sequencing.
  *
  * Bus mastering stays off, because the caller has not yet restored IOMMU
  * translation and a DMA request now would hit the blocking domain. The caller
  * calls cxl_restore_command_after_pci_reset() once the IOMMU is restored.
  *
- * Refresh the decoders now rather than rely on the copy taken before the
- * reset: a region commit or teardown during the reset has updated the cache,
- * and restoring older decoders would leave the device decoding ranges the
- * CXL core considers free.
+ * The quiesce blocks region commit and teardown throughout reset. Complete
+ * host cache invalidation before PCI operation resumes, then release the
+ * quiesce and free @cache on every exit. @snapshot remains caller-owned.
  */
 int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
-				      struct cxl_hdm_info *snapshot,
-				      u16 *command)
+				      const struct cxl_hdm_info *snapshot,
+				      struct cxl_pci_cache *cache,
+				      bool reset_attempted, int rc, u16 *command)
 {
-	int rc;
+	int rc2, policy_rc = 0;
 
+	*command = 0;
+	if (!cache)
+		return rc;
 	device_lock_assert(&pdev->dev);
-	cxl_region_quiesce_lock();
-
-	rc = cxl_hdm_cache_copy_decoders(&pdev->hdm, snapshot);
-	if (!rc)
+	if (reset_attempted && !rc)
 		rc = pci_cxl_restore_state(pdev, snapshot, command);
-	if (rc)
-		cxl_reset_save_disabled_state(pdev);
 
+	/* Complete host invalidation before ending IOMMU exclusion. */
+	rc2 = cxl_hdm_quiesce_flush(&cache->quiesce);
+	if (rc2)
+		pci_err(pdev, "failed to invalidate CPU cache after CXL bus reset: %d\n", rc2);
+	/* Undo preparation on abort; enable caching after reset only if safe. */
+	if (cache->cache_disabled && (!reset_attempted || (!rc && !rc2)))
+		policy_rc = cxl_reset_restore_cache_policy(pdev, snapshot->dvsec,
+							  cache->saved_ctrl2);
+	if (reset_attempted) {
+		rc = rc ?: rc2 ?: policy_rc;
+		if (rc)
+			cxl_reset_save_disabled_state(pdev);
+	} else {
+		/* An aborted reset alone must not poison the saved PCI command. */
+		if (rc2 || policy_rc)
+			cxl_reset_save_disabled_state(pdev);
+		rc = rc ?: rc2 ?: policy_rc;
+	}
+
+	cxl_hdm_quiesce_destroy(&cache->quiesce);
 	cxl_region_quiesce_unlock();
+	kfree(cache);
 	return rc;
 }
 
@@ -594,7 +694,7 @@ static int cxl_reset_cache_prepare(struct pci_dev *pdev, int dvsec, u16 cap,
 	int rc;
 
 	rc = cxl_hdm_quiesce_prepare(&cache->quiesce, snapshot);
-	if (rc)
+	if (rc || !(cap & PCI_DVSEC_CXL_CACHE_CAPABLE))
 		return rc;
 
 	/* Track an attempted change so partial failures still restore policy. */
@@ -731,7 +831,9 @@ static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
 		rc = __cxl_reset_execute(pdev, dvsec, cap, snapshot, &cache.quiesce,
 					 &command);
 	/* Restore cache policy after any attempt to disable caching. */
-	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
+	rc2 = 0;
+	if (cache.cache_disabled)
+		rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
 	cxl_hdm_quiesce_destroy(&cache.quiesce);
 	if (rc)
 		return rc;
drivers/pci/pci.c +7 -4
index 1d4ba90a6976..b29a6a43249d 100644
@@ -5015,6 +5015,7 @@ static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 {
 	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
+	struct cxl_pci_cache *cache;
 	struct pci_dev *bridge;
 	u16 dvsec, reg, val;
 	u16 command;
@@ -5042,14 +5043,15 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	if (rc)
 		return -ENOTTY;
 
-	snapshot = pci_cxl_reset_prepare(dev);
+	snapshot = pci_cxl_reset_prepare(dev, &cache);
 	if (IS_ERR(snapshot))
 		return PTR_ERR(snapshot);
 
 	rc = pci_dev_reset_iommu_prepare(dev);
 	if (rc) {
 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", rc);
-		return rc;
+		return cxl_restore_state_after_pci_reset(dev, snapshot, cache,
+							 false, rc, &command);
 	}
 
 	if (reg & PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR) {
@@ -5066,8 +5068,9 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
 				      reg);
 
-	if (!rc && snapshot)
-		rc = cxl_restore_state_after_pci_reset(dev, snapshot, &command);
+	/* Reset-helper failure does not prove that no hardware reset occurred. */
+	rc = cxl_restore_state_after_pci_reset(dev, snapshot, cache, true, rc,
+					       &command);
 
 	pci_dev_reset_iommu_done(dev);
 
drivers/pci/pci.h +13 -6
index 2f819e1fbead..7f6b81cf734b 100644
@@ -731,14 +731,17 @@ static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #endif
 
 struct cxl_hdm_info;
+struct cxl_pci_cache;
 #ifdef CONFIG_CXL_RESET
 void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
 void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
 int cxl_reset_function(struct pci_dev *pdev, bool probe);
-struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev);
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev,
+					struct cxl_pci_cache **cachep);
 int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
-				      struct cxl_hdm_info *snapshot,
-				      u16 *command);
+				      const struct cxl_hdm_info *snapshot,
+				      struct cxl_pci_cache *cache,
+				      bool reset_attempted, int rc, u16 *command);
 int cxl_restore_command_after_pci_reset(struct pci_dev *pdev, u16 command);
 #else
 static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
@@ -748,16 +751,20 @@ static inline int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	return -ENOTTY;
 }
 
-static inline struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev)
+static inline struct cxl_hdm_info *
+pci_cxl_reset_prepare(struct pci_dev *pdev, struct cxl_pci_cache **cachep)
 {
+	*cachep = NULL;
 	return NULL;
 }
 
 static inline int
 cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
-				  struct cxl_hdm_info *snapshot, u16 *command)
+				  const struct cxl_hdm_info *snapshot,
+				  struct cxl_pci_cache *cache,
+				  bool reset_attempted, int rc, u16 *command)
 {
-	return 0;
+	return rc;
 }
 
 static inline int cxl_restore_command_after_pci_reset(struct pci_dev *pdev,
Signature · 1 line
2.43.0
#56 lore raw

PATCH v17 19/19 cxl: Add KUnit checks for HDM decoder unpacking

In reply to Srirangan Madhavan

Test cxl_hdm_unpack_decoder() without a PCI device or HDM MMIO. Cover range boundaries and overflow, an all-ones base, zero-size and uncommitted decoders, and a locked host-only decoder with 12-way interleave.

Run the checks as a KUnit suite rather than during cxl_test module loading, so a failure does not prevent unrelated CXL mock tests from running. An uncommitted decoder has no meaningful target type, so do not check it.

---
 drivers/cxl/.kunitconfig             |  4 ++
 drivers/cxl/Kconfig                  | 10 +++
 drivers/cxl/Makefile                 |  1 +
 drivers/cxl/core/hdm_regs.c          |  2 +-
 drivers/cxl/tests/Makefile           |  5 ++
 drivers/cxl/tests/hdm_unpack_kunit.c | 91 ++++++++++++++++++++++++++++
 6 files changed, 112 insertions(+), 1 deletion(-)
 create mode 100644 drivers/cxl/.kunitconfig
 create mode 100644 drivers/cxl/tests/Makefile
 create mode 100644 drivers/cxl/tests/hdm_unpack_kunit.c
drivers/cxl/.kunitconfig new file +4 -0
new file mode 100644
index 000000000000..4fee684f5ff6
@@ -0,0 +1,4 @@
+CONFIG_KUNIT=y
+CONFIG_PCI=y
+CONFIG_CXL_BUS=y
+CONFIG_CXL_KUNIT_TEST=y
drivers/cxl/Kconfig +10 -0
index e927e69a3f7b..7f70f6babd74 100644
@@ -213,6 +213,16 @@ config CXL_REGION
 
 	  If unsure say 'y'
 
+config CXL_KUNIT_TEST
+	tristate "KUnit tests for CXL" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS
+	help
+	  Build the KUnit tests for the CXL subsystem. When built as modules,
+	  each test suite is its own module.
+
+	  If unsure, say N.
+
 config CXL_REGION_INVALIDATION_TEST
 	bool "CXL: Region Cache Management Bypass (TEST)"
 	depends on CXL_REGION
drivers/cxl/Makefile +1 -0
index 2caa90fa4bf2..d57fb0e9e7da 100644
@@ -13,6 +13,7 @@ obj-$(CONFIG_CXL_ACPI) += cxl_acpi.o
 obj-$(CONFIG_CXL_PMEM) += cxl_pmem.o
 obj-$(CONFIG_CXL_MEM) += cxl_mem.o
 obj-$(CONFIG_CXL_PCI) += cxl_pci.o
+obj-$(CONFIG_CXL_KUNIT_TEST) += tests/
 
 cxl_port-y := port.o
 cxl_acpi-y := acpi.o
drivers/cxl/core/hdm_regs.c +1 -1
index 4f5e843cd141..98b37edf5590 100644
@@ -188,7 +188,7 @@ int cxl_hdm_unpack_decoder(struct cxl_decoder_config *config, int id,
 
 	return 0;
 }
-EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_unpack_decoder, "cxl_core");
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_unpack_decoder, "cxl_core,cxl_hdm_unpack_kunit");
 
 int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
 			 int id, u32 ctrl)
drivers/cxl/tests/Makefile new file +5 -0
new file mode 100644
index 000000000000..c29dccfa9b24
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+ccflags-y += -I$(srctree)/drivers/cxl
+
+obj-$(CONFIG_CXL_KUNIT_TEST) += cxl_hdm_unpack_kunit.o
+cxl_hdm_unpack_kunit-y := hdm_unpack_kunit.o
drivers/cxl/tests/hdm_unpack_kunit.c new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.43.0
#34 lore raw

PATCH v17 12/19 PCI/CXL: Add CXL Device Reset sequencing

In reply to Srirangan Madhavan

Implement CXL Device Reset for eligible Type 2 devices: disable CXL.cache, perform supported writeback, drain transactions, prepare the IOMMU, initiate reset with Memory Clear enabled, and wait for completion.

Observe the 100 ms post-reset quiet period before polling Status2, and treat an all-ones read as not ready. Wait for the timeout the device advertises, up to 100 seconds, and access only Status2 until reset completion, error or expiry, as CXL 4.0 section 9.7.3 requires. Control2 cleanup runs only afterwards. Treat Control2 command bits as transient state, restore cache policy on exit, preserve the primary error, and abort when IOMMU preparation fails.

Reuse Device DVSEC discovery from cache initialization and keep the reset entry point declaration private to PCI core.

---
Changes in v17:
- Wait for the reset timeout the device advertises, up to 100 seconds, instead of clamping it to 20 seconds, so that Control2 is not accessed while the device may still be resetting. The warning for an unknown timeout encoding now reports the timeout used (Richard)
https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=04f8f84816d724f8b47f4d47a77916ac37c63a49

---
 drivers/pci/cxl.c             | 244 +++++++++++++++++++++++++++++++++-
 drivers/pci/pci.h             |   5 +
 include/uapi/linux/pci_regs.h |  12 ++
 3 files changed, 260 insertions(+), 1 deletion(-)
drivers/pci/cxl.c +243 -1
index a0d20f4210a5..9ac5948f595b 100644
@@ -3,13 +3,17 @@
 /*
  * CXL reset support in the PCI core. Cache the HDM decoder state of a CXL
  * memory device at enumeration, so it can be restored after a reset without
- * a CXL driver. HDM register formats and programming live in drivers/cxl.
+ * a CXL driver, and implement CXL Device Reset. HDM register formats and
+ * programming live in drivers/cxl.
  */
 #include <linux/bitfield.h>
 #include <linux/cleanup.h>
+#include <linux/delay.h>
 #include <linux/errno.h>
 #include <linux/io.h>
 #include <linux/ioport.h>
+#include <linux/iommu.h>
+#include <linux/jiffies.h>
 #include <linux/kernel.h>
 #include <linux/pci.h>
 #include <linux/slab.h>
@@ -223,3 +227,241 @@ void pci_cxl_hdm_cache_release(struct pci_dev *pdev)
 {
 	cxl_hdm_cache_release(&pdev->hdm);
 }
+
+/*
+ * CXL r4.0 sec 9.7.2 defines the reset completion timeout encodings.
+ * Sec 9.7.3 leaves config-space access behavior undefined for 100 ms after
+ * initiating CXL Reset, then limits software to CXL Status2 access until
+ * reset completion, timeout, or error. Wait for the full advertised timeout
+ * so that Control2 is not accessed while the device may still be resetting.
+ */
+#define CXL_RESET_RRS_WAIT_MS 100
+#define CXL_RESET_STATUS_POLL_MS 20
+static const u32 cxl_reset_timeout_ms[] = {
+	10, 100, 1000, 10000, 100000,
+};
+
+/*
+ * CXL 4.0 section 9.6 permits using the device cache size to determine
+ * a timeout. Use a conservative fixed estimate of 100 ms.
+ */
+#define CXL_CACHE_WBI_TIMEOUT_US 100000
+#define CXL_CACHE_WBI_POLL_US 100
+
+#define CXL_RESET_CTRL2_CMD_MASK \
+	(PCI_DVSEC_CXL_INIT_CACHE_WBI | PCI_DVSEC_CXL_INIT_CXL_RST)
+
+static int cxl_reset_update_ctrl2(struct pci_dev *pdev, int dvsec,
+				  u16 set, u16 clear)
+{
+	u16 ctrl2;
+	int rc;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(ctrl2))
+		return -ENODEV;
+
+	/*
+	 * INIT_CACHE_WBI and INIT_CXL_RST are commands. Do not replay a command
+	 * that remains set in the value read back while updating persistent
+	 * Control2 state.
+	 */
+	ctrl2 &= ~CXL_RESET_CTRL2_CMD_MASK;
+	ctrl2 &= ~clear;
+	ctrl2 |= set;
+
+	rc = pci_write_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+
+	return 0;
+}
+
+static int cxl_reset_wait_cache_wbi(struct pci_dev *pdev, int dvsec)
+{
+	unsigned long deadline;
+	u16 status2;
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    PCI_DVSEC_CXL_INIT_CACHE_WBI, 0);
+	if (rc)
+		return rc;
+
+	deadline = jiffies + usecs_to_jiffies(CXL_CACHE_WBI_TIMEOUT_US);
+	while (time_before(jiffies, deadline)) {
+		usleep_range(CXL_CACHE_WBI_POLL_US,
+			     CXL_CACHE_WBI_POLL_US * 2);
+
+		rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_STATUS2,
+					  &status2);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		if (PCI_POSSIBLE_ERROR(status2))
+			return -ENODEV;
+		if (status2 & PCI_DVSEC_CXL_CACHE_INV)
+			return 0;
+	}
+
+	pci_warn(pdev, "timed out waiting for CXL cache writeback and invalidate\n");
+	return -ETIMEDOUT;
+}
+
+static int cxl_reset_disable_cache(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    PCI_DVSEC_CXL_DISABLE_CACHING, 0);
+	if (rc || !(cap & PCI_DVSEC_CXL_CACHE_WBI_CAPABLE))
+		return rc;
+
+	return cxl_reset_wait_cache_wbi(pdev, dvsec);
+}
+
+static int cxl_reset_restore_cache_policy(struct pci_dev *pdev, int dvsec,
+					  u16 saved_ctrl2)
+{
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    saved_ctrl2 & PCI_DVSEC_CXL_DISABLE_CACHING,
+				    PCI_DVSEC_CXL_DISABLE_CACHING);
+	if (rc)
+		pci_err(pdev, "failed to restore CXL cache policy: %d\n", rc);
+
+	return rc;
+}
+
+static int cxl_reset_wait_done(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	unsigned long deadline;
+	u32 timeout_ms;
+	u16 status2;
+	int idx, rc;
+
+	idx = FIELD_GET(PCI_DVSEC_CXL_RST_TIMEOUT, cap);
+	if (idx >= ARRAY_SIZE(cxl_reset_timeout_ms)) {
+		idx = ARRAY_SIZE(cxl_reset_timeout_ms) - 1;
+		pci_warn(pdev,
+			 "unknown CXL reset timeout encoding; using %u ms\n",
+			 cxl_reset_timeout_ms[idx]);
+	}
+
+	/* Allow one retry after the mandatory 100 ms quiet period. */
+	timeout_ms = max_t(u32, cxl_reset_timeout_ms[idx],
+			   CXL_RESET_RRS_WAIT_MS + CXL_RESET_STATUS_POLL_MS);
+	pci_info(pdev, "CXL reset timeout: %u ms\n", timeout_ms);
+	msleep(CXL_RESET_RRS_WAIT_MS);
+	deadline = jiffies + msecs_to_jiffies(timeout_ms -
+					      CXL_RESET_RRS_WAIT_MS);
+
+	for (;;) {
+		rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_STATUS2,
+					  &status2);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		if (status2 != U16_MAX) {
+			if (status2 & PCI_DVSEC_CXL_RST_ERR)
+				return -EIO;
+			if (status2 & PCI_DVSEC_CXL_RST_DONE)
+				return 0;
+		}
+
+		if (time_after_eq(jiffies, deadline))
+			return -ETIMEDOUT;
+
+		msleep(CXL_RESET_STATUS_POLL_MS);
+	}
+}
+
+static int cxl_clear_memory(struct pci_dev *pdev, int dvsec, bool initiate)
+{
+	if (initiate)
+		return cxl_reset_update_ctrl2(pdev, dvsec,
+					      PCI_DVSEC_CXL_INIT_CXL_RST |
+					      PCI_DVSEC_CXL_RST_MEM_CLR_EN,
+					      0);
+
+	return cxl_reset_update_ctrl2(pdev, dvsec, 0,
+				      PCI_DVSEC_CXL_RST_MEM_CLR_EN);
+}
+
+static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc, rc2;
+
+	if (!pci_wait_for_pending_transaction(pdev)) {
+		pci_err(pdev, "timed out waiting for pending transactions\n");
+		return -ETIMEDOUT;
+	}
+
+	rc = pci_dev_reset_iommu_prepare(pdev);
+	if (rc) {
+		pci_err(pdev, "failed to stop IOMMU for CXL reset: %d\n", rc);
+		return rc;
+	}
+
+	rc = cxl_clear_memory(pdev, dvsec, true);
+	if (!rc)
+		rc = cxl_reset_wait_done(pdev, dvsec, cap);
+
+	/* Always clear Memory Clear; successful cleanup must not hide reset failure. */
+	rc2 = cxl_clear_memory(pdev, dvsec, false);
+	if (rc2)
+		pci_err(pdev, "failed to clear CXL Reset Memory Clear: %d\n", rc2);
+	rc = rc ?: rc2;
+
+	pci_dev_reset_iommu_done(pdev);
+	return rc;
+}
+
+static int cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	u16 saved_ctrl2;
+	int rc, rc2;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &saved_ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(saved_ctrl2))
+		return -ENODEV;
+
+	rc = cxl_reset_disable_cache(pdev, dvsec, cap);
+	if (!rc)
+		rc = __cxl_reset_execute(pdev, dvsec, cap);
+	/* Restore cache policy after any attempt to disable caching. */
+	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, saved_ctrl2);
+	return rc ?: rc2;
+}
+
+int cxl_reset_function(struct pci_dev *pdev, bool probe)
+{
+	u16 dvsec, cap, ctrl;
+	int rc;
+
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc)
+		return rc;
+	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE))
+		return -ENOTTY;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL, &ctrl);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(ctrl))
+		return -ENODEV;
+	if (!(ctrl & PCI_DVSEC_CXL_CACHE_ENABLE) ||
+	    !(ctrl & PCI_DVSEC_CXL_MEM_ENABLE))
+		return -ENOTTY;
+
+	if (probe)
+		return 0;
+
+	return cxl_reset_execute(pdev, dvsec, cap);
+}
drivers/pci/pci.h +5 -0
index 9e218f236e66..743e65abd758 100644
@@ -733,9 +733,14 @@ static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #ifdef CONFIG_CXL_RESET
 void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
 void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
+int cxl_reset_function(struct pci_dev *pdev, bool probe);
 #else
 static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
 static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
+static inline int cxl_reset_function(struct pci_dev *pdev, bool probe)
+{
+	return -ENOTTY;
+}
 #endif
 
 #ifdef CONFIG_PCI_NPEM
include/uapi/linux/pci_regs.h +12 -0
index ca3e77b72d87..7224857c7b30 100644
@@ -1352,10 +1352,22 @@
 #define   PCI_DVSEC_CXL_CACHE_CAPABLE			_BITUL(0)
 #define   PCI_DVSEC_CXL_MEM_CAPABLE			_BITUL(2)
 #define   PCI_DVSEC_CXL_HDM_COUNT			__GENMASK(5, 4)
+#define   PCI_DVSEC_CXL_CACHE_WBI_CAPABLE		_BITUL(6)
 #define   PCI_DVSEC_CXL_RST_CAPABLE			_BITUL(7)
+#define   PCI_DVSEC_CXL_RST_TIMEOUT			__GENMASK(10, 8)
 #define   PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE		_BITUL(11)
 #define  PCI_DVSEC_CXL_CTRL				0xC
+#define   PCI_DVSEC_CXL_CACHE_ENABLE			_BITUL(0)
 #define   PCI_DVSEC_CXL_MEM_ENABLE			_BITUL(2)
+#define  PCI_DVSEC_CXL_CTRL2				0x10
+#define   PCI_DVSEC_CXL_DISABLE_CACHING			_BITUL(0)
+#define   PCI_DVSEC_CXL_INIT_CACHE_WBI			_BITUL(1)
+#define   PCI_DVSEC_CXL_INIT_CXL_RST			_BITUL(2)
+#define   PCI_DVSEC_CXL_RST_MEM_CLR_EN			_BITUL(3)
+#define  PCI_DVSEC_CXL_STATUS2				0x12
+#define   PCI_DVSEC_CXL_CACHE_INV			_BITUL(0)
+#define   PCI_DVSEC_CXL_RST_DONE			_BITUL(1)
+#define   PCI_DVSEC_CXL_RST_ERR				_BITUL(2)
 #define  PCI_DVSEC_CXL_RANGE_SIZE_HIGH(i)		(0x18 + (i * 0x10))
 #define  PCI_DVSEC_CXL_RANGE_SIZE_LOW(i)		(0x1C + (i * 0x10))
 #define   PCI_DVSEC_CXL_MEM_INFO_VALID			_BITUL(0)
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v17 01/19] cxl: Clarify decoder interleave limit

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

CXL 2.0 added 16-way memory interleaving, making the comment that the specification supports only 8-way interleaving stale. Explain that 16 is the largest interleave a decoder can express, without changing the limit.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#9 lore raw

Re: [PATCH v17 03/19] cxl: Move decoder declarations to shared header

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 4 lines

Move the common decoder declarations to include/cxl/cxl.h for use by shared decoder settings. Preserve their layout and documentation.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#11 lore raw

Re: [PATCH v17 04/19] cxl: Embed decoder configuration in a standalone structure

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

Define cxl_decoder_config independently and embed it in cxl_decoder. Update decoder field accesses without changing behavior, so reset snapshots can reuse the configuration type without struct_group_tagged().

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#15 lore raw

Re: [PATCH v17 06/19] cxl: Move HDM decoder helpers to built-in code

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

The PCI core will restore HDM decoders after a reset, possibly while no CXL driver is loaded, so it cannot call into cxl_core.

Move the HDM register programming helpers from hdm.c to hdm_regs.c and build that file into the kernel whenever CXL_BUS is enabled, including when CXL_BUS is modular. Export only the symbols that cxl_core uses.

Quoted 5 lines

Keep the DPA lock assertion in the normal decoder programming caller so the register helpers do not depend on cxl_rwsem. Leave cxl_rwsem in cxl_core until built-in cache management needs it.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#13 lore raw

Re: [PATCH v17 05/19] cxl: Introduce endpoint HDM decoder settings

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

Keep common decoder configuration in cxl_decoder_config and represent endpoint DPA skip in cxl_endpoint_decoder_settings. Share range programming, but keep endpoint skip and switch target-list writes in their respective commit paths.

Separate commit initiation from completion waiting so reset restoration can reuse register programming without changing normal DPA-lock policy.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#20 lore raw

Re: [PATCH v17 08/19] cxl: Move cxl_rwsem into built-in code

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 4 lines

Keep the region and DPA locks available to built-in CXL state management when cxl_core is modular.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#4 lore raw

Re: [PATCH v17 02/19] cxl: Share CXL port upstream PCI device lookup

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] cxl: stale commit message and goto out on success path in read_cdat_data() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] cxl: stale commit message and goto out on success path in read_cdat_data() --

commit 731df7235bfc37ad38e18947501f81078ce6230b
Author: Srirangan Madhavan <[email protected]>

cxl: Share CXL port upstream PCI device lookup

This commit factors the lookup of a CXL port's upstream PCI device out of read_cdat_data() into a new cxl_port_get_uport_pci_dev() helper that returns a referenced struct pci_dev, and updates read_cdat_data() to release that reference via pci_dev_put().

Quoted 16 lines

cxl: Share CXL port upstream PCI device lookup

read_cdat_data() resolves a CXL port's upstream device to its backing PCI device. HDM cache updates need the same mapping.

Factor the lookup into cxl_port_get_uport_pci_dev() and return a referenced PCI device to make caller ownership explicit.

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

[ ... ]

Quoted 53 lines
drivers/cxl/core/pci.c +3 -16
index 9d807c1a002ca..905892cfedef6 100644
@@ -564,26 +564,13 @@ static unsigned char cdat_checksum(void *buf, size_t size)
  */
 void read_cdat_data(struct cxl_port *port)
 {
-	struct device *uport = port->uport_dev;
+	struct pci_dev *pdev = cxl_port_get_uport_pci_dev(port);
 	struct device *dev = &port->dev;
 	struct pci_doe_mb *doe_mb;
-	struct pci_dev *pdev = NULL;
-	struct cxl_memdev *cxlmd;
 	struct cdat_doe_rsp *buf;
 	size_t table_length, length;
 	int rc;
 
-	if (is_cxl_memdev(uport)) {
-		struct device *host;
-
-		cxlmd = to_cxl_memdev(uport);
-		host = cxlmd->dev.parent;
-		if (dev_is_pci(host))
-			pdev = to_pci_dev(host);
-	} else if (dev_is_pci(uport)) {
-		pdev = to_pci_dev(uport);
-	}
-
 	if (!pdev)
 		return;
 
@@ -591,14 +578,14 @@ void read_cdat_data(struct cxl_port *port)
 				      CXL_DOE_PROTOCOL_TABLE_ACCESS);
 	if (!doe_mb) {
 		dev_dbg(dev, "No CDAT mailbox\n");
-		return;
+		goto out;
 	}
 
 	port->cdat_available = true;
 
 	if (cxl_cdat_get_length(dev, doe_mb, &length)) {
 		dev_dbg(dev, "No CDAT length\n");
-		return;
+		goto out;
 	}
 
 	/*
@@ -624,12 +611,13 @@ void read_cdat_data(struct cxl_port *port)
 
 	port->cdat.table = buf->data;
 	port->cdat.length = length;

drivers/cxl/core/pci.c void read_cdat_data(struct cxl_port *port) · line 621

Quoted 10 lines
drivers/cxl/core/pci.c +3 -2
-
-	return;
+	goto out;
 err:
 	/* Don't leave table data allocated on error */
 	devm_kfree(dev, buf);
 	dev_err(dev, "Failed to read/validate CDAT.\n");
+out:
+	pci_dev_put(pdev);
 }

[Severity: Medium]
As reported by Jonathan Cameron on v13 [1], having the normal success path in read_cdat_data() jump over the err: label via goto out makes the control flow harder to follow, and Jonathan conditioned his Reviewed-by tag on not having the good path follow a goto.

In addition, when read_cdat_data() switched from __free(pci_dev_put) to explicit pci_dev_put(pdev) calls, the third paragraph of the commit message still states:

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

Should read_cdat_data() call pci_dev_put(pdev) directly before each return (and in the err: block) instead of jumping over err: with goto out on the normal path, and should the stale paragraph in the commit message be dropped?

[1] https://lore.kernel.org/r/20260924022156.5d376e91@jic23-hlaptop

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#17 lore raw

Re: [PATCH v17 07/19] cxl: Share HDM decoder register unpacking

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

Factor common HDM register parsing into cxl_hdm_unpack_decoder(). Validate range and interleave parameters in locals before publishing the decoder configuration, including enable and lock flags. Reject nonzero ranges whose end overflows the address space while preserving the zero-size range representation.

Read decoder base and size registers low then high through a shared helper used by enumeration and the reset snapshot.

Quoted 7 lines

Read switch target lists and endpoint DPA skip in their respective branches of init_hdm_decoder().

Preserve the decoder ID allocated by cxl_decoder_init() when publishing the parsed configuration.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#35 lore raw

Re: [PATCH v17 12/19] PCI/CXL: Add CXL Device Reset sequencing

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 12 lines

Implement CXL Device Reset for eligible Type 2 devices: disable CXL.cache, perform supported writeback, drain transactions, prepare the IOMMU, initiate reset with Memory Clear enabled, and wait for completion.

Observe the 100 ms post-reset quiet period before polling Status2, and treat an all-ones read as not ready. Wait for the timeout the device advertises, up to 100 seconds, and access only Status2 until reset completion, error or expiry, as CXL 4.0 section 9.7.3 requires. Control2 cleanup runs only afterwards. Treat Control2 command bits as transient state, restore cache policy on exit, preserve the primary error, and abort when IOMMU preparation fails.

Quoted 4 lines

Reuse Device DVSEC discovery from cache initialization and keep the reset entry point declaration private to PCI core.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#23 lore raw

Re: [PATCH v17 09/19] cxl: Refresh cached PCI HDM decoder settings

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Low] cxl: split declaration and init of __free() variable in cxl_hdm_refresh_decoder() - [Low] cxl…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] cxl: split declaration and init of __free() variable in cxl_hdm_refresh_decoder()
- [Low] cxl: unused struct cxl_hdm_info forward declaration in include/cxl/cxl.h --

commit 0273d4d08ae78949f901788b93c7db64fb203e17
Author: Srirangan Madhavan <[email protected]>

cxl: Refresh cached PCI HDM decoder settings

This commit refreshes the cached PCI HDM decoder state when hardware HDM decoders are enumerated, committed, or reset, and validates the enumerated decoder count against the cached count.

Quoted 10 lines
drivers/cxl/core/hdm.c +2 -0
index 85f9abf58a42b..ec387070d7adb 100644
@@ -725,6 +725,24 @@ static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt)
 		*tgt |= FIELD_PREP(GENMASK_ULL(63, 56), t[7]->port_id);
 }
 
+static void cxl_hdm_refresh_decoder(struct cxl_hdm *cxlhdm,
+				    struct cxl_decoder *cxld)

drivers/cxl/core/hdm.c static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt) · line 739

Quoted 10 lines
drivers/cxl/core/hdm.c +10 -0
+{
+	void __iomem *hdm = cxlhdm->regs.hdm_decoder;
+	struct pci_dev *pdev __free(pci_dev_put) = NULL;
+
+	if (!hdm)
+		return;
+	if (!is_endpoint_decoder(&cxld->dev))
+		return;
+
+	pdev = cxl_port_get_uport_pci_dev(cxlhdm->port);

[Severity: Low]
As reported by Cheatham, Benjamin on v13 [1], this isn't a bug, but in cxl_hdm_refresh_decoder() in drivers/cxl/core/hdm.c, pdev is declared with __free(pci_dev_put) = NULL at the top of the function and assigned later after the !hdm and !is_endpoint_decoder(&cxld->dev) early returns.

Should pdev be defined and initialized in a single statement where cxl_port_get_uport_pci_dev(cxlhdm->port) is called after the early returns, matching cxl_hdm_check_decoder_count() in drivers/cxl/core/pci.c and the kernel Cleanup API conventions?

[ ... ]

include/cxl/cxl.h enum cxl_devtype { · line 29

Quoted 9 lines
include/cxl/cxl.h +1 -0
index 6d6e564be27a9..341a7c52894ab 100644
@@ -26,6 +26,7 @@ enum cxl_devtype {
 };
 
 struct cxl_region;
+struct cxl_hdm_info;

[Severity: Low]
This isn't a bug, but struct cxl_hdm_info is not referenced anywhere in include/cxl/cxl.h (it is defined in include/cxl/hdm.h and forward-declared in include/linux/pci.h). Can this forward declaration be dropped from include/cxl/cxl.h?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#26 lore raw

Re: [PATCH v17 10/19] cxl: Build register block helpers into the kernel

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

Build register discovery with the built-in HDM helpers so PCI enumeration can use it even when cxl_core is modular. Export the interfaces used by cxl_core and preserve the BAR and offset in the register map.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#29 lore raw

Re: [PATCH v17 11/19] PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] PCI/CXL: missing all-ones checks when caching HDM and DVSEC control state - [High] PCI/CXL…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] PCI/CXL: missing all-ones checks when caching HDM and DVSEC control state
- [High] PCI/CXL: out-of-bounds MMIO read and size underflow in cxl_pci_hdm_map_regs()
- [High] PCI/CXL: pci_cxl_hdm_cache_init() runs before BAR survey and bridge enable
- [Medium] cxl/pci: disable_hdm() leaves stale CXL_HDM_DECODER_ENABLE in cached state --

commit e053ed26c570120750868c635b177e4dbb11e00d
Author: Srirangan Madhavan <[email protected]>

PCI/CXL: Cache endpoint HDM state during PCI enumeration

This commit caches CXL endpoint HDM register locations, decoder settings, and Device DVSEC state in pci_dev->hdm during PCI enumeration so that reset paths can restore HDM state without a bound CXL driver.

Quoted 5 lines
drivers/cxl/core/pci.c +0 -0
index 5272013548c73..ea5327cd627fc 100644
@@ -209,22 +209,31 @@ static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)

[ ... ]

drivers/cxl/core/pci.c static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val) · line 239

Quoted 9 lines
drivers/cxl/core/pci.c +6 -0
+	/*
+	 * Refresh the PCI-core cache from the live register even when
+	 * MEM_ENABLE already matched: a reset restores the cached value.
+	 */
+	cxl_hdm_cache_set_dvsec_ctrl(pdev, ctrl);
+	return ret;
 }
 
 static void clear_mem_enable(void *cxlds)

[Severity: Medium]
As reported by Sashiko on v16 [1], when the CXL driver unbinds or unwinds probe, can disable_hdm() leave a stale CXL_HDM_DECODER_ENABLE bit set in pdev->hdm->global_ctrl?

When the CXL driver binds and platform firmware did not pre-enable HDM, devm_cxl_endpoint_decoders_setup() runs:

  cxl_hdm_decode_init()
    devm_cxl_enable_hdm()      /* sets CXL_HDM_DECODER_ENABLE in MMIO */
    devm_cxl_enable_mem()
      cxl_set_mem_enable()     /* updates pdev->hdm->dvsec_ctrl */
  devm_cxl_enumerate_decoders()
    cxl_hdm_refresh_decoder()
      cxl_hdm_cache_refresh_decoder()
        info->global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);

which latches CXL_HDM_DECODER_ENABLE into pdev->hdm->global_ctrl.

On driver unbind or probe failure, devres runs clear_mem_enable(), which clears PCI_DVSEC_CXL_MEM_ENABLE in both hardware and pdev->hdm->dvsec_ctrl, and then runs disable_hdm():

  static void disable_hdm(void *_cxlhdm)
  {
          u32 global_ctrl;
          struct cxl_hdm *cxlhdm = _cxlhdm;
          void __iomem *hdm = cxlhdm->regs.hdm_decoder;
          global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
          writel(global_ctrl & ~CXL_HDM_DECODER_ENABLE,
                 hdm + CXL_HDM_DECODER_CTRL_OFFSET);

}

Because disable_hdm() clears CXL_HDM_DECODER_ENABLE in hardware without updating pdev->hdm->global_ctrl, a subsequent reset while unbound will restore CXL_HDM_DECODER_ENABLE in hardware while PCI_DVSEC_CXL_MEM_ENABLE remains disabled, and a later driver re-bind in cxl_hdm_decode_init() will see global_ctrl & CXL_HDM_DECODER_ENABLE set and assume firmware enabled it.

Should disable_hdm() (or devm_cxl_enable_hdm()) also update the cached global_ctrl in pdev->hdm?

drivers/pci/bus.c void pci_bus_add_device(struct pci_dev *dev) · line 362

Quoted 9 lines
drivers/pci/bus.c +1 -0
index 655ed53436d3e..aad567fb7c560 100644
@@ -359,6 +359,7 @@ void pci_bus_add_device(struct pci_dev *dev)
 
 	/* Save config space for error recoverability */
 	pci_save_state(dev);
+	pci_cxl_hdm_cache_init(dev);

[Severity: High]
As reported by Sashiko on v16 [2], does calling pci_cxl_hdm_cache_init() in pci_bus_add_device() run too early during boot and miss upstream bridge enablement?

On x86 ACPI boot, subsys_initcall(acpi_init) calls:

acpi_pci_root_add()
pci_bus_add_devices()
pci_bus_add_device()
pci_cxl_hdm_cache_init()

before subsys_initcall(pci_subsys_init) runs pcibios_resource_survey() and before fs_initcall(pcibios_assign_resources) runs pci_assign_unassigned_resources().

In addition, cxl_pci_bar_assigned() in drivers/pci/cxl.c checks only res->start and res->end without verifying res->parent, and cxl_pci_hdm_read_info() sets PCI_COMMAND_MEMORY only on the endpoint pdev without ensuring upstream PCI-to-PCI bridges have memory decoding enabled.

Can this cause cxl_pci_hdm_read_info() to enable PCI_COMMAND_MEMORY on an unclaimed or conflicting BIOS BAR address before pcibios_resource_survey() validates it, or fail to populate pdev->hdm permanently when BARs or bridge windows are assigned later or upstream bridges do not yet have PCI_COMMAND_MEMORY enabled?

Quoted 6 lines
drivers/pci/cxl.c new file +0 -0
new file mode 100644
index 0000000000000..a0d20f4210a52
@@ -0,0 +1,225 @@

[ ... ]

Quoted 18 lines
drivers/pci/cxl.c new file +18 -0
+static void __iomem *cxl_pci_hdm_map_regs(struct pci_dev *pdev,
+					  struct cxl_register_map *map,
+					  resource_size_t *hdm_offset,
+					  int *decoder_count)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	void __iomem *hdm;
+	int rc;
+
+	/* cxl_setup_regs() populates hdm_map, including its valid bit. */
+	rc = cxl_setup_regs(map);
+	if (rc)
+		return ERR_PTR(rc);
+	if (!hdm_map->valid)
+		return ERR_PTR(-ENODEV);
+	if (hdm_map->offset > map->max_size ||
+	    hdm_map->size > map->max_size - hdm_map->offset)
+		return ERR_PTR(-ENXIO);

drivers/pci/cxl.c line 77

Quoted 10 lines
drivers/pci/cxl.c new file +10 -0
+	if (check_add_overflow(map->bar_offset,
+			       (resource_size_t)hdm_map->offset, hdm_offset))
+		return ERR_PTR(-EOVERFLOW);
+
+	hdm = ioremap(map->resource + hdm_map->offset, hdm_map->size);
+	if (!hdm)
+		return ERR_PTR(-ENOMEM);
+
+	*decoder_count = cxl_hdm_decoder_count_mapped(&pdev->dev, hdm,
+						      hdm_map->size);

[Severity: High]
As reported by Sashiko on v16 [3], can cxl_pci_hdm_map_regs() perform out-of-bounds MMIO reads inside cxl_setup_regs() before the map->max_size bounds check runs, and underflow hdm_map->size when the HDM capability header has an invalid decoder count?

In __pci_cxl_hdm_cache_init(), cxl_find_regblock() populates map via cxl_decode_regblock(), which only checks offset <= pci_resource_len(pdev, bar) and sets map->max_size = pci_resource_len(pdev, bar) - offset.

When cxl_pci_hdm_map_regs() calls cxl_setup_regs(map):

cxl_setup_regs()

    cxl_map_regblock()         /* ioremap(map->resource, map->max_size) */
    cxl_probe_regs()
      cxl_probe_component_regs()

cxl_probe_component_regs() immediately reads from map->base + CXL_CM_OFFSET and map->base + CXL_CM_OFFSET + offset before cxl_pci_hdm_map_regs() checks hdm_map->offset > map->max_size. If map->max_size is smaller than those offsets, the read can fault past the ioremap() window.

Furthermore, in cxl_probe_component_regs():

  case CXL_CM_CAP_CAP_ID_HDM: {
          int decoder_cnt;
          decoder_cnt = cxl_hdm_decoder_count(hdr);
          length = 0x20 * decoder_cnt + 0x10;
          rmap = &map->hdm_decoder;
          break;

}

If hdr contains a reserved decoder count encoding (such as 0xffffffff from a failed MMIO read), cxl_hdm_decoder_count() returns -ENXIO (-6), underflowing u32 length to 0xffffff50 (~4 GiB) while still marking hdm_map->valid = true. If the BAR has at least 4 GiB remaining, cxl_pci_hdm_map_regs() passes hdm_map->size (0xffffff50) to ioremap() before cxl_hdm_decoder_count_mapped() checks the decoder count.

Quoted 30 lines
drivers/pci/cxl.c new file +30 -0
+	if (*decoder_count < 0) {
+		iounmap(hdm);
+		return ERR_PTR(*decoder_count);
+	}
+
+	return hdm;
+}
+
+static struct cxl_hdm_info *__cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						    struct cxl_register_map *map,
+						    int dvsec)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	struct cxl_hdm_info *info;
+	resource_size_t hdm_offset;
+	void __iomem *hdm;
+	int decoder_count;
+	u16 dvsec_ctrl;
+	int rc;
+
+	hdm = cxl_pci_hdm_map_regs(pdev, map, &hdm_offset, &decoder_count);
+	if (IS_ERR(hdm))
+		return ERR_CAST(hdm);
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL,
+				  &dvsec_ctrl);
+	if (rc) {
+		rc = pcibios_err_to_errno(rc);
+		goto out_unmap;
+	}

[ ... ]

Quoted 8 lines
drivers/pci/cxl.c new file +8 -0
+static struct cxl_hdm_info *cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						  struct cxl_register_map *map,
+						  int dvsec)
+{
+	struct cxl_hdm_info *info;
+	u16 command;
+	int rc;
+

drivers/pci/cxl.c line 154

Quoted 10 lines
drivers/pci/cxl.c new file +10 -0
+	rc = pci_read_config_word(pdev, PCI_COMMAND, &command);
+	if (rc)
+		return ERR_PTR(pcibios_err_to_errno(rc));
+
+	if (!(command & PCI_COMMAND_MEMORY)) {
+		rc = pci_write_config_word(pdev, PCI_COMMAND,
+					   command | PCI_COMMAND_MEMORY);
+		if (rc)
+			return ERR_PTR(pcibios_err_to_errno(rc));
+	}

[Severity: High]
Can all-ones config and MMIO error responses (0xffff / 0xffffffff) corrupt the cached state or bypass enabling PCI_COMMAND_MEMORY here?

In cxl_set_mem_enable() and cxl_pci_device_dvsec(), pci_read_config_word() is followed by a PCI_POSSIBLE_ERROR() check because PCI config reads to a non-responding device typically return PCIBIOS_SUCCESSFUL with an all-ones value.

However, in several paths here, all-ones reads are not checked:

1. In __cxl_pci_hdm_read_info(), pci_read_config_word(pdev,
dvsec + PCI_DVSEC_CXL_CTRL, &dvsec_ctrl) does not check PCI_POSSIBLE_ERROR(dvsec_ctrl) before storing info->dvsec_ctrl = dvsec_ctrl and info->dvsec_ctrl_valid = true. Per CXL r4.0 sec 8.1.3.2, bits 15, 13:12, and 6:3 of DVSEC CXL Control are RsvdP, so 0xffff is never valid, and caching it would cause reset recovery to write 0xffff back to PCI_DVSEC_CXL_CTRL.

2. In cxl_pci_hdm_read_info(), pci_read_config_word(pdev, PCI_COMMAND, &command) does not check PCI_POSSIBLE_ERROR(command). Because 0xffff has PCI_COMMAND_MEMORY set, an all-ones read is treated as memory space already being enabled and proceeds directly to MMIO reads.

3. In cxl_hdm_read_state() in drivers/cxl/core/hdm_regs.c:

  info->global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);

global_ctrl is stored without checking for U32_MAX, unlike cxl_hdm_cache_refresh_decoder() in drivers/cxl/core/hdm_state.c which checks global_ctrl != U32_MAX, and settings->skip in cxl_hdm_read_decoder_settings() is not checked for U64_MAX (unlike base and size in cxl_hdm_unpack_decoder()).

Should these reads also reject all-ones values before caching them or using command to gate PCI_COMMAND_MEMORY?

[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]
[3] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#44 lore raw

Re: [PATCH v17 14/19] PCI/CXL: Reject reset with unsafe function scope

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] PCI/CXL: incomplete multifunction check in cxl_reset_function() and cxl_reset_bus_function() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] PCI/CXL: incomplete multifunction check in cxl_reset_function() and cxl_reset_bus_function() --

commit 124136ec84376cd48b0955e35be2be62182793df
Author: Srirangan Madhavan <[email protected]>

PCI/CXL: Reject reset with unsafe function scope

This commit rejects cxl_reset and cxl_bus reset methods for virtual functions, multifunction devices, and physical functions with enabled virtual functions so per-device resets do not reset sibling functions.

Quoted 19 lines
drivers/pci/cxl.c +3 -0
index af8ec8db20f12..c07266ab01336 100644
@@ -501,6 +501,9 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	u16 dvsec, cap, ctrl;
 	int rc;
 
+	if (pdev->is_virtfn || pdev->multifunction || pci_num_vf(pdev))
+		return -ENOTTY;
+
 	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
 	if (rc)
 		return rc;
drivers/pci/pci.c +0 -0
index b2879a6be5f80..aef976d0c850e 100644

drivers/pci/pci.c static int cxl_reset_bus_function(struct pci_dev *dev, bool probe) · line 5026

Quoted 9 lines
drivers/pci/pci.c +6 -0
@@ -5018,6 +5018,13 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	u16 dvsec, reg, val;
 	int rc;
 
+	/*
+	 * Reject VFs and multifunction devices before walking the bridge's
+	 * capabilities: every VF behind the same bridge would repeat the walk.
+	 */
+	if (dev->is_virtfn || dev->multifunction || pci_num_vf(dev))
+		return -ENOTTY;

[Severity: High]
Is checking dev->multifunction sufficient to catch all multifunction CXL devices during reset probing and execution in both cxl_reset_function() and cxl_reset_bus_function()?

During enumeration in drivers/pci/probe.c:pci_scan_slot(), pci_scan_single_device() runs pci_init_reset_methods() before dev->multifunction = 1 is set for non-zero functions:

drivers/pci/probe.c:pci_scan_slot()
pci_scan_single_device(bus, devfn + fn)
pci_device_add()
pci_init_capabilities()
pci_init_reset_methods()
if (fn > 0)

    dev->multifunction = 1;

Since non-zero functions of conventional multifunction devices are not required to set PCI_HEADER_TYPE_MFD in their header type register, and ARI devices must have PCI_HEADER_TYPE_MFD cleared in all functions, any non-zero function with PCI_HEADER_TYPE_MFD == 0 still has dev->multifunction == 0 when pci_init_reset_methods() probes cxl_reset_function() and cxl_reset_bus_function(). As a result, probe does not reject those functions early, walking the bridge capabilities and recording cxl_reset and cxl_bus in dev->reset_methods[].

Furthermore, for Function 0 of an ARI multifunction device, PCI_HEADER_TYPE_MFD is 0 by specification and pci_scan_slot() only sets dev->multifunction = 1 when fn > 0, leaving Function 0 with dev->multifunction == 0 even after sibling functions are enumerated. Would resetting Function 0 of an ARI multifunction CXL device via cxl_reset_function() (or via cxl_reset_bus_function() when the slot reset path is used) bypass this check and reset active sibling functions?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#46 lore raw

Re: [PATCH v17 15/19] PCI/CXL: Restore CXL state after PCI reset

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] PCI/CXL: cxl_reset_quiesced() skips disabling device if cache restore fails --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] PCI/CXL: cxl_reset_quiesced() skips disabling device if cache restore fails --

commit 0833e3bda8d31d8ddf0c1310990a9ee4b81a1760
Author: Srirangan Madhavan <[email protected]>

PCI/CXL: Restore CXL state after PCI reset

This commit restores PCI configuration, cached HDM decoder settings, and CXL Device DVSEC control state after a CXL device reset. If any restoration step fails, it disables the device and updates the saved PCI command state so the outer PCI reset flow does not re-enable memory decoding or bus mastering.

Quoted 4 lines
drivers/pci/cxl.c +0 -0
index c07266ab01336..77d0e30841d9f 100644

[ ... ]

Quoted 42 lines
drivers/pci/cxl.c +11 -2
@@ -415,7 +572,9 @@ static int cxl_clear_memory(struct pci_dev *pdev, int dvsec, bool initiate)
 }
 
 static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap,
-			      struct cxl_hdm_quiesce *q)
+			      const struct cxl_hdm_info *snapshot,
+			      struct cxl_hdm_quiesce *q,
+			      u16 *command)
 	__must_hold(cxl_region_quiesce)
 {
 	int rc, rc2;
@@ -441,10 +600,15 @@ static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap,
 		pci_err(pdev, "failed to clear CXL Reset Memory Clear: %d\n", rc2);
 	rc = rc ?: rc2;
 
+	if (!rc)
+		rc = pci_cxl_restore_state(pdev, snapshot, command);
+
 	rc2 = cxl_hdm_quiesce_flush(q);
 	if (rc2)
 		pci_err(pdev, "failed to invalidate CPU cache after CXL reset: %d\n", rc2);
 	rc = rc ?: rc2;
+	if (rc)
+		cxl_reset_save_disabled_state(pdev);
 
 	pci_dev_reset_iommu_done(pdev);
 	return rc;
@@ -455,6 +619,7 @@ static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
 {
 	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
 	struct cxl_pci_cache cache = {};
+	u16 command;
 	int rc, rc2;
 
 	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2,
@@ -478,11 +643,19 @@ static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
 		return rc;
 	}
 	if (!rc)
-		rc = __cxl_reset_execute(pdev, dvsec, cap, &cache.quiesce);
+		rc = __cxl_reset_execute(pdev, dvsec, cap, snapshot, &cache.quiesce,
+					 &command);

drivers/pci/cxl.c static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap) · line 656

Quoted 10 lines
drivers/pci/cxl.c +6 -1
 	/* Restore cache policy after any attempt to disable caching. */
 	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
 	cxl_hdm_quiesce_destroy(&cache.quiesce);
-	return rc ?: rc2;
+	if (rc)
+		return rc;
+	if (rc2) {
+		cxl_reset_save_disabled_state(pdev);
+		return rc2;
+	}

[Severity: Medium]
In drivers/pci/cxl.c:cxl_reset_quiesced(), can returning early on if (rc) before checking if (rc2) skip calling cxl_reset_save_disabled_state(pdev) when restoring the CXL cache policy also fails?

Specifically, rc can be non-zero before cxl_reset_save_disabled_state(pdev) is reached in two cases after CXL caching has been disabled:

1. cxl_reset_cache_prepare() sets cache.cache_disabled = true and disables caching via cxl_reset_disable_cache(), but cxl_reset_wait_cache_wbi() then fails.

2. cxl_reset_cache_prepare() succeeds, and __cxl_reset_execute() returns early from pci_wait_for_pending_transaction() or pci_dev_reset_iommu_prepare() before reaching cxl_reset_save_disabled_state(pdev) at the end of __cxl_reset_execute():

drivers/pci/cxl.c:__cxl_reset_execute() {
	if (!pci_wait_for_pending_transaction(pdev)) {
		pci_err(pdev, "timed out waiting for pending transactions\n");
		return -ETIMEDOUT;
	}

	rc = pci_dev_reset_iommu_prepare(pdev);
	if (rc) {
		pci_err(pdev, "failed to stop IOMMU for CXL reset: %d\n", rc);
		return rc;
	}
	...
}

In either case, pdev->saved_config_space[PCI_COMMAND / 4] still holds the pre-reset MSE and BME bits. If cxl_reset_restore_cache_policy() then fails (rc2 != 0), checking if (rc) first returns without calling cxl_reset_save_disabled_state(pdev), allowing the outer PCI reset path to re-enable memory decoding and bus mastering on a device whose CXL cache policy in PCI_DVSEC_CXL_CTRL2 was not restored.

Should the if (rc2) check call cxl_reset_save_disabled_state(pdev) before returning rc?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#48 lore raw

Re: [PATCH v17 16/19] PCI/CXL: Expose CXL Reset as a PCI reset method

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

Register cxl_reset with the PCI reset-method interface and place it before FLR, which does not reset CXL.cache or CXL.mem protocol state.

Return -ENOTTY when device capabilities, function scope, cached HDM state, or required cache synchronization do not permit a safe reset.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#57 lore raw

Re: [PATCH v17 19/19] cxl: Add KUnit checks for HDM decoder unpacking

In reply to Srirangan Madhavan
Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

Test cxl_hdm_unpack_decoder() without a PCI device or HDM MMIO. Cover range boundaries and overflow, an all-ones base, zero-size and uncommitted decoders, and a locked host-only decoder with 12-way interleave.

Run the checks as a KUnit suite rather than during cxl_test module loading, so a failure does not prevent unrelated CXL mock tests from running. An uncommitted decoder has no meaningful target type, so do not check it.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
#52 lore raw

Re: [PATCH v17 17/19] PCI/CXL: Restore CXL state after CXL bus reset

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] PCI: __free(kfree) variable declared as NULL in cxl_reset_bus_function() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] PCI: __free(kfree) variable declared as NULL in cxl_reset_bus_function() --

commit 293a1729e6b1792018354518fc69bc55b2adb408
Author: Srirangan Madhavan <[email protected]>

PCI/CXL: Restore CXL state after CXL bus reset

This commit restores cached HDM decoder programming and CXL Device DVSEC control state after a CXL bus reset, refreshing decoder settings under region quiesce and re-enabling bus mastering only after IOMMU translation is restored.

Quoted 16 lines
drivers/pci/pci.c +2 -0
index 426b5ee38d04f..1d4ba90a69762 100644
@@ -5014,8 +5014,10 @@ static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
 
 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 {
+	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
 	struct pci_dev *bridge;
 	u16 dvsec, reg, val;
+	u16 command;
 	int rc;
 
 	/*

drivers/pci/pci.c static int cxl_reset_bus_function(struct pci_dev *dev, bool probe) · line 5047

Quoted 6 lines
drivers/pci/pci.c +3 -0
@@ -5040,6 +5042,10 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	if (rc)
 		return -ENOTTY;
 
+	snapshot = pci_cxl_reset_prepare(dev);
+	if (IS_ERR(snapshot))
+		return PTR_ERR(snapshot);

[Severity: Low]
This isn't a bug, but in cxl_reset_bus_function(), snapshot is declared with __free(kfree) = NULL at the top of the function and only assigned after the early return paths:

	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
	...
	snapshot = pci_cxl_reset_prepare(dev);

Following the cleanup helper conventions in include/linux/cleanup.h, could snapshot be defined and initialized in a single statement where pci_cxl_reset_prepare() is called?

	struct cxl_hdm_info *snapshot __free(kfree) =
		pci_cxl_reset_prepare(dev);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#40 lore raw

Re: [PATCH v17 13/19] cxl: Validate and synchronize HDM ranges around reset

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] cxl: missed or cleared CXL_DECODER_F_NORMALIZED_ADDRESSING in HDM cache - [High] PCI/CXL…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] cxl: missed or cleared CXL_DECODER_F_NORMALIZED_ADDRESSING in HDM cache
- [High] PCI/CXL: cxl_reset_function() returns -ENOTTY on !probe safety check failures
- [High] cxl: stale global_ctrl cache and unserialized check in cxl_reset_function()
- [Low] PCI/CXL: split declaration and assignment of __free() in cxl_reset_quiesced() --

commit 5c4d959ed1ab8877ba7835557e27e40030bf5a45
Author: Srirangan Madhavan <[email protected]>

cxl: Validate and synchronize HDM ranges around reset

This commit validates and reserves enabled system-physical HDM ranges around CXL reset, invalidating CPU caches before reset and again before ending IOMMU exclusion while holding the global cxl_rwsem.region write lock. It also rejects normalized-addressing and DVSEC-decoded memory configurations and records Normalized Addressing in the HDM cache during region discovery.

Quoted 4 lines
drivers/cxl/core/hdm_state.c +0 -0
index 9def4a7439c93..51df56377f7a9 100644

[ ... ]

Quoted 7 lines
drivers/cxl/core/hdm_state.c +7 -0
+/**
+ * cxl_hdm_cache_dvsec_decode() - check for memory decoded by DVSEC ranges
+ * @slot: cache pointer owned by the device
+ *
+ * Return: true if the published state shows CXL.mem enabled while HDM
+ * decoders are globally disabled, so that the device decodes memory through
+ * its DVSEC ranges, which the cache does not describe.

drivers/cxl/core/hdm_state.c void cxl_hdm_cache_release(struct cxl_hdm_info **slot) · line 153

Quoted 10 lines
drivers/cxl/core/hdm_state.c +10 -0
+ */
+bool cxl_hdm_cache_dvsec_decode(struct cxl_hdm_info *const *slot)
+{
+	struct cxl_hdm_info *info;
+
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	info = *slot;
+	return info && (info->dvsec_ctrl & PCI_DVSEC_CXL_MEM_ENABLE) &&
+	       !(info->global_ctrl & CXL_HDM_DECODER_ENABLE);
+}

[Severity: High]
As reported by Sashiko on v16 [1], can info->global_ctrl become out of sync with hardware across devm_cxl_enable_hdm() and disable_hdm(), and can checking cxl_hdm_cache_dvsec_decode() outside cxl_region_quiesce_lock() race with concurrent endpoint probe or unbind?

In drivers/cxl/core/pci.c, neither devm_cxl_enable_hdm() nor its devres teardown callback disable_hdm() updates pdev->hdm->global_ctrl:

drivers/cxl/core/pci.c:disable_hdm() {
	...
	global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
	writel(global_ctrl & ~CXL_HDM_DECODER_ENABLE,
	       hdm + CXL_HDM_DECODER_CTRL_OFFSET);
}

During cxl_endpoint_port_probe(), when firmware left PCI_DVSEC_CXL_MEM_ENABLE clear at boot, cxl_hdm_decode_init() calls devm_cxl_enable_hdm() (setting CXL_HDM_DECODER_ENABLE in MMIO without updating pdev->hdm->global_ctrl) and then devm_cxl_enable_mem() (setting PCI_DVSEC_CXL_MEM_ENABLE in pdev->hdm->dvsec_ctrl). Next, devm_cxl_enumerate_decoders() calls cxl_settle_decoders(), which sleeps for 20 ms before cxl_hdm_refresh_decoder() refreshes pdev->hdm->global_ctrl. Throughout that 20 ms window, pdev->hdm has PCI_DVSEC_CXL_MEM_ENABLE set in dvsec_ctrl and CXL_HDM_DECODER_ENABLE clear in global_ctrl, so cxl_hdm_cache_dvsec_decode() falsely reports DVSEC range decode mode.

Conversely, when the endpoint port or CXL driver unbinds, devres runs clear_mem_enable() followed by disable_hdm(), which clears CXL_HDM_DECODER_ENABLE in CXL_HDM_DECODER_CTRL_OFFSET without updating pdev->hdm->global_ctrl. When a subsequent reset restores state from pdev->hdm (in the later commits "PCI/CXL: Restore CXL state after PCI reset" and "PCI/CXL: Flush host and device caches for CXL bus reset"), cxl_hdm_restore_state() will write the stale snapshot->global_ctrl with CXL_HDM_DECODER_ENABLE set back into hardware.

Additionally, cxl_reset_function() evaluates cxl_hdm_cache_dvsec_decode(&pdev->hdm) in a standalone cxl_rwsem.dpa read section before cxl_reset_execute() acquires cxl_region_quiesce_lock() and calls cxl_hdm_cache_snapshot(&pdev->hdm) in cxl_reset_quiesced(), while cxl_hdm_quiesce_prepare() never checks the captured snapshot for DVSEC decode. Because endpoint port probe and unbind run under device_lock(&port->dev) rather than device_lock(&pdev->dev) and modify PCI_DVSEC_CXL_CTRL, CXL_HDM_DECODER_CTRL_OFFSET, and pdev->hdm without holding cxl_rwsem.region, can the cached state change between cxl_hdm_cache_dvsec_decode() and cxl_hdm_cache_snapshot()?

Quoted 10 lines
drivers/cxl/core/region.c +2 -0
index 8cfc06df31340..b06dd9b901f0c 100644
@@ -3840,6 +3841,19 @@ int cxl_add_to_region(struct cxl_endpoint_decoder *cxled)
 	if (IS_ERR(cxlrd))
 		return PTR_ERR(cxlrd);
 
+	/*
+	 * Translation setup may have marked the decoder as Normalized

drivers/cxl/core/region.c int cxl_add_to_region(struct cxl_endpoint_decoder *cxled) · line 3855

Quoted 10 lines
drivers/cxl/core/region.c +10 -0
+	 * Addressing, after the PCI cache was filled. Record it for reset.
+	 */
+	if (cxled->cxld.config.flags & CXL_DECODER_F_NORMALIZED_ADDRESSING) {
+		struct pci_dev *pdev __free(pci_dev_put) =
+			cxl_port_get_uport_pci_dev(cxled_to_port(cxled));
+
+		if (pdev)
+			cxl_hdm_cache_set_normalized(pdev,
+						     cxled->cxld.config.id);
+	}

[Severity: High]
As reported by Sashiko on v16 [1], can CXL_DECODER_F_NORMALIZED_ADDRESSING still be missed or cleared in pdev->hdm, causing cxl_hdm_ranges_collect() to treat a device-local normalized address range as a system physical address range during reset?

There appear to be two paths where the cached decoder loses this flag:

1. In cxl_add_to_region(), get_cxl_root_decoder(cxled, &ctx) runs before the check above. Inside get_cxl_root_decoder():

drivers/cxl/core/region.c:get_cxl_root_decoder() {
	...
	rc = cxl_root_setup_translation(cxl_root, ctx);
	if (rc) {
		...
		return ERR_PTR(rc);
	}

	cxlrd_dev = device_find_child(&cxl_root->port.dev, &ctx->hpa_range,
				      match_root_decoder);
	if (!cxlrd_dev) {
		...
		return ERR_PTR(-ENXIO);
	}
}

cxl_root_setup_translation() -> cxl_prm_setup_root() sets CXL_DECODER_F_NORMALIZED_ADDRESSING on cxled->cxld.config.flags before device_find_child(..., match_root_decoder) runs. If no root decoder window matches (!cxlrd_dev), get_cxl_root_decoder() returns ERR_PTR(-ENXIO). (Similarly, if cxl_prm_setup_root() detects Normalized Addressing via hpa_range.start == cxled->dpa_res->start but fails translation before setting the flag, get_cxl_root_decoder() returns ERR_PTR(-ENXIO).) Because discover_region() treats errors from cxl_add_to_region() as non-fatal and cxl_add_to_region() returns early on IS_ERR(cxlrd), cxl_hdm_cache_set_normalized() is never called.

2. In devm_cxl_enumerate_decoders() -> init_hdm_decoder() -> cxl_hdm_refresh_decoder() -> cxl_hdm_cache_refresh_decoder():

drivers/cxl/core/hdm_state.c:cxl_hdm_cache_refresh_decoder() {
	...
	*settings = (struct cxl_endpoint_decoder_settings) {
		.config.id = id,
	};
	if (cxld->config.flags & CXL_DECODER_F_ENABLE) {
		settings->config = cxld->config;
		settings->skip = cxled->skip;
	}
}

Because hardware registers do not have a Normalized Addressing bit, overwriting settings->config from cxld->config clears any previously recorded CXL_DECODER_F_NORMALIZED_ADDRESSING bit when the endpoint port driver is rebound or if enumeration fails on a later decoder before discover_region() runs.

If a CXL reset then runs, will cxl_hdm_ranges_collect() fail to reject the decoder with -EOPNOTSUPP and pass the untranslated normalized DPA range to request_mem_region() and cpu_cache_invalidate_memregion()?

Quoted 4 lines
drivers/pci/cxl.c +0 -0
index 9ac5948f595b1..af8ec8db20f12 100644

[ ... ]

Quoted 10 lines
drivers/pci/cxl.c +4 -3
-static int cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
+	__must_hold(cxl_region_quiesce)
 {
-	u16 saved_ctrl2;
+	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
+	struct cxl_pci_cache cache = {};
 	int rc, rc2;
 
-	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &saved_ctrl2);

drivers/pci/cxl.c static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap) · line 467

Quoted 10 lines
drivers/pci/cxl.c +4 -2
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2,
+				  &cache.saved_ctrl2);
 	if (rc)
 		return pcibios_err_to_errno(rc);
-	if (PCI_POSSIBLE_ERROR(saved_ctrl2))
+	if (PCI_POSSIBLE_ERROR(cache.saved_ctrl2))
 		return -ENODEV;
 
-	rc = cxl_reset_disable_cache(pdev, dvsec, cap);
+	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);

[Severity: Low]
This isn't a bug, but per the Cleanup API conventions, should snapshot be defined and initialized in a single statement at its point of assignment:

	struct cxl_hdm_info *snapshot __free(kfree) =
		cxl_hdm_cache_snapshot(&pdev->hdm);

rather than being declared with = NULL at the top of cxl_reset_quiesced()?

[ ... ]

Quoted 8 lines
drivers/pci/cxl.c +4 -0
@@ -463,5 +522,17 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	if (probe)
 		return 0;
 
+	/* The cache is owned by @pdev and does not require a bound CXL driver. */
+	if (!pdev->hdm)
+		return -ENOTTY;
+

drivers/pci/cxl.c int cxl_reset_function(struct pci_dev *pdev, bool probe) · line 538

Quoted 10 lines
drivers/pci/cxl.c +8 -0
+	/* Memory decoded through DVSEC ranges has no HPA ranges to quiesce. */
+	if (cxl_hdm_cache_dvsec_decode(&pdev->hdm))
+		return -ENOTTY;
+
+	if (!cpu_cache_has_invalidate_memregion() &&
+	    !IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST))
+		return -ENOTTY;
+
 	return cxl_reset_execute(pdev, dvsec, cap);
 }

[Severity: High]
When probe is false and CXL.cache and CXL.mem are enabled on the device, does returning -ENOTTY from these precondition checks cause __pci_reset_function_locked() to fall back to other PCI reset methods (such as FLR or PM reset) instead of refusing the reset?

During PCI enumeration, pci_init_reset_methods() calls cxl_reset_function() with probe == true, which returns 0 before reaching these checks and records cxl_reset in dev->reset_methods[] ahead of flr and pm (when wired up by commit "PCI/CXL: Expose CXL Reset as a PCI reset method"). Later, when __pci_reset_function_locked() runs with PCI_RESET_DO_RESET:

drivers/pci/pci.c:__pci_reset_function_locked() {
	...
	rc = method->reset_fn(dev, PCI_RESET_DO_RESET);
	if (!rc)
		return 0;

	pci_dbg(dev, "%s failed with %d\n", method->name, rc);
	if (rc != -ENOTTY)
		return rc;
}

Because -ENOTTY tells __pci_reset_function_locked() to try the next reset method in dev->reset_methods[], failing any of these checks will proceed to reset the active CXL.cache / CXL.mem function via FLR or PM reset without reserving HPA ranges, flushing CPU or device caches, or restoring CXL state.

Returning -ENOTTY here also makes the locked -ENXIO checks and pci_err() diagnostics in cxl_hdm_cache_snapshot(), cxl_hdm_quiesce_prepare(), and cxl_reset_quiesced() unreachable from cxl_reset_function(), while checking !pdev->hdm without holding cxl_rwsem.dpa. Should these checks run under cxl_region_quiesce_lock() and return non-ENOTTY errors (such as -ENXIO and -EOPNOTSUPP, matching cxl_hdm_quiesce_prepare() and pci_cxl_reset_prepare() in commit "PCI/CXL: Flush host and device caches for CXL bus reset") so the reset is aborted?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#55 lore raw

Re: [PATCH v17 18/19] PCI/CXL: Flush host and device caches for CXL bus reset

In reply to Srirangan Madhavan
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [High] PCI/CXL: cxl_restore_state_after_pci_reset() enables cache before flush - [Medium] PCI/CXL…

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [High] PCI/CXL: cxl_restore_state_after_pci_reset() enables cache before flush
- [Medium] PCI/CXL: cxl_reset_quiesced() restores caching and skips disable on error
- [Medium] PCI/CXL: cxl_reset_bus_function() disables device on pre-reset -ENOTTY
- [Medium] PCI/CXL: TOCTOU race on snapshot in pci_cxl_reset_prepare()
- [Low] PCI/CXL: missing cxl_region_quiesce context annotations on reset helpers
- [Low] cxl: unused cxl_hdm_cache_copy_decoders() after bus reset quiesce change --

commit 6351634e948c8a95d981c82600454247642192c2
Author: Srirangan Madhavan <[email protected]>

PCI/CXL: Flush host and device caches for CXL bus reset

This commit adds host and device cache flushing, HPA range reservation, and CXL region quiesce locking around CXL bus resets when cached HDM state is present. It also preserves and restores the device cache policy across the reset and leaves the device disabled if recovery fails after an attempted reset.

Quoted 13 lines
drivers/pci/cxl.c +5 -0
index a9aa2e1c631d1..c5cdad4b05906 100644
@@ -393,74 +393,174 @@ static int pci_cxl_restore_state(struct pci_dev *pdev,
 	return cxl_restore_state(pdev, snapshot);
 }
 
+static int cxl_reset_restore_cache_policy(struct pci_dev *pdev, int dvsec,
+					  u16 saved_ctrl2);
+static int cxl_reset_cache_prepare(struct pci_dev *pdev, int dvsec, u16 cap,
+				   const struct cxl_hdm_info *snapshot,
+				   struct cxl_pci_cache *cache);

[ ... ]

Quoted 34 lines
drivers/pci/cxl.c +19 -4
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev,
+					struct cxl_pci_cache **cachep)
 {
 	struct cxl_hdm_info *snapshot;
+	struct cxl_pci_cache *cache;
+	u16 dvsec, cap, command;
+	int rc;
 
 	device_lock_assert(&pdev->dev);
-	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
-	if (IS_ERR(snapshot))
-		return PTR_ERR(snapshot) == -ENXIO ? NULL : snapshot;
+	*cachep = NULL;
+	if (!pdev->hdm)
+		return NULL;
 
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc == -ENOTTY)
+		return ERR_PTR(-ENODEV);
+	if (rc)
+		return ERR_PTR(rc);
 	/* Raw reset callers may not have saved the PCI state needed for restore. */
 	if (!pdev->state_saved) {
 		pci_err(pdev, "CXL bus reset requires saved PCI state\n");
-		kfree(snapshot);
 		return ERR_PTR(-EINVAL);
 	}
 
+	cache = kzalloc_obj(*cache);
+	if (!cache)
+		return ERR_PTR(-ENOMEM);
+	cxl_region_quiesce_lock();
+	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
+	if (IS_ERR(snapshot)) {

drivers/pci/cxl.c static int pci_cxl_restore_state(struct pci_dev *pdev, · line 459

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+		rc = PTR_ERR(snapshot);
+		goto unlock;
+	}
+	if (!snapshot->dvsec_ctrl_valid) {
+		rc = -ENXIO;
+		goto free_snapshot;
+	}
+	if (cxl_hdm_cache_dvsec_decode(&pdev->hdm) ||
+	    (snapshot->dvsec_ctrl & PCI_DVSEC_CXL_CACHE_ENABLE &&
+	     !(cap & PCI_DVSEC_CXL_CACHE_WBI_CAPABLE))) {

[Severity: Medium]
In drivers/pci/cxl.c, pci_cxl_reset_prepare() calls cxl_hdm_cache_snapshot(&pdev->hdm) under a cxl_rwsem.dpa read lock to copy dvsec_ctrl and global_ctrl into snapshot, and then calls cxl_hdm_cache_dvsec_decode(&pdev->hdm) in a separate cxl_rwsem.dpa read section on the live pdev->hdm pointer rather than checking snapshot.

Meanwhile, endpoint port probe and teardown on &port->dev run under device_lock(&port->dev) without holding device_lock(&pdev->dev) or cxl_rwsem.region:

clear_mem_enable()

    -> cxl_set_mem_enable()
      -> cxl_hdm_cache_set_dvsec_ctrl()

and

devm_cxl_enumerate_decoders()

    -> cxl_hdm_refresh_decoder()
      -> cxl_hdm_cache_refresh_decoder()

both mutate pdev->hdm->dvsec_ctrl and pdev->hdm->global_ctrl under the cxl_rwsem.dpa write lock.

If clear_mem_enable() clears PCI_DVSEC_CXL_MEM_ENABLE in pdev->hdm->dvsec_ctrl (or cxl_hdm_cache_refresh_decoder() sets CXL_HDM_DECODER_ENABLE in pdev->hdm->global_ctrl) between cxl_hdm_cache_snapshot() and cxl_hdm_cache_dvsec_decode(), wouldn't cxl_hdm_cache_dvsec_decode(&pdev->hdm) return false even though snapshot captured PCI_DVSEC_CXL_MEM_ENABLE set with CXL_HDM_DECODER_ENABLE clear, allowing the reset to proceed and later write stale snapshot->global_ctrl and snapshot->dvsec_ctrl back to hardware in cxl_restore_state()?

Should this check evaluate snapshot->dvsec_ctrl and snapshot->global_ctrl directly instead of re-reading pdev->hdm?

Quoted 3 lines
drivers/pci/cxl.c +3 -0
+		rc = -EOPNOTSUPP;
+		goto free_snapshot;
+	}

[ ... ]

Quoted 7 lines

int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,

drivers/pci/cxl.c +3 -2
-				      struct cxl_hdm_info *snapshot,
-				      u16 *command)
+				      const struct cxl_hdm_info *snapshot,
+				      struct cxl_pci_cache *cache,
+				      bool reset_attempted, int rc, u16 *command)
 {

drivers/pci/cxl.c static int pci_cxl_restore_state(struct pci_dev *pdev, · line 457

Quoted 10 lines
drivers/pci/cxl.c +4 -4
-	int rc;
+	int rc2, policy_rc = 0;
 
+	*command = 0;
+	if (!cache)
+		return rc;
 	device_lock_assert(&pdev->dev);
-	cxl_region_quiesce_lock();
-
-	rc = cxl_hdm_cache_copy_decoders(&pdev->hdm, snapshot);

[Severity: Low]
Removing this call in cxl_restore_state_after_pci_reset() in drivers/pci/cxl.c removes the only caller of cxl_hdm_cache_copy_decoders() in the tree. Should the definition of cxl_hdm_cache_copy_decoders() in drivers/cxl/core/hdm_state.c and its declaration in include/cxl/hdm.h also be removed so dead code is not left behind?

Quoted 4 lines
drivers/pci/cxl.c +1 -2
-	if (!rc)
+	if (reset_attempted && !rc)
 		rc = pci_cxl_restore_state(pdev, snapshot, command);
-	if (rc)

drivers/pci/cxl.c static int pci_cxl_restore_state(struct pci_dev *pdev, · line 549

Quoted 10 lines
drivers/pci/cxl.c +8 -1
-		cxl_reset_save_disabled_state(pdev);
 
+	/* Complete host invalidation before ending IOMMU exclusion. */
+	rc2 = cxl_hdm_quiesce_flush(&cache->quiesce);
+	if (rc2)
+		pci_err(pdev, "failed to invalidate CPU cache after CXL bus reset: %d\n", rc2);
+	/* Undo preparation on abort; enable caching after reset only if safe. */
+	if (cache->cache_disabled && (!reset_attempted || (!rc && !rc2)))
+		policy_rc = cxl_reset_restore_cache_policy(pdev, snapshot->dvsec,
+							  cache->saved_ctrl2);

[Severity: High]
During a Secondary Bus Reset (Hot Reset), the non-sticky Disable_Caching bit (PCI_DVSEC_CXL_DISABLE_CACHING) in PCI_DVSEC_CXL_CTRL2 is reset to 0 by hardware along with PCI_DVSEC_CXL_CTRL.

In cxl_restore_state_after_pci_reset() in drivers/pci/cxl.c, when reset_attempted is true and rc is 0, pci_cxl_restore_state() calls cxl_restore_state() -> cxl_restore_dvsec_ctrl(), which writes snapshot->dvsec_ctrl (including PCI_DVSEC_CXL_CACHE_ENABLE and PCI_DVSEC_CXL_MEM_ENABLE) to PCI_DVSEC_CXL_CTRL before cxl_hdm_quiesce_flush() and cxl_reset_restore_cache_policy() run.

Because PCI_DVSEC_CXL_DISABLE_CACHING was cleared to 0 by the bus reset, doesn't writing snapshot->dvsec_ctrl inside pci_cxl_restore_state() immediately enable device caching before cxl_hdm_quiesce_flush() has invalidated the host CPU caches, transiently enable caching even when cache->saved_ctrl2 originally had PCI_DVSEC_CXL_DISABLE_CACHING set, and leave CXL.cache and CXL.mem enabled in hardware if cxl_hdm_quiesce_flush() fails (since cxl_reset_save_disabled_state() only clears MSE and BME in PCI_COMMAND)?

Quoted 6 lines
drivers/pci/cxl.c +6 -0
+	if (reset_attempted) {
+		rc = rc ?: rc2 ?: policy_rc;
+		if (rc)
+			cxl_reset_save_disabled_state(pdev);
+	} else {
+		/* An aborted reset alone must not poison the saved PCI command. */

drivers/pci/cxl.c static int pci_cxl_restore_state(struct pci_dev *pdev, · line 565

Quoted 10 lines
drivers/pci/cxl.c +7 -0
+		if (rc2 || policy_rc)
+			cxl_reset_save_disabled_state(pdev);
+		rc = rc ?: rc2 ?: policy_rc;
+	}
+
+	cxl_hdm_quiesce_destroy(&cache->quiesce);
 	cxl_region_quiesce_unlock();
+	kfree(cache);
 	return rc;
 }

[Severity: Low]
In include/cxl/hdm.h, cxl_region_quiesce is declared with token_context_lock(cxl_region_quiesce), and cxl_region_quiesce_lock(), cxl_region_quiesce_unlock(), cxl_hdm_quiesce_prepare(), cxl_hdm_quiesce_flush(), pci_cxl_restore_state(), and the definition of cxl_reset_cache_prepare() carry __acquires, __releases, or __must_hold annotations for cxl_region_quiesce.

In drivers/pci/cxl.c:
1. The new forward declaration of cxl_reset_cache_prepare() omits the __must_hold(cxl_region_quiesce) annotation present on its definition.
2. pci_cxl_reset_prepare() calls cxl_region_quiesce_lock() and returns with cxl_region_quiesce held on its non-NULL success path (or releases it via cxl_restore_state_after_pci_reset() on the finish path) without context annotations.
3. cxl_restore_state_after_pci_reset() calls the __must_hold functions pci_cxl_restore_state() and cxl_hdm_quiesce_flush() as well as cxl_region_quiesce_unlock() when cache is non-NULL without context annotations.

When building with Clang static context analysis enabled (CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y), won't these missing annotations trigger -Wthread-safety warnings in drivers/pci/cxl.c?

[ ... ]

drivers/pci/cxl.c static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap) · line 839

Quoted 11 lines
drivers/pci/cxl.c +3 -1
@@ -731,7 +831,9 @@ static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
 		rc = __cxl_reset_execute(pdev, dvsec, cap, snapshot, &cache.quiesce,
 					 &command);
 	/* Restore cache policy after any attempt to disable caching. */
-	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
+	rc2 = 0;
+	if (cache.cache_disabled)
+		rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
 	cxl_hdm_quiesce_destroy(&cache.quiesce);
 	if (rc)
 		return rc;

[Severity: Medium]
In cxl_restore_state_after_pci_reset() in drivers/pci/cxl.c, cxl_reset_restore_cache_policy() is guarded with (!reset_attempted || (!rc && !rc2)) so caching is not re-enabled when an attempted reset, HDM restoration, or post-reset cache flush fails, and on an aborted reset cxl_reset_save_disabled_state() is called if cxl_reset_restore_cache_policy() fails.

In cxl_reset_quiesced() in drivers/pci/cxl.c, however:
1. If __cxl_reset_execute() fails during CXL Reset, pci_cxl_restore_state(), or cxl_hdm_quiesce_flush(), cxl_reset_quiesced() still unconditionally calls cxl_reset_restore_cache_policy() whenever cache.cache_disabled is true, re-enabling caching in PCI_DVSEC_CXL_CTRL2 against unrestored HDM state after pci_dev_reset_iommu_done() has already ended IOMMU exclusion.
2. Because if (rc) return rc; runs before checking rc2:

	if (rc)
		return rc;
	if (rc2) {
		cxl_reset_save_disabled_state(pdev);
		return rc2;
	}

if cxl_reset_cache_prepare() fails after setting cache.cache_disabled = true (or __cxl_reset_execute() fails in pci_wait_for_pending_transaction() or pci_dev_reset_iommu_prepare() before reaching cxl_reset_save_disabled_state()) and cxl_reset_restore_cache_policy() also fails (rc2 != 0), cxl_reset_quiesced() returns rc without calling cxl_reset_save_disabled_state(pdev).

Should cxl_reset_quiesced() follow the same error-handling rules as cxl_restore_state_after_pci_reset() for restoring the cache policy and saving the disabled state?

Quoted 4 lines
drivers/pci/pci.c +0 -0
index 1d4ba90a69762..b29a6a43249dd 100644

[ ... ]

drivers/pci/pci.c static int cxl_reset_bus_function(struct pci_dev *dev, bool probe) · line 5073

Quoted 9 lines
drivers/pci/pci.c +3 -2
@@ -5066,8 +5068,9 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
 				      reg);
 
-	if (!rc && snapshot)
-		rc = cxl_restore_state_after_pci_reset(dev, snapshot, &command);
+	/* Reset-helper failure does not prove that no hardware reset occurred. */
+	rc = cxl_restore_state_after_pci_reset(dev, snapshot, cache, true, rc,
+					       &command);

[Severity: Medium]
In cxl_reset_bus_function() in drivers/pci/pci.c, when probe is true, the function only checks for VFs/multifunction, pci_upstream_bridge(dev), and cxl_port_dvsec(bridge) without probing pci_dev_reset_slot_function() or pci_parent_bus_reset().

When cxl_reset_bus_function(dev, false) runs on a CXL device with cached HDM state, pci_cxl_reset_prepare() disables device caching in PCI_DVSEC_CXL_CTRL2, and then pci_reset_bus_function(dev, false) is called. If pci_reset_bus_function(dev, false) returns -ENOTTY from its prerequisite checks without touching hardware (for example, when cxl_sbr_masked(bridge) remains true because PCI_DVSEC_CXL_PORT_CTL_UNMASK_SBR is read-only, or when both pci_dev_reset_slot_function() and pci_parent_bus_reset() return -ENOTTY because PCI_DEV_FLAGS_NO_BUS_RESET is set, dev->subordinate is non-NULL, or another device shares dev->bus->devices), cxl_reset_bus_function() still passes reset_attempted = true and rc = -ENOTTY to cxl_restore_state_after_pci_reset().

When reset_attempted is true and rc is non-zero, cxl_restore_state_after_pci_reset() skips cxl_reset_restore_cache_policy() and calls cxl_reset_save_disabled_state(dev), which leaves PCI_DVSEC_CXL_DISABLE_CACHING set and clears MSE and BME in dev->saved_config_space.

Should cxl_reset_bus_function() verify that slot or parent bus reset is supported before preparing the reset (or treat -ENOTTY from pci_reset_bus_function() as an unattempted reset) so an unsupported bus reset does not disable an untouched device?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
reviewer Reviewed-by on v17 2/19
#5 lore raw

Re: [PATCH v17 02/19] cxl: Share CXL port upstream PCI device lookup

In reply to Srirangan Madhavan
Quoted 15 lines · Srirangan Madhavan

read_cdat_data() resolves a CXL port's upstream device to its backing PCI device. HDM cache updates need the same mapping.

Factor the lookup into cxl_port_get_uport_pci_dev() and return a referenced PCI device to make caller ownership explicit.

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

Quoted 6 lines

---
Changes in v17:
- Use an explicit pci_dev_put() on a single exit path in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=2

I still think the new goto makes the code harder to follow. But I saw your discussion in v13[1], both Jonathan and Dave agree with your current changes. I post my proposal here which can eliminate all goto labels. If there is no response from them, or if they disagree with my changes, we can continue with your implementation.

[1]: https://lore.kernel.org/all/[email protected]/

drivers/cxl/core/pci.c +0 -0
index 9d807c1a002c..fbf4b56a39c4 100644
@@ -573,17 +573,8 @@ void read_cdat_data(struct cxl_port *port)

        size_t table_length, length;
        int rc;

-       if (is_cxl_memdev(uport)) {
-               struct device *host;
-
-               cxlmd = to_cxl_memdev(uport);
-               host = cxlmd->dev.parent;
-               if (dev_is_pci(host))
-                       pdev = to_pci_dev(host);
-       } else if (dev_is_pci(uport)) {
-               pdev = to_pci_dev(uport);
-       }
-
+       struct pci_dev *pdev __free(pci_dev_put) =
+                               cxl_port_get_uport_pci_dev(port); if (!pdev)
                return;

@@ -606,30 +597,32 @@ void read_cdat_data(struct cxl_port *port)
         * bytes for the DOE header. Table data starts afterwards. */
        buf = devm_kzalloc(dev, sizeof(*buf) + length, GFP_KERNEL); -       if (!buf)
-               goto err;
+       if (!buf) {
+               dev_err(dev, "Failed to allocate CDAT buffer.\n"); +               return;
+       }

        table_length = length;

        rc = cxl_cdat_read_table(dev, doe_mb, buf, &length); -       if (rc)
-               goto err;
+       if (rc) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to read CDAT.\n"); +               return;
+       }

        if (table_length != length)
                dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n", table_length, length);

-       if (cdat_checksum(buf->data, length))
-               goto err;
+       if (cdat_checksum(buf->data, length)) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to validate CDAT.\n"); +               return;
+       }

        port->cdat.table = buf->data; port->cdat.length = length;
-
-       return;
-err:
-       /* Don't leave table data allocated on error */ -       devm_kfree(dev, buf);
-       dev_err(dev, "Failed to read/validate CDAT.\n"); }

Quoted 120 lines
---
  drivers/cxl/core/core.h |  1 +
  drivers/cxl/core/pci.c  | 24 ++++++------------------
  drivers/cxl/core/port.c | 26 ++++++++++++++++++++++++++
  3 files changed, 33 insertions(+), 18 deletions(-)
drivers/cxl/core/core.h +1 -0
index 35eaf636adc9..983d7690c3a5 100644
@@ -157,6 +157,7 @@ long cxl_pci_get_latency(struct pci_dev *pdev);
  int cxl_pci_get_bandwidth(struct pci_dev *pdev, struct access_coordinate *c);
  int cxl_port_get_switch_dport_bandwidth(struct cxl_port *port,
  					struct access_coordinate *c);
+struct pci_dev *cxl_port_get_uport_pci_dev(struct cxl_port *port);
 
  static inline struct device *port_to_host(struct cxl_port *port)
  {
drivers/cxl/core/pci.c +6 -18
index 9d807c1a002c..905892cfedef 100644
@@ -564,26 +564,13 @@ static unsigned char cdat_checksum(void *buf, size_t size)
   */
  void read_cdat_data(struct cxl_port *port)
  {
-	struct device *uport = port->uport_dev;
+	struct pci_dev *pdev = cxl_port_get_uport_pci_dev(port);
  	struct device *dev = &port->dev;
  	struct pci_doe_mb *doe_mb;
-	struct pci_dev *pdev = NULL;
-	struct cxl_memdev *cxlmd;
  	struct cdat_doe_rsp *buf;
  	size_t table_length, length;
  	int rc;
 
-	if (is_cxl_memdev(uport)) {
-		struct device *host;
-
-		cxlmd = to_cxl_memdev(uport);
-		host = cxlmd->dev.parent;
-		if (dev_is_pci(host))
-			pdev = to_pci_dev(host);
-	} else if (dev_is_pci(uport)) {
-		pdev = to_pci_dev(uport);
-	}
-
  	if (!pdev)
  		return;
 
@@ -591,14 +578,14 @@ void read_cdat_data(struct cxl_port *port)
  				      CXL_DOE_PROTOCOL_TABLE_ACCESS);
  	if (!doe_mb) {
  		dev_dbg(dev, "No CDAT mailbox\n");
-		return;
+		goto out;
  	}
 
  	port->cdat_available = true;
 
  	if (cxl_cdat_get_length(dev, doe_mb, &length)) {
  		dev_dbg(dev, "No CDAT length\n");
-		return;
+		goto out;
  	}
 
  	/*
@@ -624,12 +611,13 @@ void read_cdat_data(struct cxl_port *port)
 
  	port->cdat.table = buf->data;
  	port->cdat.length = length;
-
-	return;
+	goto out;
  err:
  	/* Don't leave table data allocated on error */
  	devm_kfree(dev, buf);
  	dev_err(dev, "Failed to read/validate CDAT.\n");
+out:
+	pci_dev_put(pdev);
  }
  EXPORT_SYMBOL_NS_GPL(read_cdat_data, "CXL");
 
drivers/cxl/core/port.c +26 -0
index 625e4aa427db..5dc2815d82d8 100644
@@ -34,6 +34,32 @@
  static DEFINE_IDA(cxl_port_ida);
  static DEFINE_XARRAY(cxl_root_buses);
 
+/**
+ * cxl_port_get_uport_pci_dev - get the PCI device for a port's upstream device
+ * @port: CXL port to map to a PCI device
+ *
+ * Return: A referenced PCI device, or NULL if the upstream device is not PCI.
+ * The caller must release the returned reference with pci_dev_put().
+ */
+struct pci_dev *cxl_port_get_uport_pci_dev(struct cxl_port *port)
+{
+	struct device *uport = port->uport_dev;
+	struct device *host;
+
+	if (is_cxl_memdev(uport)) {
+		struct cxl_memdev *cxlmd = to_cxl_memdev(uport);
+
+		host = cxlmd->dev.parent;
+	} else {
+		host = uport;
+	}
+
+	if (!host || !dev_is_pci(host))
+		return NULL;
+
+	return pci_dev_get(to_pci_dev(host));
+}
+
  /*
   * The terminal device in PCI is NULL and @platform_bus
   * for platform devices (for cxl_test)
reviewer
#30 lore raw

Re: [PATCH v17 11/19] PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Srirangan Madhavan
Quoted 189 lines · Srirangan Madhavan

Cache HDM state in pci_dev->hdm after BAR resource setup and before driver binding, so reset can restore it without a bound CXL driver.

Limit caching to devices that advertise CXL.cache, CXL.mem, CXL Reset, and Reset Memory Clear. Save their HDM register location, decoder settings, and Device DVSEC state.

Validate capability reads and decoder counts, and restore PCI_COMMAND after temporary MMIO access, reporting restoration failures. Publish the cache under the PCI device lock and protect later updates with the DPA lock.

Assisted-by LLM

---
Changes in v17:
- Publish the cache under the PCI device lock without taking cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming)
https://lore.kernel.org/linux-cxl/[email protected]/
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() before it is written back or cached (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=11
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard)
https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b12baa1105f33cc1a10f9c9c0c6376194397d9f3

---
  MAINTAINERS                   |   1 +
  drivers/cxl/core/hdm_regs.c   |  96 +++++++++++++++
  drivers/cxl/core/hdm_state.c  |  37 +++++-
  drivers/cxl/core/pci.c        |  29 +++--
  drivers/pci/Makefile          |   1 +
  drivers/pci/bus.c             |   1 +
  drivers/pci/cxl.c             | 225 ++++++++++++++++++++++++++++++++++
  drivers/pci/pci.h             |   8 ++
  drivers/pci/probe.c           |   1 +
  include/cxl/hdm.h             |   9 ++
  include/uapi/linux/pci_regs.h |   2 +
  11 files changed, 399 insertions(+), 11 deletions(-)

create mode 100644 drivers/pci/cxl.c

MAINTAINERS +1 -0
index c2414447892c..b874340b0265 100644
@@ -6572,6 +6572,7 @@ S:	Maintained
  F:	Documentation/driver-api/cxl
  F:	Documentation/userspace-api/fwctl/fwctl-cxl.rst
  F:	drivers/cxl/
+F:	drivers/pci/cxl.c
  F:	include/cxl/
  F:	include/uapi/linux/cxl_mem.h
  F:	tools/testing/cxl/
drivers/cxl/core/hdm_regs.c +96 -0
index cc5d77c4abf5..c92dbb017162 100644
@@ -2,6 +2,7 @@
  /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
  #include <linux/delay.h>
  #include <linux/bug.h>
+#include <linux/device.h>
  #include <linux/errno.h>
  #include <linux/export.h>
  #include <linux/kernel.h>
@@ -190,3 +191,98 @@ int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
  	return cxl_hdm_unpack_decoder(config, id, ctrl, base, size);
  }
  EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_read_decoder, "cxl_core");
+
+/**
+ * cxl_hdm_decoder_count_mapped() - read the decoder count of a mapped block
+ * @dev: device for error reporting
+ * @hdm: mapped HDM decoder capability
+ * @size: size of the mapping
+ *
+ * Return: the decoder count, or a negative errno if the count is reserved or
+ * the mapping cannot hold every decoder.
+ */
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+				 resource_size_t size)
+{
+	int count;
+
+	count = cxl_hdm_decoder_count(readl(hdm + CXL_HDM_DECODER_CAP_OFFSET));
+	if (count < 0)
+		return count;
+
+	/* The last decoder's target-list high register must fit in the mapping. */
+	if (CXL_HDM_DECODER0_TL_HIGH(count - 1) + sizeof(u32) > size) {
+		dev_err(dev, "CXL HDM decoder count exceeds mapped register block\n");
+		return -ENXIO;
+	}
+
+	return count;
+}
+
+/* Read one endpoint decoder; a disabled decoder keeps only its id. */
+static int cxl_hdm_read_decoder_settings(struct device *dev,
+					 struct cxl_endpoint_decoder_settings *settings,
+					 void __iomem *hdm, int id)
+{
+	u64 lo, hi;
+	u32 ctrl;
+	int rc;
+
+	ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(id));
+	rc = cxl_hdm_read_decoder(&settings->config, hdm, id, ctrl);
+	if (rc) {
+		dev_err(dev,
+			"CXL HDM decoder %d has invalid configuration: %d\n",
+			id, rc);
+		return rc;
+	}
+
+	if (!(settings->config.flags & CXL_DECODER_F_ENABLE)) {
+		*settings = (struct cxl_endpoint_decoder_settings) {
+			.config.id = id,
+		};
+	} else {
+		lo = readl(hdm + CXL_HDM_DECODER0_SKIP_LOW(id));
+		hi = readl(hdm + CXL_HDM_DECODER0_SKIP_HIGH(id));
+		settings->skip = (hi << 32) | lo;
+	}
+
+	return 0;
+}
+
+/**
+ * cxl_hdm_read_state() - read endpoint HDM decoder state
+ * @dev: device for error messages
+ * @hdm: mapped HDM decoder capability
+ * @info: state to fill; @info->decoder_count must be set
+ *
+ * Return: 0 on success, or a negative errno if a decoder holds an invalid
+ * configuration or the decoder count changed while reading.
+ */
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+		       struct cxl_hdm_info *info)
+{
+	int count;
+	int rc;
+
+	info->global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
+	for (int i = 0; i < info->decoder_count; i++) {
+		rc = cxl_hdm_read_decoder_settings(dev, &info->settings[i],
+						   hdm, i);
+		if (rc)
+			return rc;
+	}
+
+	/*
+	 * A changed decoder count means the snapshot no longer describes the
+	 * complete hardware state. Reject it rather than publish a partial cache.
+	 */
+	count = cxl_hdm_decoder_count(readl(hdm + CXL_HDM_DECODER_CAP_OFFSET));
+	if (count != info->decoder_count) {
+		dev_err(dev, "CXL HDM decoder count changed from %d to %d\n",
+			info->decoder_count, count);
+		return -ENXIO;
+	}
+
+	return 0;
+}
drivers/cxl/core/hdm_state.c +5 -1
index d4c2be1ef833..9def4a7439c9 100644
@@ -1,21 +1,37 @@
  // SPDX-License-Identifier: GPL-2.0-only
  /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/cleanup.h>
  #include <linux/export.h>
  #include <linux/io.h>
  #include <linux/pci.h>
  #include <linux/rwsem.h>
+#include <linux/slab.h>
 
  #include <cxl/hdm.h>
-
  #include "cxl.h"
  #include "core.h"
 
+/*
+ * CXL state that must stay available while no CXL driver is bound: the CXL
+ * locks and the per-device HDM cache filled during PCI enumeration.

drivers/cxl/core/hdm_state.c line 26

Quoted 10 lines
drivers/cxl/core/hdm_state.c +4 -0
+ */
  struct cxl_rwsem cxl_rwsem = {
  	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
  	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
  };
  EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
 
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl)
+{
+	guard(rwsem_write)(&cxl_rwsem.dpa);

Is this lock needed? “pdev->hdm->dvsec_ctrl” could be modified concurrently? Seems like it is called during the endpoint port probing.

Quoted 23 lines
drivers/cxl/core/hdm_state.c +16 -0
+	if (!pdev->hdm)
+		return;
+
+	pdev->hdm->dvsec_ctrl = ctrl;
+	pdev->hdm->dvsec_ctrl_valid = true;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_set_dvsec_ctrl, "cxl_core");
+
  void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
  				   struct cxl_endpoint_decoder *cxled)
  {
@@ -70,3 +86,22 @@ int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count)
  	return 0;
  }
  EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_check_decoder_count, "cxl_core");
+
+/**
+ * cxl_hdm_cache_release() - unpublish and free cached HDM state
+ * @slot: cache pointer owned by the device
+ *
+ * Take the DPA write lock to exclude readers while clearing @slot, then
+ * free the unpublished cache after releasing the lock.
+ */

drivers/cxl/core/hdm_state.c int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count) · line 106

Quoted 10 lines
drivers/cxl/core/hdm_state.c +10 -0
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot)
+{
+	struct cxl_hdm_info *info;
+
+	scoped_guard(rwsem_write, &cxl_rwsem.dpa) {
+		info = *slot;
+		/* Unpublish before freeing so readers cannot see stale state. */
+		*slot = NULL;
+	}
+	kfree(info);

I don't think we need this lock either. And we can free the “*slot” directly. Because cxl_hdm_cache_release() is called in pci_release_dev(). pci_release_dev() runs once the pci_dev refcount drops to 0, so the pci_dev is being released, no driver can access this pci_dev at this point.

Quoted 210 lines
drivers/cxl/core/hdm_state.c +1 -0
+}
drivers/cxl/core/pci.c +19 -10
index 5272013548c7..ea5327cd627f 100644
@@ -209,22 +209,31 @@ static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)
  	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
  	int d = cxlds->cxl_dvsec;
  	u16 ctrl;
-	int rc;
+	int rc, ret = 1;
 
  	rc = pci_read_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, &ctrl);
  	if (rc)
  		return pcibios_err_to_errno(rc);
+	/* An all-ones read must not be written back or cached. */
+	if (PCI_POSSIBLE_ERROR(ctrl))
+		return -ENODEV;
 
-	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) == val)
-		return 1;
-	ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
-	ctrl |= val;
+	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) != val) {
+		ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
+		ctrl |= val;
 
-	rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
-	if (rc)
-		return pcibios_err_to_errno(rc);
+		rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		ret = 0;
+	}
 
-	return 0;
+	/*
+	 * Refresh the PCI-core cache from the live register even when
+	 * MEM_ENABLE already matched: a reset restores the cached value.
+	 */
+	cxl_hdm_cache_set_dvsec_ctrl(pdev, ctrl);
+	return ret;
  }
 
  static void clear_mem_enable(void *cxlds)
@@ -314,7 +323,7 @@ int cxl_dvsec_rr_decode(struct cxl_dev_state *cxlds,
  	 * capable, there is no point in continuing to enable CXL.mem.
  	 */
  	hdm_count = FIELD_GET(PCI_DVSEC_CXL_HDM_COUNT, cap);
-	if (!hdm_count || hdm_count > 2)
+	if (!cxl_dvsec_hdm_count_valid(hdm_count))
  		return -EINVAL;
 
  	/*
drivers/pci/Makefile +1 -0
index 41ebc3b9a518..7a5d9f7297e9 100644
@@ -34,6 +34,7 @@ obj-$(CONFIG_PCI_P2PDMA)	+= p2pdma.o
  obj-$(CONFIG_XEN_PCIDEV_FRONTEND) += xen-pcifront.o
  obj-$(CONFIG_VGA_ARB)		+= vgaarb.o
  obj-$(CONFIG_PCI_DOE)		+= doe.o
+obj-$(CONFIG_CXL_RESET)		+= cxl.o
  obj-$(CONFIG_PCI_IDE)		+= ide.o
  obj-$(CONFIG_PCI_TSM)		+= tsm.o
  obj-$(CONFIG_PCI_DYNAMIC_OF_NODES) += of_property.o
drivers/pci/bus.c +1 -0
index 655ed53436d3..aad567fb7c56 100644
@@ -359,6 +359,7 @@ void pci_bus_add_device(struct pci_dev *dev)
 
  	/* Save config space for error recoverability */
  	pci_save_state(dev);
+	pci_cxl_hdm_cache_init(dev);
 
  	/*
  	 * Enable runtime PM, which potentially allows the device to
drivers/pci/cxl.c new file +125 -0
new file mode 100644
index 000000000000..a0d20f4210a5
@@ -0,0 +1,225 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+/*
+ * CXL reset support in the PCI core. Cache the HDM decoder state of a CXL
+ * memory device at enumeration, so it can be restored after a reset without
+ * a CXL driver. HDM register formats and programming live in drivers/cxl.
+ */
+#include <linux/bitfield.h>
+#include <linux/cleanup.h>
+#include <linux/errno.h>
+#include <linux/io.h>
+#include <linux/ioport.h>
+#include <linux/kernel.h>
+#include <linux/pci.h>
+#include <linux/slab.h>
+
+#include <cxl/hdm.h>
+#include <cxl/pci.h>
+
+#include "pci.h"
+
+/* Find the CXL Device DVSEC and read its capability register. */
+static int cxl_pci_device_dvsec(struct pci_dev *pdev, u16 *dvsec, u16 *cap)
+{
+	int rc;
+
+	*dvsec = pci_find_dvsec_capability(pdev, PCI_VENDOR_ID_CXL,
+					   PCI_DVSEC_CXL_DEVICE);
+	if (!*dvsec)
+		return -ENOTTY;
+
+	rc = pci_read_config_word(pdev, *dvsec + PCI_DVSEC_CXL_CAP, cap);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(*cap))
+		return -ENODEV;
+
+	return 0;
+}
+
+static bool cxl_pci_bar_assigned(struct pci_dev *pdev, int bar)
+{
+	struct resource *res = &pdev->resource[bar];
+
+	return pci_resource_len(pdev, bar) &&
+	       !(res->flags & (IORESOURCE_UNSET | IORESOURCE_DISABLED)) &&
+	       resource_type(res) == IORESOURCE_MEM && res->start && res->end;
+}
+
+static void __iomem *cxl_pci_hdm_map_regs(struct pci_dev *pdev,
+					  struct cxl_register_map *map,
+					  resource_size_t *hdm_offset,
+					  int *decoder_count)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	void __iomem *hdm;
+	int rc;
+
+	/* cxl_setup_regs() populates hdm_map, including its valid bit. */
+	rc = cxl_setup_regs(map);
+	if (rc)
+		return ERR_PTR(rc);
+	if (!hdm_map->valid)
+		return ERR_PTR(-ENODEV);
+	if (hdm_map->offset > map->max_size ||
+	    hdm_map->size > map->max_size - hdm_map->offset)
+		return ERR_PTR(-ENXIO);
+	if (check_add_overflow(map->bar_offset,
+			       (resource_size_t)hdm_map->offset, hdm_offset))
+		return ERR_PTR(-EOVERFLOW);
+
+	hdm = ioremap(map->resource + hdm_map->offset, hdm_map->size);
+	if (!hdm)
+		return ERR_PTR(-ENOMEM);
+
+	*decoder_count = cxl_hdm_decoder_count_mapped(&pdev->dev, hdm,
+						      hdm_map->size);
+	if (*decoder_count < 0) {
+		iounmap(hdm);
+		return ERR_PTR(*decoder_count);
+	}
+
+	return hdm;
+}
+
+static struct cxl_hdm_info *__cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						    struct cxl_register_map *map,
+						    int dvsec)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	struct cxl_hdm_info *info;
+	resource_size_t hdm_offset;
+	void __iomem *hdm;
+	int decoder_count;
+	u16 dvsec_ctrl;
+	int rc;
+
+	hdm = cxl_pci_hdm_map_regs(pdev, map, &hdm_offset, &decoder_count);
+	if (IS_ERR(hdm))
+		return ERR_CAST(hdm);
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL,
+				  &dvsec_ctrl);
+	if (rc) {
+		rc = pcibios_err_to_errno(rc);
+		goto out_unmap;
+	}
+
+	info = kzalloc_flex(*info, settings, decoder_count, GFP_KERNEL);
+	if (!info) {
+		rc = -ENOMEM;
+		goto out_unmap;
+	}
+
+	info->decoder_count = decoder_count;
+	info->hdm_bar = map->bar;
+	info->hdm_offset = hdm_offset;
+	info->hdm_size = hdm_map->size;
+	info->dvsec = dvsec;
+	info->dvsec_ctrl = dvsec_ctrl;
+	info->dvsec_ctrl_valid = true;
+
+	rc = cxl_hdm_read_state(&pdev->dev, hdm, info);
+	if (rc)
+		goto out_free;

drivers/pci/cxl.c line 135

Quoted 10 lines
drivers/pci/cxl.c new file +10 -0
+
+	iounmap(hdm);
+	return info;
+
+out_free:
+	kfree(info);
+out_unmap:
+	iounmap(hdm);
+	return ERR_PTR(rc);
+}

How about like this?

+static struct cxl_hdm_info *__cxl_pci_hdm_read_info(struct pci_dev *pdev,
+ struct cxl_register_map *map,
+ int dvsec)
+{
+ struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+ struct cxl_hdm_info *info = NULL;
+ resource_size_t hdm_offset;
+ void __iomem *hdm;
+ int decoder_count;
+ u16 dvsec_ctrl;
+ int rc;
+
+ hdm = cxl_pci_hdm_map_regs(pdev, map, &hdm_offset, &decoder_count);
+ if (IS_ERR(hdm))
+ return ERR_CAST(hdm);
+
+ rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL,
+ &dvsec_ctrl);
+ if (rc) {
+ rc = pcibios_err_to_errno(rc);
+ goto out;
+ }
+
+ info = kzalloc_flex(*info, settings, decoder_count, GFP_KERNEL);
+ if (!info) {
+ rc = -ENOMEM;
+ goto out;
+ }
+
+ info->decoder_count = decoder_count;
+ info->hdm_bar = map->bar;
+ info->hdm_offset = hdm_offset;
+ info->hdm_size = hdm_map->size;
+ info->dvsec = dvsec;
+ info->dvsec_ctrl = dvsec_ctrl;
+ info->dvsec_ctrl_valid = true;
+
+ rc = cxl_hdm_read_state(&pdev->dev, hdm, info);
+out:
+ if (rc)
+ kfree(info);
+ iounmap(hdm);
+ return rc ? ERR_PTR(rc) : info;
+}

Quoted 62 lines
drivers/pci/cxl.c new file +62 -0
+
+static struct cxl_hdm_info *cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						  struct cxl_register_map *map,
+						  int dvsec)
+{
+	struct cxl_hdm_info *info;
+	u16 command;
+	int rc;
+
+	rc = pci_read_config_word(pdev, PCI_COMMAND, &command);
+	if (rc)
+		return ERR_PTR(pcibios_err_to_errno(rc));
+
+	if (!(command & PCI_COMMAND_MEMORY)) {
+		rc = pci_write_config_word(pdev, PCI_COMMAND,
+					   command | PCI_COMMAND_MEMORY);
+		if (rc)
+			return ERR_PTR(pcibios_err_to_errno(rc));
+	}
+
+	info = __cxl_pci_hdm_read_info(pdev, map, dvsec);
+	if (!(command & PCI_COMMAND_MEMORY)) {
+		rc = pci_write_config_word(pdev, PCI_COMMAND, command);
+		if (rc)
+			pci_err(pdev,
+				"failed to restore PCI_COMMAND after CXL HDM cache init: %d\n",
+				pcibios_err_to_errno(rc));
+	}
+	return info;
+}
+
+static int __pci_cxl_hdm_cache_init(struct pci_dev *pdev)
+{
+	struct cxl_register_map map = { };
+	struct cxl_hdm_info *read_info;
+	u16 dvsec, cap;
+	int rc;
+
+	guard(pci_dev)(pdev);
+
+	/* Avoid duplicate MMIO reads when the cache is already present. */
+	if (pdev->hdm)
+		return 0;
+
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc == -ENOTTY)
+		return 0;
+	if (rc)
+		return rc;
+	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE) ||
+	    !cxl_dvsec_hdm_count_valid(FIELD_GET(PCI_DVSEC_CXL_HDM_COUNT, cap)))
+		return 0;
+
+	rc = cxl_find_regblock(pdev, CXL_REGLOC_RBI_COMPONENT, &map);
+	if (rc)
+		return rc;
+	if (map.bar < 0 || map.bar >= PCI_STD_NUM_BARS ||
+	    !cxl_pci_bar_assigned(pdev, map.bar))
+		return -ENODEV;

drivers/pci/cxl.c line 207

Quoted 10 lines
drivers/pci/cxl.c new file +10 -0
+
+	read_info = cxl_pci_hdm_read_info(pdev, &map, dvsec);
+	if (IS_ERR(read_info))
+		return PTR_ERR(read_info);
+
+	/*
+	 * The PCI device lock held since the cache check excludes other
+	 * initializers. CXL drivers bind only after enumeration, so no cache
+	 * mutator can run yet and cxl_rwsem.dpa is not needed to publish.
+	 */

I think this comment should be moved to above "guard(pci_dev)(pdev);".

Quoted 96 lines
drivers/pci/cxl.c new file +18 -0
+	pdev->hdm = read_info;
+
+	return 0;
+}
+
+void pci_cxl_hdm_cache_init(struct pci_dev *pdev)
+{
+	int rc;
+
+	rc = __pci_cxl_hdm_cache_init(pdev);
+	if (rc)
+		pci_dbg(pdev, "CXL HDM cache init failed: %d\n", rc);
+}
+
+void pci_cxl_hdm_cache_release(struct pci_dev *pdev)
+{
+	cxl_hdm_cache_release(&pdev->hdm);
+}
drivers/pci/pci.h +8 -0
index ba3c3fddddc2..9e218f236e66 100644
@@ -730,6 +730,14 @@ static inline void pci_doe_destroy(struct pci_dev *pdev) { }
  static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
  #endif
 
+#ifdef CONFIG_CXL_RESET
+void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
+void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
+#else
+static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
+static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
+#endif
+
  #ifdef CONFIG_PCI_NPEM
  void pci_npem_create(struct pci_dev *dev);
  void pci_npem_remove(struct pci_dev *dev);
drivers/pci/probe.c +1 -0
index 27008e2ea5af..cb52357344ed 100644
@@ -2484,6 +2484,7 @@ static void pci_release_dev(struct device *dev)
  	struct pci_dev *pci_dev;
 
  	pci_dev = to_pci_dev(dev);
+	pci_cxl_hdm_cache_release(pci_dev);
  	pci_release_capabilities(pci_dev);
  	pci_release_of_node(pci_dev);
  	pcibios_release_device(pci_dev);
include/cxl/hdm.h +9 -0
index 06e9aa4479c2..0604dcc439c9 100644
@@ -26,6 +26,7 @@ struct cxl_endpoint_decoder_settings {
   * @hdm_offset: offset of the HDM decoder capability in @hdm_bar
   * @hdm_size: size of the HDM decoder register block
   * @global_ctrl: HDM decoder global control register
+ * @dvsec: config space offset of the CXL Device DVSEC
   * @dvsec_ctrl: CXL DVSEC control register
   * @dvsec_ctrl_valid: whether @dvsec_ctrl contains valid state
   * @settings: per-endpoint-decoder programming state
@@ -39,13 +40,21 @@ struct cxl_hdm_info {
  	resource_size_t hdm_offset;
  	resource_size_t hdm_size;
  	u32 global_ctrl;
+	u16 dvsec;
  	u16 dvsec_ctrl;
  	bool dvsec_ctrl_valid;
  	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
  };
+struct device;
 
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+				 resource_size_t size);
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+		       struct cxl_hdm_info *info);
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl);
  void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
  				   struct cxl_endpoint_decoder *cxled);
  int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
 
  #endif /* __CXL_HDM_H__ */
include/uapi/linux/pci_regs.h +2 -0
index facaa324bd86..ca3e77b72d87 100644
@@ -1352,6 +1352,8 @@
  #define   PCI_DVSEC_CXL_CACHE_CAPABLE			_BITUL(0)
  #define   PCI_DVSEC_CXL_MEM_CAPABLE			_BITUL(2)
  #define   PCI_DVSEC_CXL_HDM_COUNT			__GENMASK(5, 4)
+#define   PCI_DVSEC_CXL_RST_CAPABLE			_BITUL(7)
+#define   PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE		_BITUL(11)
  #define  PCI_DVSEC_CXL_CTRL				0xC
  #define   PCI_DVSEC_CXL_MEM_ENABLE			_BITUL(2)
  #define  PCI_DVSEC_CXL_RANGE_SIZE_HIGH(i)		(0x18 + (i * 0x10))
reviewer
#36 lore raw

Re: [PATCH v17 12/19] PCI/CXL: Add CXL Device Reset sequencing

In reply to Srirangan Madhavan
Quoted 176 lines · Srirangan Madhavan

Implement CXL Device Reset for eligible Type 2 devices: disable CXL.cache, perform supported writeback, drain transactions, prepare the IOMMU, initiate reset with Memory Clear enabled, and wait for completion.

Observe the 100 ms post-reset quiet period before polling Status2, and treat an all-ones read as not ready. Wait for the timeout the device advertises, up to 100 seconds, and access only Status2 until reset completion, error or expiry, as CXL 4.0 section 9.7.3 requires. Control2 cleanup runs only afterwards. Treat Control2 command bits as transient state, restore cache policy on exit, preserve the primary error, and abort when IOMMU preparation fails.

Reuse Device DVSEC discovery from cache initialization and keep the reset entry point declaration private to PCI core.

---
Changes in v17:
- Wait for the reset timeout the device advertises, up to 100 seconds, instead of clamping it to 20 seconds, so that Control2 is not accessed while the device may still be resetting. The warning for an unknown timeout encoding now reports the timeout used (Richard)
https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=04f8f84816d724f8b47f4d47a77916ac37c63a49

---
  drivers/pci/cxl.c             | 244 +++++++++++++++++++++++++++++++++-
  drivers/pci/pci.h             |   5 +
  include/uapi/linux/pci_regs.h |  12 ++
  3 files changed, 260 insertions(+), 1 deletion(-)
drivers/pci/cxl.c +122 -1
index a0d20f4210a5..9ac5948f595b 100644
@@ -3,13 +3,17 @@
  /*
   * CXL reset support in the PCI core. Cache the HDM decoder state of a CXL
   * memory device at enumeration, so it can be restored after a reset without
- * a CXL driver. HDM register formats and programming live in drivers/cxl.
+ * a CXL driver, and implement CXL Device Reset. HDM register formats and
+ * programming live in drivers/cxl.
   */
  #include <linux/bitfield.h>
  #include <linux/cleanup.h>
+#include <linux/delay.h>
  #include <linux/errno.h>
  #include <linux/io.h>
  #include <linux/ioport.h>
+#include <linux/iommu.h>
+#include <linux/jiffies.h>
  #include <linux/kernel.h>
  #include <linux/pci.h>
  #include <linux/slab.h>
@@ -223,3 +227,241 @@ void pci_cxl_hdm_cache_release(struct pci_dev *pdev)
  {
  	cxl_hdm_cache_release(&pdev->hdm);
  }
+
+/*
+ * CXL r4.0 sec 9.7.2 defines the reset completion timeout encodings.
+ * Sec 9.7.3 leaves config-space access behavior undefined for 100 ms after
+ * initiating CXL Reset, then limits software to CXL Status2 access until
+ * reset completion, timeout, or error. Wait for the full advertised timeout
+ * so that Control2 is not accessed while the device may still be resetting.
+ */
+#define CXL_RESET_RRS_WAIT_MS 100
+#define CXL_RESET_STATUS_POLL_MS 20
+static const u32 cxl_reset_timeout_ms[] = {
+	10, 100, 1000, 10000, 100000,
+};
+
+/*
+ * CXL 4.0 section 9.6 permits using the device cache size to determine
+ * a timeout. Use a conservative fixed estimate of 100 ms.
+ */
+#define CXL_CACHE_WBI_TIMEOUT_US 100000
+#define CXL_CACHE_WBI_POLL_US 100
+
+#define CXL_RESET_CTRL2_CMD_MASK \
+	(PCI_DVSEC_CXL_INIT_CACHE_WBI | PCI_DVSEC_CXL_INIT_CXL_RST)
+
+static int cxl_reset_update_ctrl2(struct pci_dev *pdev, int dvsec,
+				  u16 set, u16 clear)
+{
+	u16 ctrl2;
+	int rc;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(ctrl2))
+		return -ENODEV;
+
+	/*
+	 * INIT_CACHE_WBI and INIT_CXL_RST are commands. Do not replay a command
+	 * that remains set in the value read back while updating persistent
+	 * Control2 state.
+	 */
+	ctrl2 &= ~CXL_RESET_CTRL2_CMD_MASK;
+	ctrl2 &= ~clear;
+	ctrl2 |= set;
+
+	rc = pci_write_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+
+	return 0;
+}
+
+static int cxl_reset_wait_cache_wbi(struct pci_dev *pdev, int dvsec)
+{
+	unsigned long deadline;
+	u16 status2;
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    PCI_DVSEC_CXL_INIT_CACHE_WBI, 0);
+	if (rc)
+		return rc;
+
+	deadline = jiffies + usecs_to_jiffies(CXL_CACHE_WBI_TIMEOUT_US);
+	while (time_before(jiffies, deadline)) {
+		usleep_range(CXL_CACHE_WBI_POLL_US,
+			     CXL_CACHE_WBI_POLL_US * 2);
+
+		rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_STATUS2,
+					  &status2);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		if (PCI_POSSIBLE_ERROR(status2))
+			return -ENODEV;
+		if (status2 & PCI_DVSEC_CXL_CACHE_INV)
+			return 0;
+	}
+
+	pci_warn(pdev, "timed out waiting for CXL cache writeback and invalidate\n");
+	return -ETIMEDOUT;
+}
+
+static int cxl_reset_disable_cache(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    PCI_DVSEC_CXL_DISABLE_CACHING, 0);
+	if (rc || !(cap & PCI_DVSEC_CXL_CACHE_WBI_CAPABLE))
+		return rc;
+
+	return cxl_reset_wait_cache_wbi(pdev, dvsec);
+}
+
+static int cxl_reset_restore_cache_policy(struct pci_dev *pdev, int dvsec,
+					  u16 saved_ctrl2)
+{
+	int rc;
+
+	rc = cxl_reset_update_ctrl2(pdev, dvsec,
+				    saved_ctrl2 & PCI_DVSEC_CXL_DISABLE_CACHING,
+				    PCI_DVSEC_CXL_DISABLE_CACHING);
+	if (rc)
+		pci_err(pdev, "failed to restore CXL cache policy: %d\n", rc);
+
+	return rc;
+}
+
+static int cxl_reset_wait_done(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	unsigned long deadline;
+	u32 timeout_ms;
+	u16 status2;
+	int idx, rc;
+
+	idx = FIELD_GET(PCI_DVSEC_CXL_RST_TIMEOUT, cap);
+	if (idx >= ARRAY_SIZE(cxl_reset_timeout_ms)) {

drivers/pci/cxl.c void pci_cxl_hdm_cache_release(struct pci_dev *pdev) · line 356

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+		idx = ARRAY_SIZE(cxl_reset_timeout_ms) - 1;
+		pci_warn(pdev,
+			 "unknown CXL reset timeout encoding; using %u ms\n",
+			 cxl_reset_timeout_ms[idx]);
+	}
+
+	/* Allow one retry after the mandatory 100 ms quiet period. */
+	timeout_ms = max_t(u32, cxl_reset_timeout_ms[idx],
+			   CXL_RESET_RRS_WAIT_MS + CXL_RESET_STATUS_POLL_MS);
+	pci_info(pdev, "CXL reset timeout: %u ms\n", timeout_ms);

This log is improper, “CXL reset timeout:” seems like the timeout happens, but it just outputs the timeout value before starting waiting for CXL reset done. How about something like "Waiting for CXL reset to complete. (max wait: %u ms)\n"?

Quoted 8 lines
drivers/pci/cxl.c +8 -0
+	msleep(CXL_RESET_RRS_WAIT_MS);
+	deadline = jiffies + msecs_to_jiffies(timeout_ms -
+					      CXL_RESET_RRS_WAIT_MS);
+
+	for (;;) {
+		rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_STATUS2,
+					  &status2);
+		if (rc)

drivers/pci/cxl.c void pci_cxl_hdm_cache_release(struct pci_dev *pdev) · line 374

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+			return pcibios_err_to_errno(rc);
+		if (status2 != U16_MAX) {
+			if (status2 & PCI_DVSEC_CXL_RST_ERR)
+				return -EIO;
+			if (status2 & PCI_DVSEC_CXL_RST_DONE)
+				return 0;
+		}
+
+		if (time_after_eq(jiffies, deadline))
+			return -ETIMEDOUT;

How about outputing a pci_err() when timeout happens? Like what you did in cxl_reset_await_cache_wbi().

Quoted 74 lines
drivers/pci/cxl.c +74 -0
+
+		msleep(CXL_RESET_STATUS_POLL_MS);
+	}
+}
+
+static int cxl_clear_memory(struct pci_dev *pdev, int dvsec, bool initiate)
+{
+	if (initiate)
+		return cxl_reset_update_ctrl2(pdev, dvsec,
+					      PCI_DVSEC_CXL_INIT_CXL_RST |
+					      PCI_DVSEC_CXL_RST_MEM_CLR_EN,
+					      0);
+
+	return cxl_reset_update_ctrl2(pdev, dvsec, 0,
+				      PCI_DVSEC_CXL_RST_MEM_CLR_EN);
+}
+
+static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc, rc2;
+
+	if (!pci_wait_for_pending_transaction(pdev)) {
+		pci_err(pdev, "timed out waiting for pending transactions\n");
+		return -ETIMEDOUT;
+	}
+
+	rc = pci_dev_reset_iommu_prepare(pdev);
+	if (rc) {
+		pci_err(pdev, "failed to stop IOMMU for CXL reset: %d\n", rc);
+		return rc;
+	}
+
+	rc = cxl_clear_memory(pdev, dvsec, true);
+	if (!rc)
+		rc = cxl_reset_wait_done(pdev, dvsec, cap);
+
+	/* Always clear Memory Clear; successful cleanup must not hide reset failure. */
+	rc2 = cxl_clear_memory(pdev, dvsec, false);
+	if (rc2)
+		pci_err(pdev, "failed to clear CXL Reset Memory Clear: %d\n", rc2);
+	rc = rc ?: rc2;
+
+	pci_dev_reset_iommu_done(pdev);
+	return rc;
+}
+
+static int cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	u16 saved_ctrl2;
+	int rc, rc2;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &saved_ctrl2);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(saved_ctrl2))
+		return -ENODEV;
+
+	rc = cxl_reset_disable_cache(pdev, dvsec, cap);
+	if (!rc)
+		rc = __cxl_reset_execute(pdev, dvsec, cap);
+	/* Restore cache policy after any attempt to disable caching. */
+	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, saved_ctrl2);
+	return rc ?: rc2;
+}
+
+int cxl_reset_function(struct pci_dev *pdev, bool probe)
+{
+	u16 dvsec, cap, ctrl;
+	int rc;
+
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc)
+		return rc;
+	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||

drivers/pci/cxl.c void pci_cxl_hdm_cache_release(struct pci_dev *pdev) · line 458

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE))
+		return -ENOTTY;
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL, &ctrl);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(ctrl))
+		return -ENODEV;

There are many instances where we use pci_read_config_word() together with PCI_POSSIBLE_ERROR(). Would it make sense to introduce a helper to wrap pci_read_config_word() and its PCI_POSSIBLE_ERROR() error handling?

Quoted 55 lines
drivers/pci/cxl.c +9 -0
+	if (!(ctrl & PCI_DVSEC_CXL_CACHE_ENABLE) ||
+	    !(ctrl & PCI_DVSEC_CXL_MEM_ENABLE))
+		return -ENOTTY;
+
+	if (probe)
+		return 0;
+
+	return cxl_reset_execute(pdev, dvsec, cap);
+}
drivers/pci/pci.h +5 -0
index 9e218f236e66..743e65abd758 100644
@@ -733,9 +733,14 @@ static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
  #ifdef CONFIG_CXL_RESET
  void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
  void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
+int cxl_reset_function(struct pci_dev *pdev, bool probe);
  #else
  static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
  static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
+static inline int cxl_reset_function(struct pci_dev *pdev, bool probe)
+{
+	return -ENOTTY;
+}
  #endif
 
  #ifdef CONFIG_PCI_NPEM
include/uapi/linux/pci_regs.h +12 -0
index ca3e77b72d87..7224857c7b30 100644
@@ -1352,10 +1352,22 @@
  #define   PCI_DVSEC_CXL_CACHE_CAPABLE			_BITUL(0)
  #define   PCI_DVSEC_CXL_MEM_CAPABLE			_BITUL(2)
  #define   PCI_DVSEC_CXL_HDM_COUNT			__GENMASK(5, 4)
+#define   PCI_DVSEC_CXL_CACHE_WBI_CAPABLE		_BITUL(6)
  #define   PCI_DVSEC_CXL_RST_CAPABLE			_BITUL(7)
+#define   PCI_DVSEC_CXL_RST_TIMEOUT			__GENMASK(10, 8)
  #define   PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE		_BITUL(11)
  #define  PCI_DVSEC_CXL_CTRL				0xC
+#define   PCI_DVSEC_CXL_CACHE_ENABLE			_BITUL(0)
  #define   PCI_DVSEC_CXL_MEM_ENABLE			_BITUL(2)
+#define  PCI_DVSEC_CXL_CTRL2				0x10
+#define   PCI_DVSEC_CXL_DISABLE_CACHING			_BITUL(0)
+#define   PCI_DVSEC_CXL_INIT_CACHE_WBI			_BITUL(1)
+#define   PCI_DVSEC_CXL_INIT_CXL_RST			_BITUL(2)
+#define   PCI_DVSEC_CXL_RST_MEM_CLR_EN			_BITUL(3)
+#define  PCI_DVSEC_CXL_STATUS2				0x12
+#define   PCI_DVSEC_CXL_CACHE_INV			_BITUL(0)
+#define   PCI_DVSEC_CXL_RST_DONE			_BITUL(1)
+#define   PCI_DVSEC_CXL_RST_ERR				_BITUL(2)
  #define  PCI_DVSEC_CXL_RANGE_SIZE_HIGH(i)		(0x18 + (i * 0x10))
  #define  PCI_DVSEC_CXL_RANGE_SIZE_LOW(i)		(0x1C + (i * 0x10))
  #define   PCI_DVSEC_CXL_MEM_INFO_VALID			_BITUL(0)
reviewer
#31 lore raw

Re: [PATCH v17 11/19] PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Li Ming
Quoted 202 lines · Li Ming
Quoted 200 lines · Srirangan Madhavan

Cache HDM state in pci_dev->hdm after BAR resource setup and before driver binding, so reset can restore it without a bound CXL driver.

Limit caching to devices that advertise CXL.cache, CXL.mem, CXL Reset, and Reset Memory Clear. Save their HDM register location, decoder settings, and Device DVSEC state.

Validate capability reads and decoder counts, and restore PCI_COMMAND after temporary MMIO access, reporting restoration failures. Publish the cache under the PCI device lock and protect later updates with the DPA lock.

Assisted-by LLM

---
Changes in v17:
- Publish the cache under the PCI device lock without taking cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming)
https://lore.kernel.org/linux-cxl/[email protected]/
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() before it is written back or cached (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=11
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard)
https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b12baa1105f33cc1a10f9c9c0c6376194397d9f3
---
  MAINTAINERS                   |   1 +
  drivers/cxl/core/hdm_regs.c   |  96 +++++++++++++++
  drivers/cxl/core/hdm_state.c  |  37 +++++-
  drivers/cxl/core/pci.c        |  29 +++--
  drivers/pci/Makefile          |   1 +

  drivers/pci/bus.c             |   1 +
  drivers/pci/cxl.c             | 225 ++++++++++++++++++++++++++++++++++
  drivers/pci/pci.h             |   8 ++
  drivers/pci/probe.c           |   1 +
  include/cxl/hdm.h             |   9 ++
  include/uapi/linux/pci_regs.h |   2 +
  11 files changed, 399 insertions(+), 11 deletions(-)

  create mode 100644 drivers/pci/cxl.c

MAINTAINERS +0 -0
index c2414447892c..b874340b0265 100644
@@ -6572,6 +6572,7 @@ S:    Maintained

  F:    Documentation/driver-api/cxl
  F:    Documentation/userspace-api/fwctl/fwctl-cxl.rst F:    drivers/cxl/
+F:    drivers/pci/cxl.c
  F:    include/cxl/
  F:    include/uapi/linux/cxl_mem.h
  F:    tools/testing/cxl/

drivers/cxl/core/hdm_regs.c +1 -0
index cc5d77c4abf5..c92dbb017162 100644
@@ -2,6 +2,7 @@
   /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
   #include <linux/delay.h>
   #include <linux/bug.h>
+#include <linux/device.h>
   #include <linux/errno.h>
   #include <linux/export.h>
   #include <linux/kernel.h>
@@ -190,3 +191,98 @@ int cxl_hdm_read_decoder(struct 
 cxl_decoder_config *config, void __iomem *hdm,
       return cxl_hdm_unpack_decoder(config, id, ctrl, base, size);
   }

  EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_read_decoder, "cxl_core");

drivers/cxl/core/hdm_regs.c +3 -0
+
+/**
+ * cxl_hdm_decoder_count_mapped() - read the decoder count of a 

mapped block
+ * @dev: device for error reporting
+ * @hdm: mapped HDM decoder capability
+ * @size: size of the mapping
+ *
+ * Return: the decoder count, or a negative errno if the count is reserved or
+ * the mapping cannot hold every decoder.
+ */

drivers/cxl/core/hdm_regs.c +6 -0
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+                 resource_size_t size)
+{
+    int count;
+
+    count = cxl_hdm_decoder_count(readl(hdm + 

CXL_HDM_DECODER_CAP_OFFSET));
+    if (count < 0)
+        return count;
+
+    /* The last decoder's target-list high register must fit in the mapping. */
+    if (CXL_HDM_DECODER0_TL_HIGH(count - 1) + sizeof(u32) > size) { +        dev_err(dev, "CXL HDM decoder count exceeds mapped register block\n");
+        return -ENXIO;
+    }

drivers/cxl/core/hdm_regs.c +42 -0
+
+    return count;
+}
+
+/* Read one endpoint decoder; a disabled decoder keeps only its id. */
+static int cxl_hdm_read_decoder_settings(struct device *dev,
+                     struct cxl_endpoint_decoder_settings *settings,
+                     void __iomem *hdm, int id)
+{
+    u64 lo, hi;
+    u32 ctrl;
+    int rc;
+
+    ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(id));
+    rc = cxl_hdm_read_decoder(&settings->config, hdm, id, ctrl);
+    if (rc) {
+        dev_err(dev,
+            "CXL HDM decoder %d has invalid configuration: %d\n",
+            id, rc);
+        return rc;
+    }
+
+    if (!(settings->config.flags & CXL_DECODER_F_ENABLE)) {
+        *settings = (struct cxl_endpoint_decoder_settings) {
+            .config.id = id,
+        };
+    } else {
+        lo = readl(hdm + CXL_HDM_DECODER0_SKIP_LOW(id));
+        hi = readl(hdm + CXL_HDM_DECODER0_SKIP_HIGH(id));
+        settings->skip = (hi << 32) | lo;
+    }
+
+    return 0;
+}
+
+/**
+ * cxl_hdm_read_state() - read endpoint HDM decoder state
+ * @dev: device for error messages
+ * @hdm: mapped HDM decoder capability
+ * @info: state to fill; @info->decoder_count must be set
+ *
+ * Return: 0 on success, or a negative errno if a decoder holds an 

invalid
+ * configuration or the decoder count changed while reading.
+ */

drivers/cxl/core/hdm_regs.c +16 -0
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+               struct cxl_hdm_info *info)
+{
+    int count;
+    int rc;
+
+    info->global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
+    for (int i = 0; i < info->decoder_count; i++) {
+        rc = cxl_hdm_read_decoder_settings(dev, &info->settings[i],
+                           hdm, i);
+        if (rc)
+            return rc;
+    }
+
+    /*
+     * A changed decoder count means the snapshot no longer 

describes the
+     * complete hardware state. Reject it rather than publish a partial cache.
+     */
+    count = cxl_hdm_decoder_count(readl(hdm + CXL_HDM_DECODER_CAP_OFFSET));
+    if (count != info->decoder_count) {
+        dev_err(dev, "CXL HDM decoder count changed from %d to %d\n", +            info->decoder_count, count);
+        return -ENXIO;
+    }

drivers/cxl/core/hdm_regs.c +3 -0
+
+    return 0;
+}
drivers/cxl/core/hdm_state.c +2 -1
index d4c2be1ef833..9def4a7439c9 100644
@@ -1,21 +1,37 @@
   // SPDX-License-Identifier: GPL-2.0-only
   /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/cleanup.h>
   #include <linux/export.h>
   #include <linux/io.h>
   #include <linux/pci.h>
   #include <linux/rwsem.h>
+#include <linux/slab.h>
     #include <cxl/hdm.h>
-
   #include "cxl.h"
   #include "core.h"

  +/*
+ * CXL state that must stay available while no CXL driver is bound:
the CXL
+ * locks and the per-device HDM cache filled during PCI enumeration.
+ */
  struct cxl_rwsem cxl_rwsem = {

Quoted 8 lines
Quoted 7 lines

      .region = __RWSEM_INITIALIZER(cxl_rwsem.region), .dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
  };
  EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
  +void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl) +{
+    guard(rwsem_write)(&cxl_rwsem.dpa);

Is this lock needed? “pdev->hdm->dvsec_ctrl” could be modified concurrently? Seems like it is called during the endpoint port probing.

I realize that we may need this lock while I was reviewing patch #13. The CXL reset operation could be triggered during the endpoint port probing.

Would you mind moving the code of holding cxl_rwsem.dpa to patch #13? I think this could make it easier to review.

[snip]

#37 lore raw

Re: [PATCH v17 12/19] PCI/CXL: Add CXL Device Reset sequencing

In reply to Srirangan Madhavan
Quoted 12 lines · Srirangan Madhavan

Implement CXL Device Reset for eligible Type 2 devices: disable CXL.cache, perform supported writeback, drain transactions, prepare the IOMMU, initiate reset with Memory Clear enabled, and wait for completion.

Observe the 100 ms post-reset quiet period before polling Status2, and treat an all-ones read as not ready. Wait for the timeout the device advertises, up to 100 seconds, and access only Status2 until reset completion, error or expiry, as CXL 4.0 section 9.7.3 requires. Control2 cleanup runs only afterwards. Treat Control2 command bits as transient state, restore cache policy on exit, preserve the primary error, and abort when IOMMU preparation fails.

Quoted 4 lines

Reuse Device DVSEC discovery from cache initialization and keep the reset entry point declaration private to PCI core.

Hi Srirangan,

A concern regarding IOMMU handling below. If it turns to be unfounded, you can add my review tag.

Thank you,

Alejandro

<snip>

drivers/pci/cxl.c void pci_cxl_hdm_cache_release(struct pci_dev *pdev) · line 401

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc, rc2;
+
+	if (!pci_wait_for_pending_transaction(pdev)) {
+		pci_err(pdev, "timed out waiting for pending transactions\n");
+		return -ETIMEDOUT;
+	}
+
+	rc = pci_dev_reset_iommu_prepare(pdev);

I'm not sure if this is safe enough. I can see a situation where a Type2 device could not be using CXL.mem and CXL.cache but CXL.io. This would imply no CXL initialization from the Type2 driver but:

    1) Such a driver could be giving functionality without CXL

    2) The device belonging to an IOMMU domain which such functionality is using

    3) The HDM decoder range as a system resource is free.

If I am right, a CXL reset could happen, and although it should not be triggered by user space under these circumstances, the door is open ...

The solution would be, currently, to check for a  driver not bound to the device in an IOMMU enabled system. I say currently because CXL.cache will need extra work with IOMMU mapping which are not yet there.

maintainer Reviewed-by on v17 7/19
#18 lore raw

Re: [PATCH v17 07/19] cxl: Share HDM decoder register unpacking

In reply to Srirangan Madhavan
Quoted 9 lines · Srirangan Madhavan

Factor common HDM register parsing into cxl_hdm_unpack_decoder(). Validate range and interleave parameters in locals before publishing the decoder configuration, including enable and lock flags. Reject nonzero ranges whose end overflows the address space while preserving the zero-size range representation.

Read decoder base and size registers low then high through a shared helper used by enumeration and the reset snapshot.

Quoted 8 lines

Read switch target lists and endpoint DPA skip in their respective branches of init_hdm_decoder().

Preserve the decoder ID allocated by cxl_decoder_init() when publishing the parsed configuration.

Assisted-by LLM

Feel free to just drop this. Upstream no longer wants it.

Quoted 1 line
Quoted 218 lines

---
Changes in v17:
- Initialize the zero-size end to base - 1 and document the zero-size case, removing a branch (Richard)
https://lore.kernel.org/linux-cxl/auQ27s1rSCcbdRJ3@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=7d6ed7faf7d8e14abce8ae23902d5323738868d2

---
 drivers/cxl/core/core.h     |  5 +++
 drivers/cxl/core/hdm.c      | 65 ++++++++------------------------
 drivers/cxl/core/hdm_regs.c | 74 +++++++++++++++++++++++++++++++++++++
 3 files changed, 95 insertions(+), 49 deletions(-)
drivers/cxl/core/core.h +5 -0
index fb14b222f3ca..ea539f00e55d 100644
@@ -147,6 +147,11 @@ void cxl_commit_start_switch(const struct cxl_decoder_config *config,
 			     u64 targets, void __iomem *hdm);
 int cxld_await_commit(void __iomem *hdm, int id);
 
+int cxl_hdm_unpack_decoder(struct cxl_decoder_config *config, int id,
+			   u32 ctrl, u64 base, u64 size);
+int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
+			 int id, u32 ctrl);
+
 int cxl_memdev_init(void);
 void cxl_memdev_exit(void);
 void cxl_mbox_init(void);
drivers/cxl/core/hdm.c +16 -49
index 2c373dfbc070..5b5f5f22ea32 100644
@@ -938,11 +938,11 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld,
 			    u64 *dpa_base, struct cxl_endpoint_dvsec_info *info)
 {
 	struct cxl_endpoint_decoder *cxled = NULL;
-	u64 size, base, skip, dpa_size, lo, hi;
-	bool committed;
+	u64 size, skip, dpa_size, lo, hi;
+	struct cxl_decoder_config config;
 	u32 remainder;
-	int i, rc;
 	u32 ctrl;
+	int i, rc;
 	union {
 		u64 value;
 		unsigned char target_id[8];
@@ -953,41 +953,25 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld,
 							which, info);
 
 	ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(which));
-	lo = readl(hdm + CXL_HDM_DECODER0_BASE_LOW_OFFSET(which));
-	hi = readl(hdm + CXL_HDM_DECODER0_BASE_HIGH_OFFSET(which));
-	base = (hi << 32) + lo;
-	lo = readl(hdm + CXL_HDM_DECODER0_SIZE_LOW_OFFSET(which));
-	hi = readl(hdm + CXL_HDM_DECODER0_SIZE_HIGH_OFFSET(which));
-	size = (hi << 32) + lo;
-	committed = !!(ctrl & CXL_HDM_DECODER0_CTRL_COMMITTED);
+	rc = cxl_hdm_read_decoder(&config, hdm, which, ctrl);
+	if (rc) {
+		dev_warn(&port->dev,
+			 "decoder%d.%d: Invalid decoder configuration (ctrl: %#x): %d\n",
+			 port->id, cxld->config.id, ctrl, rc);
+		return rc;
+	}
+
+	config.id = cxld->config.id;
 	cxld->commit = cxl_decoder_commit;
 	cxld->reset = cxl_decoder_reset;
-
-	if (!committed)
-		size = 0;
-	if (base == U64_MAX || size == U64_MAX) {
-		dev_warn(&port->dev, "decoder%d.%d: Invalid resource range\n",
-			 port->id, cxld->config.id);
-		return -ENXIO;
-	}
+	cxld->config = config;
+	size = range_len(&cxld->config.hpa_range);
 
 	if (info)
 		cxled = to_cxl_endpoint_decoder(&cxld->dev);
-	cxld->config.hpa_range = (struct range) {
-		.start = base,
-		.end = base + size - 1,
-	};
 
 	/* decoders are enabled if committed */
-	if (committed) {
-		cxld->config.flags |= CXL_DECODER_F_ENABLE;
-		if (ctrl & CXL_HDM_DECODER0_CTRL_LOCK)
-			cxld->config.flags |= CXL_DECODER_F_LOCK;
-		if (FIELD_GET(CXL_HDM_DECODER0_CTRL_HOSTONLY, ctrl))
-			cxld->config.target_type = CXL_DECODER_HOSTONLYMEM;
-		else
-			cxld->config.target_type = CXL_DECODER_DEVMEM;
-
+	if (cxld->config.flags & CXL_DECODER_F_ENABLE) {
 		guard(rwsem_write)(&cxl_rwsem.region);
 		if (cxld->config.id != cxl_num_decoders_committed(port)) {
 			dev_warn(&port->dev,
@@ -1021,23 +1005,6 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld,
 			writel(ctrl, hdm + CXL_HDM_DECODER0_CTRL_OFFSET(which));
 		}
 	}
-	rc = eiw_to_ways(FIELD_GET(CXL_HDM_DECODER0_CTRL_IW_MASK, ctrl),
-			  &cxld->config.interleave_ways);
-	if (rc) {
-		dev_warn(&port->dev,
-			 "decoder%d.%d: Invalid interleave ways (ctrl: %#x)\n",
-			 port->id, cxld->config.id, ctrl);
-		return rc;
-	}
-	rc = eig_to_granularity(FIELD_GET(CXL_HDM_DECODER0_CTRL_IG_MASK, ctrl),
-				 &cxld->config.interleave_granularity);
-	if (rc) {
-		dev_warn(&port->dev,
-			 "decoder%d.%d: Invalid interleave granularity (ctrl: %#x)\n",
-			 port->id, cxld->config.id, ctrl);
-		return rc;
-	}
-
 	dev_dbg(&port->dev, "decoder%d.%d: range: %#llx-%#llx iw: %d ig: %d\n",
 		port->id, cxld->config.id, cxld->config.hpa_range.start, cxld->config.hpa_range.end,
 		cxld->config.interleave_ways, cxld->config.interleave_granularity);
@@ -1052,7 +1019,7 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld,
 		return 0;
 	}
 
-	if (!committed)
+	if (!(cxld->config.flags & CXL_DECODER_F_ENABLE))
 		return 0;
 
 	dpa_size = div_u64_rem(size, cxld->config.interleave_ways, &remainder);
drivers/cxl/core/hdm_regs.c +74 -0
index 53d2f236e49c..cc5d77c4abf5 100644
@@ -116,3 +116,77 @@ void cxl_commit_start_switch(const struct cxl_decoder_config *config,
 	writel(ctrl, hdm + CXL_HDM_DECODER0_CTRL_OFFSET(id));
 }
 EXPORT_SYMBOL_FOR_MODULES(cxl_commit_start_switch, "cxl_core");
+
+int cxl_hdm_unpack_decoder(struct cxl_decoder_config *config, int id,
+			   u32 ctrl, u64 base, u64 size)
+{
+	bool committed = FIELD_GET(CXL_HDM_DECODER0_CTRL_COMMITTED, ctrl);
+	enum cxl_decoder_type target_type = 0;
+	int interleave_granularity;
+	unsigned long flags = 0;
+	struct range hpa_range;
+	int interleave_ways;
+	u64 end;
+	int rc;
+
+	if (!committed)
+		size = 0;
+	if (base == U64_MAX || size == U64_MAX)
+		return -ENXIO;
+	/* A zero-size decoder maps no HPA; its range is empty at @base. */
+	end = base - 1;
+	if (size && check_add_overflow(base, size - 1, &end))
+		return -ENXIO;
+
+	hpa_range = (struct range) {
+		.start = base,
+		.end = end,
+	};
+
+	if (committed) {
+		flags |= CXL_DECODER_F_ENABLE;
+		if (ctrl & CXL_HDM_DECODER0_CTRL_LOCK)
+			flags |= CXL_DECODER_F_LOCK;
+		if (FIELD_GET(CXL_HDM_DECODER0_CTRL_HOSTONLY, ctrl))
+			target_type = CXL_DECODER_HOSTONLYMEM;
+		else
+			target_type = CXL_DECODER_DEVMEM;
+	}
+
+	rc = eiw_to_ways(FIELD_GET(CXL_HDM_DECODER0_CTRL_IW_MASK, ctrl),
+			 &interleave_ways);
+	if (rc)
+		return rc;
+	rc = eig_to_granularity(FIELD_GET(CXL_HDM_DECODER0_CTRL_IG_MASK, ctrl),
+				&interleave_granularity);
+	if (rc)
+		return rc;
+
+	*config = (struct cxl_decoder_config) {
+		.id = id,
+		.hpa_range = hpa_range,
+		.interleave_ways = interleave_ways,
+		.interleave_granularity = interleave_granularity,
+		.target_type = target_type,
+		.flags = flags,
+	};
+
+	return 0;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_unpack_decoder, "cxl_core");
+
+int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
+			 int id, u32 ctrl)
+{
+	u64 lo, hi, base, size;
+
+	lo = readl(hdm + CXL_HDM_DECODER0_BASE_LOW_OFFSET(id));
+	hi = readl(hdm + CXL_HDM_DECODER0_BASE_HIGH_OFFSET(id));
+	base = (hi << 32) | lo;
+	lo = readl(hdm + CXL_HDM_DECODER0_SIZE_LOW_OFFSET(id));
+	hi = readl(hdm + CXL_HDM_DECODER0_SIZE_HIGH_OFFSET(id));
+	size = (hi << 32) | lo;
+
+	return cxl_hdm_unpack_decoder(config, id, ctrl, base, size);
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_read_decoder, "cxl_core");
maintainer Reviewed-by on v17 8/19
#21 lore raw

Re: [PATCH v17 08/19] cxl: Move cxl_rwsem into built-in code

In reply to Srirangan Madhavan
Quoted 5 lines · Srirangan Madhavan

Keep the region and DPA locks available to built-in CXL state management when cxl_core is modular.

Quoted 56 lines
---
 drivers/cxl/core/Makefile    |  2 +-
 drivers/cxl/core/hdm.c       |  5 -----
 drivers/cxl/core/hdm_state.c | 15 +++++++++++++++
 3 files changed, 16 insertions(+), 6 deletions(-)
 create mode 100644 drivers/cxl/core/hdm_state.c
drivers/cxl/core/Makefile +1 -1
index 6703c1729396..9971efb237fb 100644
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CXL_BUS) += cxl_core.o
-obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o
+obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o
 obj-$(CONFIG_CXL_SUSPEND) += suspend.o
 
 ccflags-y += -I$(srctree)/drivers/cxl
drivers/cxl/core/hdm.c +0 -5
index 5b5f5f22ea32..85f9abf58a42 100644
@@ -17,11 +17,6 @@
  * for enumerating these registers and capabilities.
  */
 
-struct cxl_rwsem cxl_rwsem = {
-	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
-	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
-};
-
 static int add_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld)
 {
 	int rc;
drivers/cxl/core/hdm_state.c new file +15 -0
new file mode 100644
index 000000000000..c9cc019902ef
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/export.h>
+#include <linux/rwsem.h>
+
+#include <cxl/hdm.h>
+
+#include "cxl.h"
+#include "core.h"
+
+struct cxl_rwsem cxl_rwsem = {
+	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
+	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
+};
+EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
maintainer
#24 lore raw

Re: [PATCH v17 09/19] cxl: Refresh cached PCI HDM decoder settings

In reply to Srirangan Madhavan
Quoted 73 lines · Srirangan Madhavan

Early PCI discovery creates the HDM cache, while later CXL enumeration and decoder operations provide updated programming state.

Refresh the PCI snapshot when decoders are enumerated, committed, or reset so reset recovery need not walk the CXL topology. Keep cache access and locking in the built-in HDM state helpers. Ignore updates when no cache exists and reject decoder-count mismatches.

Use CXL_RESET for the PCI HDM cache. Shared HDM register helpers do not require it.

Skip cache checks and updates for DVSEC-emulated decoders, which do not use HDM registers. Keep cached global control when MMIO reads return all ones.

Non-PCI mock ports have no upstream PCI device, so the cache helpers ignore them. This avoids test wrappers and a circular dependency between cxl_core and cxl_mock.

---
Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=50a88f5194e5df38590d413f925d8d5afa8a8488

---
 drivers/cxl/Kconfig          |  5 ++++
 drivers/cxl/core/core.h      |  1 +
 drivers/cxl/core/hdm.c       | 34 +++++++++++++++++++--
 drivers/cxl/core/hdm_state.c | 57 ++++++++++++++++++++++++++++++++++++
 drivers/cxl/core/pci.c       | 24 +++++++++++++++
 include/cxl/cxl.h            |  1 +
 include/cxl/hdm.h            | 32 ++++++++++++++++++++
 include/linux/pci.h          |  6 ++++
 8 files changed, 158 insertions(+), 2 deletions(-)
drivers/cxl/Kconfig +5 -0
index 80aeb0d556bd..8b08bfdc4982 100644
@@ -6,6 +6,7 @@ menuconfig CXL_BUS
 	select FW_UPLOAD
 	select PCI_DOE
 	select FIRMWARE_TABLE
+	select CXL_RESET
 	select NUMA_KEEP_MEMINFO if NUMA_MEMBLKS
 	select FWCTL if CXL_FEATURES
 	help
@@ -244,3 +245,7 @@ config CXL_ATL
 	depends on ACPI_PRMT && AMD_NB
 
 endif
+
+# CXL_BUS requires the PCI HDM cache and built-in state helpers, even when modular.
+config CXL_RESET
+	bool
drivers/cxl/core/core.h +1 -0
index ea539f00e55d..e34d574f6594 100644
@@ -224,6 +224,7 @@ static inline void devm_cxl_dport_ras_setup(struct cxl_dport *dport) { }
 int cxl_gpf_port_setup(struct cxl_dport *dport);
 
 struct cxl_hdm;
+int cxl_hdm_check_decoder_count(struct cxl_hdm *cxlhdm);
 int cxl_hdm_decode_init(struct cxl_dev_state *cxlds, struct cxl_hdm *cxlhdm,
 			struct cxl_endpoint_dvsec_info *info);
 int cxl_port_get_possible_dports(struct cxl_port *port);
drivers/cxl/core/hdm.c +0 -0
index 85f9abf58a42..ec387070d7ad 100644

drivers/cxl/core/hdm.c static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt) · line 732

Quoted 8 lines
drivers/cxl/core/hdm.c +5 -0
@@ -725,6 +725,24 @@ static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt)
 		*tgt |= FIELD_PREP(GENMASK_ULL(63, 56), t[7]->port_id);
 }
 
+static void cxl_hdm_refresh_decoder(struct cxl_hdm *cxlhdm,
+				    struct cxl_decoder *cxld)
+{
+	void __iomem *hdm = cxlhdm->regs.hdm_decoder;
+	struct pci_dev *pdev __free(pci_dev_put) = NULL;

Move the declaration to before you use the variable. This is an exception when it comes to var declarations in the kernel. The pattern above is discouraged.

drivers/cxl/core/hdm.c static void cxlsd_set_targets(struct cxl_switch_decoder *cxlsd, u64 *tgt) · line 739

Quoted 7 lines
drivers/cxl/core/hdm.c +7 -0
+
+	if (!hdm)
+		return;
+	if (!is_endpoint_decoder(&cxld->dev))
+		return;
+
+	pdev = cxl_port_get_uport_pci_dev(cxlhdm->port);

As mentioned above,
struct pci_dev *pdev __free(pci_dev_put) = cxl_port_get_uport_pci_dev(cxlhdm->port);

Quoted 106 lines
drivers/cxl/core/hdm.c +20 -2
+	if (!pdev)
+		return;
+	cxl_hdm_cache_refresh_decoder(pdev, hdm,
+				      to_cxl_endpoint_decoder(&cxld->dev));
+}
+
 static void
 cxl_endpoint_decoder_snapshot(struct cxl_endpoint_decoder *cxled,
 			      struct cxl_endpoint_decoder_settings *settings)
@@ -805,6 +823,7 @@ static int cxl_decoder_commit(struct cxl_decoder *cxld)
 	}
 	port->commit_end++;
 	cxld->config.flags |= CXL_DECODER_F_ENABLE;
+	cxl_hdm_refresh_decoder(cxlhdm, cxld);
 
 	return 0;
 }
@@ -877,6 +896,7 @@ static void cxl_decoder_reset(struct cxl_decoder *cxld)
 	writel(0, hdm + CXL_HDM_DECODER0_BASE_LOW_OFFSET(id));
 
 	cxld->config.flags &= ~CXL_DECODER_F_ENABLE;
+	cxl_hdm_refresh_decoder(cxlhdm, cxld);
 
 	/* Userspace is now responsible for reconfiguring this decoder */
 	if (is_endpoint_decoder(&cxld->dev)) {
@@ -1079,13 +1099,21 @@ static int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm,
 {
 	void __iomem *hdm = cxlhdm->regs.hdm_decoder;
 	struct cxl_port *port = cxlhdm->port;
-	int i;
+	/* DVSEC-emulated decoders do not describe the cached HDM registers. */
+	bool emulated = should_emulate_decoders(info);
 	u64 dpa_base = 0;
+	int i, rc;
+
+	if (is_cxl_endpoint(port) && hdm && !emulated) {
+		rc = cxl_hdm_check_decoder_count(cxlhdm);
+		if (rc)
+			return rc;
+	}
 
 	cxl_settle_decoders(cxlhdm);
 
 	for (i = 0; i < cxlhdm->decoder_count; i++) {
-		int rc, target_count = cxlhdm->target_count;
+		int target_count = cxlhdm->target_count;
 		struct cxl_decoder *cxld;
 
 		if (is_cxl_endpoint(port)) {
@@ -1120,6 +1148,8 @@ static int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm,
 			put_device(&cxld->dev);
 			return rc;
 		}
+		if (!emulated)
+			cxl_hdm_refresh_decoder(cxlhdm, cxld);
 		rc = add_hdm_decoder(port, cxld);
 		if (rc) {
 			dev_warn(&port->dev,
drivers/cxl/core/hdm_state.c +33 -0
index c9cc019902ef..d4c2be1ef833 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
 #include <linux/export.h>
+#include <linux/io.h>
+#include <linux/pci.h>
 #include <linux/rwsem.h>
 
 #include <cxl/hdm.h>
@@ -13,3 +15,58 @@ struct cxl_rwsem cxl_rwsem = {
 	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
 };
 EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
+
+void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
+				   struct cxl_endpoint_decoder *cxled)
+{
+	struct cxl_endpoint_decoder_settings *settings;
+	struct cxl_decoder *cxld = &cxled->cxld;
+	struct cxl_hdm_info *info;
+	u32 global_ctrl;
+	int id;
+
+	guard(rwsem_write)(&cxl_rwsem.dpa);
+	id = cxld->config.id;
+	info = pdev->hdm;
+	if (!info)
+		return;
+	if (id < 0 || id >= info->decoder_count) {
+		pci_warn(pdev, "CXL HDM decoder %d exceeds cached count %d\n",
+			 id, info->decoder_count);
+		return;
+	}
+
+	/* Preserve the last good value when the device does not respond. */
+	global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
+	if (global_ctrl != U32_MAX)
+		info->global_ctrl = global_ctrl;
+	settings = &info->settings[id];
+
+	/*
+	 * A disabled decoder's software object may retain its old range and
+	 * skip state. Leave only the decoder id in the cached settings so stale
+	 * state is not restored as an enabled decode.

drivers/cxl/core/hdm_state.c struct cxl_rwsem cxl_rwsem = { · line 58

Quoted 10 lines
drivers/cxl/core/hdm_state.c +10 -0
+	 */
+	*settings = (struct cxl_endpoint_decoder_settings) {
+		.config.id = id,
+	};
+	if (cxld->config.flags & CXL_DECODER_F_ENABLE) {
+		settings->config = cxld->config;
+		settings->skip = cxled->skip;
+	}
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_refresh_decoder, "cxl_core");

kdoc header for exported symbol

drivers/cxl/core/hdm_state.c struct cxl_rwsem cxl_rwsem = { · line 60

Quoted 2 lines
drivers/cxl/core/hdm_state.c +2 -0
+
+int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count)

In the end we are just looking to see if there's a match right? I think returning a bool and changing the function name to be more obvious.

bool cxl_hdm_cache_decoder_count_match() maybe?

drivers/cxl/core/hdm_state.c struct cxl_rwsem cxl_rwsem = { · line 72

Quoted 12 lines
drivers/cxl/core/hdm_state.c +12 -0
+{
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	if (pdev->hdm && pdev->hdm->decoder_count != count) {
+		pci_warn(pdev,
+			 "CXL HDM cache decoder count mismatch: cached=%d hdm=%d\n",
+			 pdev->hdm->decoder_count, count);
+		return -ENXIO;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_check_decoder_count, "cxl_core");

kdoc header for exported symbol. Also are you sure this symbol needs to be exported?

DJ

Quoted 126 lines
drivers/cxl/core/pci.c +24 -0
index f72cd8f50e77..5272013548c7 100644
@@ -6,6 +6,7 @@
 #include <linux/delay.h>
 #include <linux/pci.h>
 #include <linux/pci-doe.h>
+#include <cxl/hdm.h>
 #include <cxl/pci.h>
 #include <linux/aer.h>
 #include <cxlpci.h>
@@ -180,6 +181,29 @@ int cxl_await_media_ready(struct cxl_dev_state *cxlds)
 }
 EXPORT_SYMBOL_NS_GPL(cxl_await_media_ready, "CXL");
 
+/**
+ * cxl_hdm_check_decoder_count() - check enumeration against the PCI HDM cache
+ * @cxlhdm: HDM capability containing the decoder count to check
+ *
+ * Take cxl_rwsem.dpa for read while comparing the cached count. Call only
+ * for hardware HDM decoders, since DVSEC-emulated ranges do not describe
+ * the HDM registers represented by the cache.
+ *
+ * Return: 0 if the counts match or no upstream PCI device or cache exists,
+ * or -ENXIO if the cached and enumerated decoder counts differ.
+ */
+int cxl_hdm_check_decoder_count(struct cxl_hdm *cxlhdm)
+{
+	struct pci_dev *pdev __free(pci_dev_put) =
+		cxl_port_get_uport_pci_dev(cxlhdm->port);
+
+	if (!pdev)
+		return 0;
+
+	return cxl_hdm_cache_check_decoder_count(pdev, cxlhdm->decoder_count);
+}
+EXPORT_SYMBOL_NS_GPL(cxl_hdm_check_decoder_count, "CXL");
+
 static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)
 {
 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
include/cxl/cxl.h +1 -0
index 6d6e564be27a..341a7c52894a 100644
@@ -26,6 +26,7 @@ enum cxl_devtype {
 };
 
 struct cxl_region;
+struct cxl_hdm_info;
 
 enum cxl_decoder_type {
 	CXL_DECODER_DEVMEM = 2,
include/cxl/hdm.h +32 -0
index 219b9bb67440..06e9aa4479c2 100644
@@ -6,6 +6,9 @@
 #include <linux/types.h>
 #include <cxl/cxl.h>
 
+struct pci_dev;
+struct cxl_endpoint_decoder;
+
 /**
  * struct cxl_endpoint_decoder_settings - endpoint HDM decoder programming
  * @config: common decoder configuration
@@ -16,4 +19,33 @@ struct cxl_endpoint_decoder_settings {
 	u64 skip;
 };
 
+/**
+ * struct cxl_hdm_info - cached CXL HDM state for a PCI device
+ * @decoder_count: number of entries in @settings
+ * @hdm_bar: PCI BAR containing the HDM decoder capability
+ * @hdm_offset: offset of the HDM decoder capability in @hdm_bar
+ * @hdm_size: size of the HDM decoder register block
+ * @global_ctrl: HDM decoder global control register
+ * @dvsec_ctrl: CXL DVSEC control register
+ * @dvsec_ctrl_valid: whether @dvsec_ctrl contains valid state
+ * @settings: per-endpoint-decoder programming state
+ *
+ * Publication through pci_dev.hdm and all mutable fields are protected by
+ * cxl_rwsem.dpa.
+ */
+struct cxl_hdm_info {
+	int decoder_count;
+	int hdm_bar;
+	resource_size_t hdm_offset;
+	resource_size_t hdm_size;
+	u32 global_ctrl;
+	u16 dvsec_ctrl;
+	bool dvsec_ctrl_valid;
+	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
+};
+
+void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
+				   struct cxl_endpoint_decoder *cxled);
+int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+
 #endif /* __CXL_HDM_H__ */
include/linux/pci.h +6 -0
index d31a8d107b1e..7bb37fcb556d 100644
@@ -339,6 +339,9 @@ struct pcie_link_state;
 struct pci_sriov;
 struct pci_p2pdma;
 struct rcec_ea;
+#ifdef CONFIG_CXL_RESET
+struct cxl_hdm_info;
+#endif
 
 /* struct pci_dev - describes a PCI device
  *
@@ -566,6 +569,9 @@ struct pci_dev {
 #ifdef CONFIG_PCI_DOE
 	struct xarray	doe_mbs;	/* Data Object Exchange mailboxes */
 #endif
+#ifdef CONFIG_CXL_RESET
+	struct cxl_hdm_info *hdm;	/* CXL HDM decoder state */
+#endif
 #ifdef CONFIG_PCI_NPEM
 	struct npem	*npem;		/* Native PCIe Enclosure Management */
 #endif
maintainer
#6 lore raw

Re: [PATCH v17 02/19] cxl: Share CXL port upstream PCI device lookup

In reply to Li Ming
Quoted 90 lines · Li Ming
Quoted 15 lines · Srirangan Madhavan

read_cdat_data() resolves a CXL port's upstream device to its backing PCI device. HDM cache updates need the same mapping.

Factor the lookup into cxl_port_get_uport_pci_dev() and return a referenced PCI device to make caller ownership explicit.

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

Quoted 6 lines

---
Changes in v17:
- Use an explicit pci_dev_put() on a single exit path in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko)
   https://sashiko.dev/#/patchset/[email protected]?part=2

I still think the new goto makes the code harder to follow. But I saw your discussion in v13[1], both Jonathan and Dave agree with your current changes. I post my proposal here which can eliminate all goto labels. If there is no response from them, or if they disagree with my changes, we can continue with your implementation.

[1]: https://lore.kernel.org/all/[email protected]/

drivers/cxl/core/pci.c +16 -17
index 9d807c1a002c..fbf4b56a39c4 100644
@@ -573,17 +573,8 @@ void read_cdat_data(struct cxl_port *port)
         size_t table_length, length;
         int rc;
 
-       if (is_cxl_memdev(uport)) {
-               struct device *host;
-
-               cxlmd = to_cxl_memdev(uport);
-               host = cxlmd->dev.parent;
-               if (dev_is_pci(host))
-                       pdev = to_pci_dev(host);
-       } else if (dev_is_pci(uport)) {
-               pdev = to_pci_dev(uport);
-       }
-
+       struct pci_dev *pdev __free(pci_dev_put) =
+                               cxl_port_get_uport_pci_dev(port);
         if (!pdev)
                 return;
 
@@ -606,30 +597,32 @@ void read_cdat_data(struct cxl_port *port)
          * bytes for the DOE header. Table data starts afterwards.
          */
         buf = devm_kzalloc(dev, sizeof(*buf) + length, GFP_KERNEL);
-       if (!buf)
-               goto err;
+       if (!buf) {
+               dev_err(dev, "Failed to allocate CDAT buffer.\n");
+               return;
+       }
 
         table_length = length;
 
         rc = cxl_cdat_read_table(dev, doe_mb, buf, &length);
-       if (rc)
-               goto err;
+       if (rc) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to read CDAT.\n");
+               return;
+       }
 
         if (table_length != length)
                 dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
                         table_length, length);
 
-       if (cdat_checksum(buf->data, length))
-               goto err;
+       if (cdat_checksum(buf->data, length)) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to validate CDAT.\n");
+               return;
+       }
 
         port->cdat.table = buf->data;

drivers/cxl/core/pci.c void read_cdat_data(struct cxl_port *port) · line 628

Quoted 10 lines
drivers/cxl/core/pci.c +0 -6
         port->cdat.length = length;
-
-       return;
-err:
-       /* Don't leave table data allocated on error */
-       devm_kfree(dev, buf);
-       dev_err(dev, "Failed to read/validate CDAT.\n");
  }
 
 

How about something like this? I think it's cleaner:

drivers/cxl/core/pci.c +32 -27
index 905892cfedef..c924904faec4 100644
@@ -556,6 +556,27 @@ static unsigned char cdat_checksum(void *buf, size_t size)
 	return sum;
 }
 
+static int cxl_cdat_read_validate(struct device *dev,
+				  struct pci_doe_mb *doe_mb,
+				  struct cdat_doe_rsp *buf, size_t *length)
+{
+	size_t table_length = *length;
+	int rc;
+
+	rc = cxl_cdat_read_table(dev, doe_mb, buf, length);
+	if (rc)
+		return rc;
+
+	if (table_length != *length)
+		dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
+			 table_length, *length);
+
+	if (cdat_checksum(buf->data, *length))
+		return -EIO;
+
+	return 0;
+}
+
 /**
  * read_cdat_data - Read the CDAT data on this port
  * @port: Port to read data from
@@ -564,13 +585,13 @@ static unsigned char cdat_checksum(void *buf, size_t size)
  */
 void read_cdat_data(struct cxl_port *port)
 {
-	struct pci_dev *pdev = cxl_port_get_uport_pci_dev(port);
 	struct device *dev = &port->dev;
 	struct pci_doe_mb *doe_mb;
 	struct cdat_doe_rsp *buf;
-	size_t table_length, length;
-	int rc;
+	size_t length;
 
+	struct pci_dev *pdev __free(pci_dev_put) =
+		cxl_port_get_uport_pci_dev(port);
 	if (!pdev)
 		return;
 
@@ -578,14 +599,14 @@ void read_cdat_data(struct cxl_port *port)
 				      CXL_DOE_PROTOCOL_TABLE_ACCESS);
 	if (!doe_mb) {
 		dev_dbg(dev, "No CDAT mailbox\n");
-		goto out;
+		return;
 	}
 
 	port->cdat_available = true;
 
 	if (cxl_cdat_get_length(dev, doe_mb, &length)) {
 		dev_dbg(dev, "No CDAT length\n");
-		goto out;
+		return;
 	}
 
 	/*
@@ -593,31 +614,15 @@ void read_cdat_data(struct cxl_port *port)
 	 * bytes for the DOE header. Table data starts afterwards.
 	 */
 	buf = devm_kzalloc(dev, sizeof(*buf) + length, GFP_KERNEL);
-	if (!buf)
-		goto err;
-
-	table_length = length;
-
-	rc = cxl_cdat_read_table(dev, doe_mb, buf, &length);
-	if (rc)
-		goto err;
-
-	if (table_length != length)
-		dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
-			table_length, length);
-
-	if (cdat_checksum(buf->data, length))
-		goto err;
+	if (!buf || cxl_cdat_read_validate(dev, doe_mb, buf, &length)) {
+		/* Don't leave table data allocated on error */
+		devm_kfree(dev, buf);
+		dev_err(dev, "Failed to read/validate CDAT.\n");
+		return;
+	}
 
 	port->cdat.table = buf->data;
 	port->cdat.length = length;
-	goto out;
-err:
-	/* Don't leave table data allocated on error */
-	devm_kfree(dev, buf);
-	dev_err(dev, "Failed to read/validate CDAT.\n");
-out:
-	pci_dev_put(pdev);
 }
 EXPORT_SYMBOL_NS_GPL(read_cdat_data, "CXL");
maintainer
#53 lore raw

Re: [PATCH v17 17/19] PCI/CXL: Restore CXL state after CXL bus reset

In reply to Srirangan Madhavan
Quoted 49 lines · Srirangan Madhavan

CXL bus reset can clear HDM decoder programming and CXL Device DVSEC control state. Restore the cached state after a successful cxl_bus reset while IOMMU exclusion remains active.

Restore PCI configuration first so HDM MMIO is accessible, and preserve a disabled state if restoration fails.

Copy the cached state before the reset, then refresh its decoder settings from the cache under the CXL region quiesce once the reset completes. A region decommit during the reset updates the cache, and restoring the earlier decoders would leave the endpoint decoding an HPA range that the CXL core considers free. Keep global and DVSEC control from before the reset, since a refresh during the reset can read them as all-ones.

The prepare/restore interface and decoder-refresh structure follow Dave Jiang's cxl-type2-reset reference branch.

---
Changes in v17:
- Enable bus mastering only after the IOMMU is restored, via a separate cxl_restore_command_after_pci_reset() step (Richard)
https://lore.kernel.org/linux-cxl/auRhJa-nzR0CnKf3@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b93f0c8e67b198a63786fd3721b7177ab9df60be

---
 drivers/cxl/core/hdm_state.c | 31 +++++++++++++
 drivers/pci/cxl.c            | 85 ++++++++++++++++++++++++++++++++++++
 drivers/pci/pci.c            | 14 ++++++
 drivers/pci/pci.h            | 24 ++++++++++
 include/cxl/hdm.h            |  2 +
 5 files changed, 156 insertions(+)
drivers/cxl/core/hdm_state.c +5 -0
index 51df56377f7a..7e0903ce0b78 100644
@@ -182,6 +182,37 @@ struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot)
 	return copy;
 }
 
+/**
+ * cxl_hdm_cache_copy_decoders() - refresh the decoders of a snapshot
+ * @slot: cache pointer owned by the device
+ * @dst: snapshot of the same device from cxl_hdm_cache_snapshot()
+ *

drivers/cxl/core/hdm_state.c struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot) · line 199

Quoted 10 lines
drivers/cxl/core/hdm_state.c +10 -0
+ * Copy only the per-decoder settings, which region commit and teardown keep
+ * current. Leave the rest of @dst, including global and DVSEC control, as
+ * captured: a refresh during a reset may have read those registers from a
+ * device that returned all-ones.
+ *
+ * Return: 0 on success, -ENXIO when nothing is published, or -EINVAL when
+ * @dst holds a different number of decoders.
+ */
+int cxl_hdm_cache_copy_decoders(struct cxl_hdm_info *const *slot,
+				struct cxl_hdm_info *dst)

I think this function is a dead function for the series. By the end, nothing calls it.

DJ

Quoted 216 lines
drivers/cxl/core/hdm_state.c +16 -0
+{
+	struct cxl_hdm_info *info;
+
+	lockdep_assert_held_write(&cxl_rwsem.region);
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	info = *slot;
+	if (!info)
+		return -ENXIO;
+	if (info->decoder_count != dst->decoder_count)
+		return -EINVAL;
+
+	memcpy(dst->settings, info->settings,
+	       flex_array_size(info, settings, info->decoder_count));
+	return 0;
+}
+
 void cxl_region_quiesce_lock(void)
 	__acquires(cxl_region_quiesce)
 	__context_unsafe(token maps to cxl_rwsem.region)
drivers/pci/cxl.c +85 -0
index c68b08f7f95b..a9aa2e1c631d 100644
@@ -393,6 +393,91 @@ static int pci_cxl_restore_state(struct pci_dev *pdev,
 	return cxl_restore_state(pdev, snapshot);
 }
 
+/**
+ * pci_cxl_reset_prepare() - allocate HDM state storage ahead of a bus reset
+ * @pdev: device about to be reset
+ *
+ * Copy the cached HDM state before the reset, so that restoring cannot fail
+ * for lack of memory. The decoder settings are refreshed when the state is
+ * restored.
+ *
+ * Return: storage for cxl_restore_state_after_pci_reset(), to be freed with
+ * kfree(); NULL when @pdev has no cached HDM state; or an ERR_PTR() on
+ * failure.
+ */
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev)
+{
+	struct cxl_hdm_info *snapshot;
+
+	device_lock_assert(&pdev->dev);
+	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
+	if (IS_ERR(snapshot))
+		return PTR_ERR(snapshot) == -ENXIO ? NULL : snapshot;
+
+	/* Raw reset callers may not have saved the PCI state needed for restore. */
+	if (!pdev->state_saved) {
+		pci_err(pdev, "CXL bus reset requires saved PCI state\n");
+		kfree(snapshot);
+		return ERR_PTR(-EINVAL);
+	}
+
+	return snapshot;
+}
+
+/**
+ * cxl_restore_state_after_pci_reset() - restore CXL state after a bus reset
+ * @pdev: device that was reset
+ * @snapshot: storage from pci_cxl_reset_prepare()
+ * @command: returns the saved PCI_COMMAND value to apply once the IOMMU is
+ *	     restored
+ *
+ * Under the region quiesce, refresh the decoder settings in @snapshot from the
+ * cache and restore: first the PCI configuration needed to reach HDM MMIO,
+ * then the HDM decoder and CXL Device DVSEC state. Leave @pdev disabled on
+ * failure.
+ *
+ * Bus mastering stays off, because the caller has not yet restored IOMMU
+ * translation and a DMA request now would hit the blocking domain. The caller
+ * calls cxl_restore_command_after_pci_reset() once the IOMMU is restored.
+ *
+ * Refresh the decoders now rather than rely on the copy taken before the
+ * reset: a region commit or teardown during the reset has updated the cache,
+ * and restoring older decoders would leave the device decoding ranges the
+ * CXL core considers free.
+ */
+int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
+				      struct cxl_hdm_info *snapshot,
+				      u16 *command)
+{
+	int rc;
+
+	device_lock_assert(&pdev->dev);
+	cxl_region_quiesce_lock();
+
+	rc = cxl_hdm_cache_copy_decoders(&pdev->hdm, snapshot);
+	if (!rc)
+		rc = pci_cxl_restore_state(pdev, snapshot, command);
+	if (rc)
+		cxl_reset_save_disabled_state(pdev);
+
+	cxl_region_quiesce_unlock();
+	return rc;
+}
+
+/**
+ * cxl_restore_command_after_pci_reset() - re-enable the device after a bus reset
+ * @pdev: device that was reset
+ * @command: PCI_COMMAND value from cxl_restore_state_after_pci_reset()
+ *
+ * Call after the IOMMU is restored: this can enable bus mastering. Save the
+ * restored PCI state, and leave @pdev disabled on failure.
+ */
+int cxl_restore_command_after_pci_reset(struct pci_dev *pdev, u16 command)
+{
+	device_lock_assert(&pdev->dev);
+	return cxl_reset_save_restored_state(pdev, command);
+}
+
 /*
  * CXL r4.0 sec 9.7.2 defines the reset completion timeout encodings.
  * Sec 9.7.3 leaves config-space access behavior undefined for 100 ms after
drivers/pci/pci.c +14 -0
index 426b5ee38d04..1d4ba90a6976 100644
@@ -5014,8 +5014,10 @@ static int pci_reset_bus_function(struct pci_dev *dev, bool probe)
 
 static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 {
+	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
 	struct pci_dev *bridge;
 	u16 dvsec, reg, val;
+	u16 command;
 	int rc;
 
 	/*
@@ -5040,6 +5042,10 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 	if (rc)
 		return -ENOTTY;
 
+	snapshot = pci_cxl_reset_prepare(dev);
+	if (IS_ERR(snapshot))
+		return PTR_ERR(snapshot);
+
 	rc = pci_dev_reset_iommu_prepare(dev);
 	if (rc) {
 		pci_err(dev, "failed to stop IOMMU for a PCI reset: %d\n", rc);
@@ -5060,7 +5066,15 @@ static int cxl_reset_bus_function(struct pci_dev *dev, bool probe)
 		pci_write_config_word(bridge, dvsec + PCI_DVSEC_CXL_PORT_CTL,
 				      reg);
 
+	if (!rc && snapshot)
+		rc = cxl_restore_state_after_pci_reset(dev, snapshot, &command);
+
 	pci_dev_reset_iommu_done(dev);
+
+	/* Enable bus mastering only once the IOMMU translates again. */
+	if (!rc && snapshot)
+		rc = cxl_restore_command_after_pci_reset(dev, command);
+
 	return rc;
 }
 
drivers/pci/pci.h +24 -0
index 743e65abd758..2f819e1fbead 100644
@@ -730,10 +730,16 @@ static inline void pci_doe_destroy(struct pci_dev *pdev) { }
 static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #endif
 
+struct cxl_hdm_info;
 #ifdef CONFIG_CXL_RESET
 void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
 void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
 int cxl_reset_function(struct pci_dev *pdev, bool probe);
+struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev);
+int cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
+				      struct cxl_hdm_info *snapshot,
+				      u16 *command);
+int cxl_restore_command_after_pci_reset(struct pci_dev *pdev, u16 command);
 #else
 static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
 static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
@@ -741,6 +747,24 @@ static inline int cxl_reset_function(struct pci_dev *pdev, bool probe)
 {
 	return -ENOTTY;
 }
+
+static inline struct cxl_hdm_info *pci_cxl_reset_prepare(struct pci_dev *pdev)
+{
+	return NULL;
+}
+
+static inline int
+cxl_restore_state_after_pci_reset(struct pci_dev *pdev,
+				  struct cxl_hdm_info *snapshot, u16 *command)
+{
+	return 0;
+}
+
+static inline int cxl_restore_command_after_pci_reset(struct pci_dev *pdev,
+						      u16 command)
+{
+	return 0;
+}
 #endif
 
 #ifdef CONFIG_PCI_NPEM
include/cxl/hdm.h +2 -0
index 94a8f8a1a65a..81767f21052a 100644
@@ -64,6 +64,8 @@ void cxl_hdm_cache_set_normalized(struct pci_dev *pdev, int id);
 void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
 bool cxl_hdm_cache_dvsec_decode(struct cxl_hdm_info *const *slot);
 struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot);
+int cxl_hdm_cache_copy_decoders(struct cxl_hdm_info *const *slot,
+				struct cxl_hdm_info *dst);
 
 /*
  * Region quiesce blocks CXL region commit and teardown, and with them decoder
maintainer
#27 lore raw

Re: [PATCH v17 10/19] cxl: Build register block helpers into the kernel

In reply to Srirangan Madhavan
Quoted 6 lines · Srirangan Madhavan

Build register discovery with the built-in HDM helpers so PCI enumeration can use it even when cxl_core is modular. Export the interfaces used by cxl_core and preserve the BAR and offset in the register map.

This patch does what the first sentence claims, but then a bunch of misc stuff tagged along with it. Please keep commits to one logical change per commit.

Move the bar and bar_offset changes to when they are needed.

Move cxl_dvsec_hdm_count_valid() to where it's being used.

the 'struct pci_dev' forward declare, is this needed?

Also the exports can use EXPORT_SYMBOL_FOR_MODULES(..., "cxl_core") I think?

DJ

Quoted 173 lines
---
 drivers/cxl/core/Makefile |  3 +--
 drivers/cxl/core/regs.c   |  9 +++++++++
 drivers/cxl/cxl.h         |  3 ---
 include/cxl/cxl.h         |  5 +++++
 include/cxl/pci.h         | 13 +++++++++++++
 tools/testing/cxl/Kbuild  |  1 -
 6 files changed, 28 insertions(+), 6 deletions(-)
drivers/cxl/core/Makefile +1 -2
index 9971efb237fb..9a77e68d44ce 100644
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CXL_BUS) += cxl_core.o
-obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o
+obj-$(subst m,y,$(CONFIG_CXL_BUS)) += hdm_regs.o hdm_state.o regs.o
 obj-$(CONFIG_CXL_SUSPEND) += suspend.o
 
 ccflags-y += -I$(srctree)/drivers/cxl
@@ -8,7 +8,6 @@ CFLAGS_trace.o = -DTRACE_INCLUDE_PATH=. -I$(src)
 
 cxl_core-y := port.o
 cxl_core-y += pmem.o
-cxl_core-y += regs.o
 cxl_core-y += memdev.o
 cxl_core-y += mbox.o
 cxl_core-y += pci.o
drivers/cxl/core/regs.c +9 -0
index 20c2d9fbcfe7..def3c20d1a7a 100644
@@ -200,6 +200,7 @@ void __iomem *devm_cxl_iomap_block(struct device *dev, resource_size_t addr,
 
 	return ret_val;
 }
+EXPORT_SYMBOL_FOR_MODULES(devm_cxl_iomap_block, "cxl_core");
 
 int cxl_map_component_regs(const struct cxl_register_map *map,
 			   struct cxl_component_regs *regs,
@@ -285,6 +286,8 @@ static bool cxl_decode_regblock(struct pci_dev *pdev, u32 reg_lo, u32 reg_hi,
 	}
 
 	map->reg_type = reg_type;
+	map->bar = bar;
+	map->bar_offset = offset;
 	map->resource = pci_resource_start(pdev, bar) + offset;
 	map->max_size = pci_resource_len(pdev, bar) - offset;
 	return true;
@@ -309,6 +312,7 @@ static int __cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_ty
 	*map = (struct cxl_register_map) {
 		.host = &pdev->dev,
 		.resource = CXL_RESOURCE_NONE,
+		.bar = -1,
 	};
 
 	regloc = pci_find_dvsec_capability(pdev, PCI_VENDOR_ID_CXL,
@@ -339,6 +343,8 @@ static int __cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_ty
 	}
 
 	map->resource = CXL_RESOURCE_NONE;
+	map->bar = -1;
+	map->bar_offset = 0;
 	if (index == CXL_INSTANCES_COUNT)
 		return instance;
 
@@ -518,6 +524,7 @@ u16 cxl_rcrb_to_aer(struct device *dev, resource_size_t rcrb)
 
 	return offset;
 }
+EXPORT_SYMBOL_NS_GPL(cxl_rcrb_to_aer, "CXL");
 
 static resource_size_t cxl_rcrb_to_linkcap(struct device *dev, struct cxl_dport *dport)
 {
@@ -634,6 +641,7 @@ resource_size_t __rcrb_to_component(struct device *dev, struct cxl_rcrb_info *ri
 
 	return component_reg_phys;
 }
+EXPORT_SYMBOL_NS_GPL(__rcrb_to_component, "CXL");
 
 resource_size_t cxl_rcd_component_reg_phys(struct device *dev,
 					   struct cxl_dport *dport)
@@ -642,3 +650,4 @@ resource_size_t cxl_rcd_component_reg_phys(struct device *dev,
 		return CXL_RESOURCE_NONE;
 	return __rcrb_to_component(dev, &dport->rcrb, CXL_RCRB_UPSTREAM);
 }
+EXPORT_SYMBOL_NS_GPL(cxl_rcd_component_reg_phys, "CXL");
drivers/cxl/cxl.h +0 -3
index 688350c7c5fb..ad4e80be2bd7 100644
@@ -239,9 +239,6 @@ enum cxl_regloc_type;
 int cxl_count_regblock(struct pci_dev *pdev, enum cxl_regloc_type type);
 int cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_type type,
 			       struct cxl_register_map *map, unsigned int index);
-int cxl_find_regblock(struct pci_dev *pdev, enum cxl_regloc_type type,
-		      struct cxl_register_map *map);
-int cxl_setup_regs(struct cxl_register_map *map);
 struct cxl_dport;
 int cxl_dport_map_rcd_linkcap(struct pci_dev *pdev, struct cxl_dport *dport);
 
include/cxl/cxl.h +5 -0
index 341a7c52894a..ea23bc15d00e 100644
@@ -27,6 +27,7 @@ enum cxl_devtype {
 
 struct cxl_region;
 struct cxl_hdm_info;
+struct pci_dev;
 
 enum cxl_decoder_type {
 	CXL_DECODER_DEVMEM = 2,
@@ -150,6 +151,8 @@ struct cxl_pmu_reg_map {
  * @base: virtual base of the register-block-BAR + @block_offset
  * @resource: physical resource base of the register block
  * @max_size: maximum mapping size to perform register search
+ * @bar: PCI BAR containing the register block
+ * @bar_offset: register block offset relative to @bar
  * @reg_type: see enum cxl_regloc_type
  * @component_map: cxl_reg_map for component registers
  * @device_map: cxl_reg_maps for device registers
@@ -160,6 +163,8 @@ struct cxl_register_map {
 	void __iomem *base;
 	resource_size_t resource;
 	resource_size_t max_size;
+	int bar;
+	resource_size_t bar_offset;
 	u8 reg_type;
 	union {
 		struct cxl_component_reg_map component_map;
include/cxl/pci.h +13 -0
index 3e0000015871..b15d7e415e27 100644
@@ -4,6 +4,8 @@
 #ifndef __CXL_CXL_PCI_H__
 #define __CXL_CXL_PCI_H__
 
+#include <linux/types.h>
+
 /* Register Block Identifier (RBI) */
 enum cxl_regloc_type {
 	CXL_REGLOC_RBI_EMPTY = 0,
@@ -19,4 +21,15 @@ struct pci_dev;
 
 int cxl_pci_setup_regs(struct pci_dev *pdev, enum cxl_regloc_type type,
 		       struct cxl_register_map *map);
+int cxl_find_regblock(struct pci_dev *pdev, enum cxl_regloc_type type,
+		      struct cxl_register_map *map);
+int cxl_setup_regs(struct cxl_register_map *map);
+/*
+ * CXL r4.0 sec 8.1.3.1: a CXL.mem capable device reports one or two HDM
+ * ranges. 00b is illegal when Mem_Capable is set and 11b is reserved.
+ */
+static inline bool cxl_dvsec_hdm_count_valid(unsigned int hdm_count)
+{
+	return hdm_count == 1 || hdm_count == 2;
+}
 #endif
tools/testing/cxl/Kbuild +0 -1
index 2be1df80fcc9..e80500f457a9 100644
@@ -55,7 +55,6 @@ obj-m += cxl_core.o
 
 cxl_core-y := $(CXL_CORE_SRC)/port.o
 cxl_core-y += $(CXL_CORE_SRC)/pmem.o
-cxl_core-y += $(CXL_CORE_SRC)/regs.o
 cxl_core-y += $(CXL_CORE_SRC)/memdev.o
 cxl_core-y += $(CXL_CORE_SRC)/mbox.o
 cxl_core-y += $(CXL_CORE_SRC)/pci.o
reviewer
#7 lore raw

Re: [PATCH v17 02/19] cxl: Share CXL port upstream PCI device lookup

In reply to Dave Jiang
Quoted 89 lines · Dave Jiang
Quoted 87 lines · Li Ming
Quoted 15 lines · Srirangan Madhavan

read_cdat_data() resolves a CXL port's upstream device to its backing PCI device. HDM cache updates need the same mapping.

Factor the lookup into cxl_port_get_uport_pci_dev() and return a referenced PCI device to make caller ownership explicit.

Use automatic reference cleanup in read_cdat_data(), as suggested by Li Ming, so early returns release the PCI device reference.

Quoted 6 lines

---
Changes in v17:
- Use an explicit pci_dev_put() on a single exit path in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko)
   https://sashiko.dev/#/patchset/[email protected]?part=2

I still think the new goto makes the code harder to follow. But I saw your discussion in v13[1], both Jonathan and Dave agree with your current changes. I post my proposal here which can eliminate all goto labels. If there is no response from them, or if they disagree with my changes, we can continue with your implementation.

[1]: https://lore.kernel.org/all/[email protected]/

drivers/cxl/core/pci.c +16 -17
index 9d807c1a002c..fbf4b56a39c4 100644
@@ -573,17 +573,8 @@ void read_cdat_data(struct cxl_port *port)
         size_t table_length, length;
         int rc;
 
-       if (is_cxl_memdev(uport)) {
-               struct device *host;
-
-               cxlmd = to_cxl_memdev(uport);
-               host = cxlmd->dev.parent;
-               if (dev_is_pci(host))
-                       pdev = to_pci_dev(host);
-       } else if (dev_is_pci(uport)) {
-               pdev = to_pci_dev(uport);
-       }
-
+       struct pci_dev *pdev __free(pci_dev_put) =
+                               cxl_port_get_uport_pci_dev(port);
         if (!pdev)
                 return;
 
@@ -606,30 +597,32 @@ void read_cdat_data(struct cxl_port *port)
          * bytes for the DOE header. Table data starts afterwards.
          */
         buf = devm_kzalloc(dev, sizeof(*buf) + length, GFP_KERNEL);
-       if (!buf)
-               goto err;
+       if (!buf) {
+               dev_err(dev, "Failed to allocate CDAT buffer.\n");
+               return;
+       }
 
         table_length = length;
 
         rc = cxl_cdat_read_table(dev, doe_mb, buf, &length);
-       if (rc)
-               goto err;
+       if (rc) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to read CDAT.\n");
+               return;
+       }
 
         if (table_length != length)
                 dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
                         table_length, length);
 
-       if (cdat_checksum(buf->data, length))
-               goto err;
+       if (cdat_checksum(buf->data, length)) {
+               devm_kfree(dev, buf);
+               dev_err(dev, "Failed to validate CDAT.\n");
+               return;
+       }
 
Quoted 12 lines

drivers/cxl/core/pci.c void read_cdat_data(struct cxl_port *port)

Quoted 11 lines
drivers/cxl/core/pci.c +0 -6
         port->cdat.table = buf->data;
         port->cdat.length = length;
-
-       return;
-err:
-       /* Don't leave table data allocated on error */
-       devm_kfree(dev, buf);
-       dev_err(dev, "Failed to read/validate CDAT.\n");
  }
 
 

How about something like this? I think it's cleaner:

Hi Dave,

Your implementation also works for me.

Ming

Quoted 104 lines
drivers/cxl/core/pci.c +32 -27
index 905892cfedef..c924904faec4 100644
@@ -556,6 +556,27 @@ static unsigned char cdat_checksum(void *buf, size_t size)
 	return sum;
 }
 
+static int cxl_cdat_read_validate(struct device *dev,
+				  struct pci_doe_mb *doe_mb,
+				  struct cdat_doe_rsp *buf, size_t *length)
+{
+	size_t table_length = *length;
+	int rc;
+
+	rc = cxl_cdat_read_table(dev, doe_mb, buf, length);
+	if (rc)
+		return rc;
+
+	if (table_length != *length)
+		dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
+			 table_length, *length);
+
+	if (cdat_checksum(buf->data, *length))
+		return -EIO;
+
+	return 0;
+}
+
 /**
  * read_cdat_data - Read the CDAT data on this port
  * @port: Port to read data from
@@ -564,13 +585,13 @@ static unsigned char cdat_checksum(void *buf, size_t size)
  */
 void read_cdat_data(struct cxl_port *port)
 {
-	struct pci_dev *pdev = cxl_port_get_uport_pci_dev(port);
 	struct device *dev = &port->dev;
 	struct pci_doe_mb *doe_mb;
 	struct cdat_doe_rsp *buf;
-	size_t table_length, length;
-	int rc;
+	size_t length;
 
+	struct pci_dev *pdev __free(pci_dev_put) =
+		cxl_port_get_uport_pci_dev(port);
 	if (!pdev)
 		return;
 
@@ -578,14 +599,14 @@ void read_cdat_data(struct cxl_port *port)
 				      CXL_DOE_PROTOCOL_TABLE_ACCESS);
 	if (!doe_mb) {
 		dev_dbg(dev, "No CDAT mailbox\n");
-		goto out;
+		return;
 	}
 
 	port->cdat_available = true;
 
 	if (cxl_cdat_get_length(dev, doe_mb, &length)) {
 		dev_dbg(dev, "No CDAT length\n");
-		goto out;
+		return;
 	}
 
 	/*
@@ -593,31 +614,15 @@ void read_cdat_data(struct cxl_port *port)
 	 * bytes for the DOE header. Table data starts afterwards.
 	 */
 	buf = devm_kzalloc(dev, sizeof(*buf) + length, GFP_KERNEL);
-	if (!buf)
-		goto err;
-
-	table_length = length;
-
-	rc = cxl_cdat_read_table(dev, doe_mb, buf, &length);
-	if (rc)
-		goto err;
-
-	if (table_length != length)
-		dev_warn(dev, "Malformed CDAT table length (%zu:%zu), discarding trailing data\n",
-			table_length, length);
-
-	if (cdat_checksum(buf->data, length))
-		goto err;
+	if (!buf || cxl_cdat_read_validate(dev, doe_mb, buf, &length)) {
+		/* Don't leave table data allocated on error */
+		devm_kfree(dev, buf);
+		dev_err(dev, "Failed to read/validate CDAT.\n");
+		return;
+	}
 
 	port->cdat.table = buf->data;
 	port->cdat.length = length;
-	goto out;
-err:
-	/* Don't leave table data allocated on error */
-	devm_kfree(dev, buf);
-	dev_err(dev, "Failed to read/validate CDAT.\n");
-out:
-	pci_dev_put(pdev);
 }
 EXPORT_SYMBOL_NS_GPL(read_cdat_data, "CXL");
maintainer
#59 lore raw
In reply to Srirangan Madhavan
Quoted 34 lines · Srirangan Madhavan

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

    /sys/bus/pci/devices/.../reset_method
    /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

Quoted 3 lines

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

I think holding it across the bus reset can deadlock with pciehp and a PCI remove. I tested in QEMU with two cxl-type2 devices from Manish's RFC [1].

For a device in a pciehp slot, pci_reset_bus_function() ends up in pciehp_reset_slot(), which takes the slot's reset_lock. The reset still holds cxl_rwsem.region at that point.

Two other tasks can complete a cycle. pciehp_ist() for that slot can hold reset_lock and wait for pci_rescan_remove_lock in pciehp_unconfigure_device(). A PCI remove of a second Type 2 device can hold pci_rescan_remove_lock while cxl_decoder_detach() waits for cxl_rwsem.region.

On v17 as posted, lockdep reports the cycle:

  [   60.891789] WARNING: possible circular locking dependency detected
  [   60.893014] irq/24-pciehp/103 is trying to acquire lock:
  [   60.893367] ffff888072b4f128 (&cxl_memdev_key){+.+.}-{4:4}, at: device_del+0x8d/0x580
                 but task is already holding lock:
  [   60.894498] ffffffff84699e80 (pci_rescan_remove_lock){+.+.}-{4:4}, at: pciehp_unconfigure_device+0x93/0x210
  [...]
                 -> #3 (&ctrl->reset_lock){++++}-{4:4}:
  [   60.916794]        down_write_nested+0x80/0x170
  [   60.917826]        pciehp_reset_slot+0x6c/0xc0
  [   60.918893]        pci_reset_hotplug_slot+0x5c/0x90
  [   60.919928]        pci_reset_bus_function+0x161/0x330
  [   60.920951]        cxl_reset_bus_function+0x1c6/0x280
  [   60.921958]        __pci_reset_function_locked+0x96/0x170
  [   60.922990]        pci_reset_function+0xc8/0x180
  [   60.923977]        reset_store+0x84/0xd0
  [...]
                 -> #2 (cxl_rwsem.region){++++}-{4:4}:
  [...]
  [   61.013490] Chain exists of:
                   &cxl_memdev_key --> &ctrl->reset_lock --> pci_rescan_remove_lock

With a test-only msleep() after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(), it turns into a real hang. The reset, a sysfs remove of the second device and a power off of the first device's slot all got stuck.

Two region reads blocked behind the reset as well. A read of region1/commit timed out after 5 s, and cxl list -R stayed in D state in decoders_committed_show().

To reproduce, I used Manish's RFC as posted. It allows one cxl-type2 per pxb-cxl, so each device has its own host bridge and window. On q35 with cxl=on, plus the memory backends:

-device pxb-cxl,id=cxl.0,bus=pcie.0,bus_nr=53
-device cxl-rp,id=hb0rp0,bus=cxl.0,chassis=0,slot=0,port=0
-device cxl-type2,bus=hb0rp0,volatile-memdev=t2mem0,id=cxl-t2,fmw-index=0 -device pxb-cxl,id=cxl.1,bus=pcie.0,bus_nr=191
-device cxl-rp,id=hb1rp0,bus=cxl.1,chassis=0,slot=2,port=0
-device cxl-type2,bus=hb1rp0,volatile-memdev=t2mem1,id=cxl-t2b,fmw-index=1 -M cxl-fmw.0.targets.0=cxl.0,cxl-fmw.0.size=4G,cxl-fmw.1.targets.0=cxl.1,cxl-fmw.1.size=4G

The guest kernel needs CONFIG_CXL_REGION_INVALIDATION_TEST=y. Without it, the cxl_bus reset fails in an x86 guest with "failed to prepare CXL bus reset ranges: -6".

I drove both devices with a small test module based on tools/testing/cxl/test/accel.c. It attaches each firmware-committed region with devm_cxl_probe_mem() and has no reset handlers. Then, with lockdep on:

echo cxl_bus > /sys/bus/pci/devices/0000:36:00.0/reset_method echo 1 > /sys/bus/pci/devices/0000:36:00.0/reset
echo 0 > /sys/bus/pci/slots/2/power # second device, 0000:c0:00.0

For the hang, add msleep(10000) after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(). Start the cxl_bus reset, remove 0000:c0:00.0 through sysfs two seconds later, and power off slot 0 two seconds after that.

Separately, pci_cxl_reset_prepare() returns with the quiesce held on its success path only, and cxl_restore_state_after_pci_reset() releases it. With Clang 23 and CONTEXT_ANALYSIS=y passed to make, that gives five cxl_region_quiesce warnings in drivers/pci/cxl.c.

[1]: https://lore.kernel.org/all/[email protected]/

DJ

maintainer
#62 lore raw
In reply to Srirangan Madhavan
Quoted 34 lines · Srirangan Madhavan

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

    /sys/bus/pci/devices/.../reset_method
    /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

Quoted 3 lines

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

Hi Srirangan,

Thanks for all the followups on review feedback. I think you answer some of my question above, 'For sysfs reset...' Could you explain the intended use cases for this reset method? Like why and when would userspace issue a CXL reset. In particular, is reset intended to be available before endpoint and region discovery have completed?

I see how the series saves state for restoration after reset. I don't see what ensures discovery has progressed far enough for reset to be safe.

I also see DaveJ's cxl_bus deadlock report. My concern is related but separate. Even without a deadlock, a reset could hold the global region lock for up to 100 seconds plus cache maintenance and restoration, blocking discovery and region assembly on unrelated devices. Understanding the intended usage would help assess whether that disruption is acceptable. Note that my simple concern is a user issuing those cxl_reset's on repeat and blocking CXL bringup. Yeah, that's a bad user, but is there any protection against that?

Adding specific questions on patches 11, 13, and 16

-- Alison

Quoted 146 lines

Changes from v16 [1]:
- Publish the PCI HDM cache under the PCI device lock instead of cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming) [6][7]
- Wait for the reset timeout the device advertises, up to 100 seconds, instead of clamping it to 20 seconds, so Control2 is not accessed while the device may still be resetting (Richard) [8]
- State that userspace is expected to offline CXL.mem users before reset, and what the HPA reservation does and does not cover (Richard) [9]
- Enable bus mastering after the IOMMU is restored on CXL bus reset (Richard) [10]
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard) [11]
- Initialize the zero-size HDM decoder end to base - 1 and document the zero-size case (Richard) [12]
- Set Lock On Commit after programming the decoder registers and before Commit when recommitting a locked decoder (Alison) [13]
- Record Normalized Addressing in the cached decoder when region discovery sets it, and note the short window before that update (Sashiko) [15]
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() (Sashiko)
[15]
- Add the missing context-analysis annotations on the region quiesce lock and unlock and on __cxl_reset_execute() (Sashiko) [15]
- Use an explicit pci_dev_put() in read_cdat_data() instead of mixing __free() with goto cleanup (Sashiko) [15]
- Check for VFs and multifunction devices before the CXL DVSEC lookups in the two reset methods, to avoid repeated capability walks while probing VFs (Joshua) [18]
- Fold the CXL bus reset cache flush patch into this series (Dave); the series is now 19 patches
- Added Richard's Reviewed-by tags to patches 6-10, 14 and 16
- Specified the reviewer behind each change in the changelogs, per Alison [14]

Earlier revision history is in the v16 [1] and v15 [2] cover letters.

Attribution for Dave Jiang's reference branch is still open. Since I am unsure about [16] I have not yet added the right tags. The patches link to his branch below the separator for now.

The v15 discussion on the scope check is still pending [17].

HDM caching requires CXL.cache, CXL.mem, CXL Reset and Reset Memory Clear capabilities. CXL bus reset state restoration uses that cache.

CXL Reset requires a registered CPU cache clean/invalidate provider and matching firmware, such as the separate SMCCC provider series [3]. Without that provider, cxl_reset can be advertised while execution returns -ENOTTY, unless the test-only CXL_REGION_INVALIDATION_TEST bypass is enabled.

The KUnit suite checks HDM range boundaries, zero-size and uncommitted state, lock and target-type decoding, and 12-way interleave.

Testing: v17 was tested on an ARM64 target with v5 of the SMCCC cache provider series [3] applied. Reset loops passed for both cxl_reset and cxl_bus after running bidirectional host-device traffic. The cxl_hdm_unpack_kunit suite passes.

[1] https://lore.kernel.org/linux-cxl/[email protected]/
[2] https://lore.kernel.org/linux-cxl/[email protected]/
[3] https://lore.kernel.org/linux-arm-kernel/[email protected]/
[4] https://computeexpresslink.org/wp-content/uploads/2026/02/CXL-Specification_rev4p0_ver1p0_2026February26_clean_evalcopy_v2.pdf
[5] https://lore.kernel.org/all/[email protected]/
[6] https://lore.kernel.org/linux-cxl/[email protected]/
[7] https://lore.kernel.org/linux-cxl/[email protected]/T/#m7f8d0e51d4cfe09fefcebd93d49dcb916be9198a
[8] https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/
[9] https://lore.kernel.org/linux-cxl/auQRSOGWEDzB_qjF@MWDK4CY14F/
[10] https://lore.kernel.org/linux-cxl/auRhJa-nzR0CnKf3@MWDK4CY14F/
[11] https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/
[12] https://lore.kernel.org/linux-cxl/auQ27s1rSCcbdRJ3@MWDK4CY14F/
[13] https://lore.kernel.org/linux-cxl/[email protected]/
[14] https://lore.kernel.org/linux-cxl/[email protected]/
[15] https://sashiko.dev/#/patchset/[email protected]
[16] https://lore.kernel.org/linux-cxl/[email protected]/T/#m2f61467417f422316cb15b976773944dcdcb48c7
[17] https://lore.kernel.org/linux-cxl/[email protected]/T/#m4f62ed0f038f2d136158c74c1c6c338129266131
[18] https://lore.kernel.org/linux-cxl/[email protected]/

Srirangan Madhavan (19):
cxl: Clarify decoder interleave limit
cxl: Share CXL port upstream PCI device lookup
cxl: Move decoder declarations to shared header
cxl: Embed decoder configuration in a standalone structure
cxl: Introduce endpoint HDM decoder settings
cxl: Move HDM decoder helpers to built-in code
cxl: Share HDM decoder register unpacking
cxl: Move cxl_rwsem into built-in code
cxl: Refresh cached PCI HDM decoder settings
cxl: Build register block helpers into the kernel PCI/CXL: Cache endpoint HDM state during PCI enumeration PCI/CXL: Add CXL Device Reset sequencing
cxl: Validate and synchronize HDM ranges around reset PCI/CXL: Reject reset with unsafe function scope PCI/CXL: Restore CXL state after PCI reset PCI/CXL: Expose CXL Reset as a PCI reset method PCI/CXL: Restore CXL state after CXL bus reset PCI/CXL: Flush host and device caches for CXL bus reset
cxl: Add KUnit checks for HDM decoder unpacking

 MAINTAINERS                          |   1 +
 drivers/cxl/.kunitconfig             |   4 +
 drivers/cxl/Kconfig                  |  18 +-
 drivers/cxl/Makefile                 |   1 +
 drivers/cxl/acpi.c                   |  26 +-
 drivers/cxl/core/Makefile            |   2 +-
 drivers/cxl/core/atl.c               |   4 +-
 drivers/cxl/core/core.h              |  15 +
 drivers/cxl/core/hdm.c               | 273 +++-----
 drivers/cxl/core/hdm_regs.c          | 437 +++++++++++++
 drivers/cxl/core/hdm_state.c         | 402 ++++++++++++
 drivers/cxl/core/pci.c               |  85 ++-
 drivers/cxl/core/port.c              |  68 +-
 drivers/cxl/core/region.c            | 116 ++--
 drivers/cxl/core/regs.c              |   9 +
 drivers/cxl/cxl.h                    |  46 +-
 drivers/cxl/pci.c                    |   2 +-
 drivers/cxl/port.c                   |   4 +-
 drivers/cxl/tests/Makefile           |   5 +
 drivers/cxl/tests/hdm_unpack_kunit.c |  91 +++
 drivers/pci/Makefile                 |   1 +
 drivers/pci/bus.c                    |   1 +
 drivers/pci/cxl.c                    | 907 +++++++++++++++++++++++++++
 drivers/pci/pci.c                    |  27 +-
 drivers/pci/pci.h                    |  44 ++
 drivers/pci/probe.c                  |   1 +
 include/cxl/cxl.h                    |  59 +-
 include/cxl/hdm.h                    | 109 ++++
 include/cxl/pci.h                    |  13 +
 include/linux/pci.h                  |   8 +-
 include/uapi/linux/pci_regs.h        |  14 +
 tools/testing/cxl/Kbuild             |   1 -
 tools/testing/cxl/test/cxl.c         | 158 +++--
 33 files changed, 2526 insertions(+), 426 deletions(-)
 create mode 100644 drivers/cxl/.kunitconfig
 create mode 100644 drivers/cxl/core/hdm_regs.c
 create mode 100644 drivers/cxl/core/hdm_state.c
 create mode 100644 drivers/cxl/tests/Makefile
 create mode 100644 drivers/cxl/tests/hdm_unpack_kunit.c
 create mode 100644 drivers/pci/cxl.c
 create mode 100644 include/cxl/hdm.h

base-commit: fef22d37d47043b63e4007f2f5fe762fa21fae0c

Signature · 1 line
2.43.0
maintainer
#32 lore raw

Re: [PATCH v17 11/19] PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Srirangan Madhavan
Quoted 2 lines · Srirangan Madhavan

Cache HDM state in pci_dev->hdm after BAR resource setup and before driver binding, so reset can restore it without a bound CXL driver.

Does having this cache make the device ready for reset before its CXL endpoint and region discovery have run?

I understand why restoration needs to work without a bound CXL driver, but what establishes that the cached state is sufficiently complete for reset at this point? Some information, such as normalized addressing in patch 13, is only recorded later during discovery.

-- Alison

Quoted 621 lines

Limit caching to devices that advertise CXL.cache, CXL.mem, CXL Reset, and Reset Memory Clear. Save their HDM register location, decoder settings, and Device DVSEC state.

Validate capability reads and decoder counts, and restore PCI_COMMAND after temporary MMIO access, reporting restoration failures. Publish the cache under the PCI device lock and protect later updates with the DPA lock.

Assisted-by LLM

---
Changes in v17:
- Publish the cache under the PCI device lock without taking cxl_rwsem.dpa, and drop the cxl_hdm_cache_present() and cxl_hdm_cache_publish() helpers (Li Ming)
https://lore.kernel.org/linux-cxl/[email protected]/
- Reject an all-ones DVSEC Control read in cxl_set_mem_enable() before it is written back or cached (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=11
- Explain why cxl_set_mem_enable() refreshes the cached DVSEC Control when MEM_ENABLE already matches (Richard)
https://lore.kernel.org/linux-cxl/auRQN6a3QVtqjd5a@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=b12baa1105f33cc1a10f9c9c0c6376194397d9f3

---
 MAINTAINERS                   |   1 +
 drivers/cxl/core/hdm_regs.c   |  96 +++++++++++++++
 drivers/cxl/core/hdm_state.c  |  37 +++++-
 drivers/cxl/core/pci.c        |  29 +++--
 drivers/pci/Makefile          |   1 +
 drivers/pci/bus.c             |   1 +
 drivers/pci/cxl.c             | 225 ++++++++++++++++++++++++++++++++++
 drivers/pci/pci.h             |   8 ++
 drivers/pci/probe.c           |   1 +
 include/cxl/hdm.h             |   9 ++
 include/uapi/linux/pci_regs.h |   2 +
 11 files changed, 399 insertions(+), 11 deletions(-)
 create mode 100644 drivers/pci/cxl.c
MAINTAINERS +1 -0
index c2414447892c..b874340b0265 100644
@@ -6572,6 +6572,7 @@ S:	Maintained
 F:	Documentation/driver-api/cxl
 F:	Documentation/userspace-api/fwctl/fwctl-cxl.rst
 F:	drivers/cxl/
+F:	drivers/pci/cxl.c
 F:	include/cxl/
 F:	include/uapi/linux/cxl_mem.h
 F:	tools/testing/cxl/
drivers/cxl/core/hdm_regs.c +96 -0
index cc5d77c4abf5..c92dbb017162 100644
@@ -2,6 +2,7 @@
 /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
 #include <linux/delay.h>
 #include <linux/bug.h>
+#include <linux/device.h>
 #include <linux/errno.h>
 #include <linux/export.h>
 #include <linux/kernel.h>
@@ -190,3 +191,98 @@ int cxl_hdm_read_decoder(struct cxl_decoder_config *config, void __iomem *hdm,
 	return cxl_hdm_unpack_decoder(config, id, ctrl, base, size);
 }
 EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_read_decoder, "cxl_core");
+
+/**
+ * cxl_hdm_decoder_count_mapped() - read the decoder count of a mapped block
+ * @dev: device for error reporting
+ * @hdm: mapped HDM decoder capability
+ * @size: size of the mapping
+ *
+ * Return: the decoder count, or a negative errno if the count is reserved or
+ * the mapping cannot hold every decoder.
+ */
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+				 resource_size_t size)
+{
+	int count;
+
+	count = cxl_hdm_decoder_count(readl(hdm + CXL_HDM_DECODER_CAP_OFFSET));
+	if (count < 0)
+		return count;
+
+	/* The last decoder's target-list high register must fit in the mapping. */
+	if (CXL_HDM_DECODER0_TL_HIGH(count - 1) + sizeof(u32) > size) {
+		dev_err(dev, "CXL HDM decoder count exceeds mapped register block\n");
+		return -ENXIO;
+	}
+
+	return count;
+}
+
+/* Read one endpoint decoder; a disabled decoder keeps only its id. */
+static int cxl_hdm_read_decoder_settings(struct device *dev,
+					 struct cxl_endpoint_decoder_settings *settings,
+					 void __iomem *hdm, int id)
+{
+	u64 lo, hi;
+	u32 ctrl;
+	int rc;
+
+	ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(id));
+	rc = cxl_hdm_read_decoder(&settings->config, hdm, id, ctrl);
+	if (rc) {
+		dev_err(dev,
+			"CXL HDM decoder %d has invalid configuration: %d\n",
+			id, rc);
+		return rc;
+	}
+
+	if (!(settings->config.flags & CXL_DECODER_F_ENABLE)) {
+		*settings = (struct cxl_endpoint_decoder_settings) {
+			.config.id = id,
+		};
+	} else {
+		lo = readl(hdm + CXL_HDM_DECODER0_SKIP_LOW(id));
+		hi = readl(hdm + CXL_HDM_DECODER0_SKIP_HIGH(id));
+		settings->skip = (hi << 32) | lo;
+	}
+
+	return 0;
+}
+
+/**
+ * cxl_hdm_read_state() - read endpoint HDM decoder state
+ * @dev: device for error messages
+ * @hdm: mapped HDM decoder capability
+ * @info: state to fill; @info->decoder_count must be set
+ *
+ * Return: 0 on success, or a negative errno if a decoder holds an invalid
+ * configuration or the decoder count changed while reading.
+ */
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+		       struct cxl_hdm_info *info)
+{
+	int count;
+	int rc;
+
+	info->global_ctrl = readl(hdm + CXL_HDM_DECODER_CTRL_OFFSET);
+	for (int i = 0; i < info->decoder_count; i++) {
+		rc = cxl_hdm_read_decoder_settings(dev, &info->settings[i],
+						   hdm, i);
+		if (rc)
+			return rc;
+	}
+
+	/*
+	 * A changed decoder count means the snapshot no longer describes the
+	 * complete hardware state. Reject it rather than publish a partial cache.
+	 */
+	count = cxl_hdm_decoder_count(readl(hdm + CXL_HDM_DECODER_CAP_OFFSET));
+	if (count != info->decoder_count) {
+		dev_err(dev, "CXL HDM decoder count changed from %d to %d\n",
+			info->decoder_count, count);
+		return -ENXIO;
+	}
+
+	return 0;
+}
drivers/cxl/core/hdm_state.c +36 -1
index d4c2be1ef833..9def4a7439c9 100644
@@ -1,21 +1,37 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+#include <linux/cleanup.h>
 #include <linux/export.h>
 #include <linux/io.h>
 #include <linux/pci.h>
 #include <linux/rwsem.h>
+#include <linux/slab.h>
 
 #include <cxl/hdm.h>
-
 #include "cxl.h"
 #include "core.h"
 
+/*
+ * CXL state that must stay available while no CXL driver is bound: the CXL
+ * locks and the per-device HDM cache filled during PCI enumeration.
+ */
 struct cxl_rwsem cxl_rwsem = {
 	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
 	.dpa = __RWSEM_INITIALIZER(cxl_rwsem.dpa),
 };
 EXPORT_SYMBOL_FOR_MODULES(cxl_rwsem, "cxl_core");
 
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl)
+{
+	guard(rwsem_write)(&cxl_rwsem.dpa);
+	if (!pdev->hdm)
+		return;
+
+	pdev->hdm->dvsec_ctrl = ctrl;
+	pdev->hdm->dvsec_ctrl_valid = true;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_set_dvsec_ctrl, "cxl_core");
+
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled)
 {
@@ -70,3 +86,22 @@ int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count)
 	return 0;
 }
 EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_check_decoder_count, "cxl_core");
+
+/**
+ * cxl_hdm_cache_release() - unpublish and free cached HDM state
+ * @slot: cache pointer owned by the device
+ *
+ * Take the DPA write lock to exclude readers while clearing @slot, then
+ * free the unpublished cache after releasing the lock.
+ */
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot)
+{
+	struct cxl_hdm_info *info;
+
+	scoped_guard(rwsem_write, &cxl_rwsem.dpa) {
+		info = *slot;
+		/* Unpublish before freeing so readers cannot see stale state. */
+		*slot = NULL;
+	}
+	kfree(info);
+}
drivers/cxl/core/pci.c +19 -10
index 5272013548c7..ea5327cd627f 100644
@@ -209,22 +209,31 @@ static int cxl_set_mem_enable(struct cxl_dev_state *cxlds, u16 val)
 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
 	int d = cxlds->cxl_dvsec;
 	u16 ctrl;
-	int rc;
+	int rc, ret = 1;
 
 	rc = pci_read_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, &ctrl);
 	if (rc)
 		return pcibios_err_to_errno(rc);
+	/* An all-ones read must not be written back or cached. */
+	if (PCI_POSSIBLE_ERROR(ctrl))
+		return -ENODEV;
 
-	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) == val)
-		return 1;
-	ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
-	ctrl |= val;
+	if ((ctrl & PCI_DVSEC_CXL_MEM_ENABLE) != val) {
+		ctrl &= ~PCI_DVSEC_CXL_MEM_ENABLE;
+		ctrl |= val;
 
-	rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
-	if (rc)
-		return pcibios_err_to_errno(rc);
+		rc = pci_write_config_word(pdev, d + PCI_DVSEC_CXL_CTRL, ctrl);
+		if (rc)
+			return pcibios_err_to_errno(rc);
+		ret = 0;
+	}
 
-	return 0;
+	/*
+	 * Refresh the PCI-core cache from the live register even when
+	 * MEM_ENABLE already matched: a reset restores the cached value.
+	 */
+	cxl_hdm_cache_set_dvsec_ctrl(pdev, ctrl);
+	return ret;
 }
 
 static void clear_mem_enable(void *cxlds)
@@ -314,7 +323,7 @@ int cxl_dvsec_rr_decode(struct cxl_dev_state *cxlds,
 	 * capable, there is no point in continuing to enable CXL.mem.
 	 */
 	hdm_count = FIELD_GET(PCI_DVSEC_CXL_HDM_COUNT, cap);
-	if (!hdm_count || hdm_count > 2)
+	if (!cxl_dvsec_hdm_count_valid(hdm_count))
 		return -EINVAL;
 
 	/*
drivers/pci/Makefile +1 -0
index 41ebc3b9a518..7a5d9f7297e9 100644
@@ -34,6 +34,7 @@ obj-$(CONFIG_PCI_P2PDMA)	+= p2pdma.o
 obj-$(CONFIG_XEN_PCIDEV_FRONTEND) += xen-pcifront.o
 obj-$(CONFIG_VGA_ARB)		+= vgaarb.o
 obj-$(CONFIG_PCI_DOE)		+= doe.o
+obj-$(CONFIG_CXL_RESET)		+= cxl.o
 obj-$(CONFIG_PCI_IDE)		+= ide.o
 obj-$(CONFIG_PCI_TSM)		+= tsm.o
 obj-$(CONFIG_PCI_DYNAMIC_OF_NODES) += of_property.o
drivers/pci/bus.c +1 -0
index 655ed53436d3..aad567fb7c56 100644
@@ -359,6 +359,7 @@ void pci_bus_add_device(struct pci_dev *dev)
 
 	/* Save config space for error recoverability */
 	pci_save_state(dev);
+	pci_cxl_hdm_cache_init(dev);
 
 	/*
 	 * Enable runtime PM, which potentially allows the device to
drivers/pci/cxl.c new file +225 -0
new file mode 100644
index 000000000000..a0d20f4210a5
@@ -0,0 +1,225 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
+/*
+ * CXL reset support in the PCI core. Cache the HDM decoder state of a CXL
+ * memory device at enumeration, so it can be restored after a reset without
+ * a CXL driver. HDM register formats and programming live in drivers/cxl.
+ */
+#include <linux/bitfield.h>
+#include <linux/cleanup.h>
+#include <linux/errno.h>
+#include <linux/io.h>
+#include <linux/ioport.h>
+#include <linux/kernel.h>
+#include <linux/pci.h>
+#include <linux/slab.h>
+
+#include <cxl/hdm.h>
+#include <cxl/pci.h>
+
+#include "pci.h"
+
+/* Find the CXL Device DVSEC and read its capability register. */
+static int cxl_pci_device_dvsec(struct pci_dev *pdev, u16 *dvsec, u16 *cap)
+{
+	int rc;
+
+	*dvsec = pci_find_dvsec_capability(pdev, PCI_VENDOR_ID_CXL,
+					   PCI_DVSEC_CXL_DEVICE);
+	if (!*dvsec)
+		return -ENOTTY;
+
+	rc = pci_read_config_word(pdev, *dvsec + PCI_DVSEC_CXL_CAP, cap);
+	if (rc)
+		return pcibios_err_to_errno(rc);
+	if (PCI_POSSIBLE_ERROR(*cap))
+		return -ENODEV;
+
+	return 0;
+}
+
+static bool cxl_pci_bar_assigned(struct pci_dev *pdev, int bar)
+{
+	struct resource *res = &pdev->resource[bar];
+
+	return pci_resource_len(pdev, bar) &&
+	       !(res->flags & (IORESOURCE_UNSET | IORESOURCE_DISABLED)) &&
+	       resource_type(res) == IORESOURCE_MEM && res->start && res->end;
+}
+
+static void __iomem *cxl_pci_hdm_map_regs(struct pci_dev *pdev,
+					  struct cxl_register_map *map,
+					  resource_size_t *hdm_offset,
+					  int *decoder_count)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	void __iomem *hdm;
+	int rc;
+
+	/* cxl_setup_regs() populates hdm_map, including its valid bit. */
+	rc = cxl_setup_regs(map);
+	if (rc)
+		return ERR_PTR(rc);
+	if (!hdm_map->valid)
+		return ERR_PTR(-ENODEV);
+	if (hdm_map->offset > map->max_size ||
+	    hdm_map->size > map->max_size - hdm_map->offset)
+		return ERR_PTR(-ENXIO);
+	if (check_add_overflow(map->bar_offset,
+			       (resource_size_t)hdm_map->offset, hdm_offset))
+		return ERR_PTR(-EOVERFLOW);
+
+	hdm = ioremap(map->resource + hdm_map->offset, hdm_map->size);
+	if (!hdm)
+		return ERR_PTR(-ENOMEM);
+
+	*decoder_count = cxl_hdm_decoder_count_mapped(&pdev->dev, hdm,
+						      hdm_map->size);
+	if (*decoder_count < 0) {
+		iounmap(hdm);
+		return ERR_PTR(*decoder_count);
+	}
+
+	return hdm;
+}
+
+static struct cxl_hdm_info *__cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						    struct cxl_register_map *map,
+						    int dvsec)
+{
+	struct cxl_reg_map *hdm_map = &map->component_map.hdm_decoder;
+	struct cxl_hdm_info *info;
+	resource_size_t hdm_offset;
+	void __iomem *hdm;
+	int decoder_count;
+	u16 dvsec_ctrl;
+	int rc;
+
+	hdm = cxl_pci_hdm_map_regs(pdev, map, &hdm_offset, &decoder_count);
+	if (IS_ERR(hdm))
+		return ERR_CAST(hdm);
+
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL,
+				  &dvsec_ctrl);
+	if (rc) {
+		rc = pcibios_err_to_errno(rc);
+		goto out_unmap;
+	}
+
+	info = kzalloc_flex(*info, settings, decoder_count, GFP_KERNEL);
+	if (!info) {
+		rc = -ENOMEM;
+		goto out_unmap;
+	}
+
+	info->decoder_count = decoder_count;
+	info->hdm_bar = map->bar;
+	info->hdm_offset = hdm_offset;
+	info->hdm_size = hdm_map->size;
+	info->dvsec = dvsec;
+	info->dvsec_ctrl = dvsec_ctrl;
+	info->dvsec_ctrl_valid = true;
+
+	rc = cxl_hdm_read_state(&pdev->dev, hdm, info);
+	if (rc)
+		goto out_free;
+
+	iounmap(hdm);
+	return info;
+
+out_free:
+	kfree(info);
+out_unmap:
+	iounmap(hdm);
+	return ERR_PTR(rc);
+}
+
+static struct cxl_hdm_info *cxl_pci_hdm_read_info(struct pci_dev *pdev,
+						  struct cxl_register_map *map,
+						  int dvsec)
+{
+	struct cxl_hdm_info *info;
+	u16 command;
+	int rc;
+
+	rc = pci_read_config_word(pdev, PCI_COMMAND, &command);
+	if (rc)
+		return ERR_PTR(pcibios_err_to_errno(rc));
+
+	if (!(command & PCI_COMMAND_MEMORY)) {
+		rc = pci_write_config_word(pdev, PCI_COMMAND,
+					   command | PCI_COMMAND_MEMORY);
+		if (rc)
+			return ERR_PTR(pcibios_err_to_errno(rc));
+	}
+
+	info = __cxl_pci_hdm_read_info(pdev, map, dvsec);
+	if (!(command & PCI_COMMAND_MEMORY)) {
+		rc = pci_write_config_word(pdev, PCI_COMMAND, command);
+		if (rc)
+			pci_err(pdev,
+				"failed to restore PCI_COMMAND after CXL HDM cache init: %d\n",
+				pcibios_err_to_errno(rc));
+	}
+	return info;
+}
+
+static int __pci_cxl_hdm_cache_init(struct pci_dev *pdev)
+{
+	struct cxl_register_map map = { };
+	struct cxl_hdm_info *read_info;
+	u16 dvsec, cap;
+	int rc;
+
+	guard(pci_dev)(pdev);
+
+	/* Avoid duplicate MMIO reads when the cache is already present. */
+	if (pdev->hdm)
+		return 0;
+
+	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
+	if (rc == -ENOTTY)
+		return 0;
+	if (rc)
+		return rc;
+	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
+	    !(cap & PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE) ||
+	    !cxl_dvsec_hdm_count_valid(FIELD_GET(PCI_DVSEC_CXL_HDM_COUNT, cap)))
+		return 0;
+
+	rc = cxl_find_regblock(pdev, CXL_REGLOC_RBI_COMPONENT, &map);
+	if (rc)
+		return rc;
+	if (map.bar < 0 || map.bar >= PCI_STD_NUM_BARS ||
+	    !cxl_pci_bar_assigned(pdev, map.bar))
+		return -ENODEV;
+
+	read_info = cxl_pci_hdm_read_info(pdev, &map, dvsec);
+	if (IS_ERR(read_info))
+		return PTR_ERR(read_info);
+
+	/*
+	 * The PCI device lock held since the cache check excludes other
+	 * initializers. CXL drivers bind only after enumeration, so no cache
+	 * mutator can run yet and cxl_rwsem.dpa is not needed to publish.
+	 */
+	pdev->hdm = read_info;
+
+	return 0;
+}
+
+void pci_cxl_hdm_cache_init(struct pci_dev *pdev)
+{
+	int rc;
+
+	rc = __pci_cxl_hdm_cache_init(pdev);
+	if (rc)
+		pci_dbg(pdev, "CXL HDM cache init failed: %d\n", rc);
+}
+
+void pci_cxl_hdm_cache_release(struct pci_dev *pdev)
+{
+	cxl_hdm_cache_release(&pdev->hdm);
+}
drivers/pci/pci.h +8 -0
index ba3c3fddddc2..9e218f236e66 100644
@@ -730,6 +730,14 @@ static inline void pci_doe_destroy(struct pci_dev *pdev) { }
 static inline void pci_doe_disconnected(struct pci_dev *pdev) { }
 #endif
 
+#ifdef CONFIG_CXL_RESET
+void pci_cxl_hdm_cache_init(struct pci_dev *pdev);
+void pci_cxl_hdm_cache_release(struct pci_dev *pdev);
+#else
+static inline void pci_cxl_hdm_cache_init(struct pci_dev *pdev) { }
+static inline void pci_cxl_hdm_cache_release(struct pci_dev *pdev) { }
+#endif
+
 #ifdef CONFIG_PCI_NPEM
 void pci_npem_create(struct pci_dev *dev);
 void pci_npem_remove(struct pci_dev *dev);
drivers/pci/probe.c +1 -0
index 27008e2ea5af..cb52357344ed 100644
@@ -2484,6 +2484,7 @@ static void pci_release_dev(struct device *dev)
 	struct pci_dev *pci_dev;
 
 	pci_dev = to_pci_dev(dev);
+	pci_cxl_hdm_cache_release(pci_dev);
 	pci_release_capabilities(pci_dev);
 	pci_release_of_node(pci_dev);
 	pcibios_release_device(pci_dev);
include/cxl/hdm.h +9 -0
index 06e9aa4479c2..0604dcc439c9 100644
@@ -26,6 +26,7 @@ struct cxl_endpoint_decoder_settings {
  * @hdm_offset: offset of the HDM decoder capability in @hdm_bar
  * @hdm_size: size of the HDM decoder register block
  * @global_ctrl: HDM decoder global control register
+ * @dvsec: config space offset of the CXL Device DVSEC
  * @dvsec_ctrl: CXL DVSEC control register
  * @dvsec_ctrl_valid: whether @dvsec_ctrl contains valid state
  * @settings: per-endpoint-decoder programming state
@@ -39,13 +40,21 @@ struct cxl_hdm_info {
 	resource_size_t hdm_offset;
 	resource_size_t hdm_size;
 	u32 global_ctrl;
+	u16 dvsec;
 	u16 dvsec_ctrl;
 	bool dvsec_ctrl_valid;
 	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
 };
+struct device;
 
+int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
+				 resource_size_t size);
+int cxl_hdm_read_state(struct device *dev, void __iomem *hdm,
+		       struct cxl_hdm_info *info);
+void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl);
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled);
 int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
 
 #endif /* __CXL_HDM_H__ */
include/uapi/linux/pci_regs.h +2 -0
index facaa324bd86..ca3e77b72d87 100644
@@ -1352,6 +1352,8 @@
 #define   PCI_DVSEC_CXL_CACHE_CAPABLE			_BITUL(0)
 #define   PCI_DVSEC_CXL_MEM_CAPABLE			_BITUL(2)
 #define   PCI_DVSEC_CXL_HDM_COUNT			__GENMASK(5, 4)
+#define   PCI_DVSEC_CXL_RST_CAPABLE			_BITUL(7)
+#define   PCI_DVSEC_CXL_RST_MEM_CLR_CAPABLE		_BITUL(11)
 #define  PCI_DVSEC_CXL_CTRL				0xC
 #define   PCI_DVSEC_CXL_MEM_ENABLE			_BITUL(2)
 #define  PCI_DVSEC_CXL_RANGE_SIZE_HIGH(i)		(0x18 + (i * 0x10))
Signature · 1 line
2.43.0
maintainer
#41 lore raw

Re: [PATCH v17 13/19] cxl: Validate and synchronize HDM ranges around reset

In reply to Srirangan Madhavan
Quoted 12 lines · Srirangan Madhavan

Refuse reset unless enabled system-physical HDM ranges can be reserved exclusively and CPU-cache invalidation is available. Invalidate before reset and again before ending IOMMU exclusion, holding range reservations until the second invalidation completes. A later patch places state restoration before the second invalidation.

Userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges: the reset fails while a conflicting resource is claimed, and no one can claim the range during the reset. It cannot see accesses by code that uses the range without claiming it, which the offline expectation also covers.

Quoted 5 lines

Reject normalized-addressing decoders because their cached ranges are not system physical addresses. Record Normalized Addressing in the cache when region discovery sets it, since the cache is filled earlier. A reset that takes its snapshot between endpoint probe and that update can still miss it.

What prevents reset during this window? If the snapshot misses the normalized-addressing flag can a reset proceed and use a range that is not a system physical address?

Does this mean we need to prevent reset until discovery has resolved the address interpretation, or is there another check that makes reset safe before then?

Quoted 11 lines

Ignore zero-size decoders because they map no address range. Refuse reset when the device decodes memory through its DVSEC ranges instead of HDM decoders, since the cache holds no range to reserve for that memory.

Hold the global cxl_rwsem.region write lock across snapshot, reset and restoration to keep the decoder state and reserved ranges stable. This also blocks region and decoder sysfs, region probe, poison operations, sanitize and region-aware event tracing across CXL devices. The Memory Clear wait lasts up to the timeout the device advertises, at most 100 seconds; cache flushes and other reset work extend the hold.

Similar to questions on previous versions and in cover letter -

Can a reset acquire this lock while other CXL devices are still being discovered and their regions assembled, and block that work for the full reset duration?

What limits the disruption to unrelated devices, including repeated resets? Could the locking be scoped to the affected device or regions rather than holding the global region lock throughout the wait?

Quoted 602 lines

Allow the existing CXL_REGION_INVALIDATION_TEST option to bypass missing CPU cache invalidation for test environments without a provider.

Assisted-by LLM

---
Changes in v17:
- State that userspace is expected to offline CXL.mem users before reset, and what the HPA reservation does and does not cover (Richard)
https://lore.kernel.org/linux-cxl/auQRSOGWEDzB_qjF@MWDK4CY14F/
- Record Normalized Addressing in the cached decoder when region discovery sets it, and note the short window before that update (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=13
- Annotate cxl_region_quiesce_lock()/unlock() and __cxl_reset_execute() for context analysis (Sashiko)
https://sashiko.dev/#/patchset/[email protected]?part=15
- Describe the region lock hold as bounded by the advertised reset timeout, at most 100 seconds, plus cache flushes (Richard)
https://lore.kernel.org/linux-cxl/auQC2UECQ8vaelPz@MWDK4CY14F/

Reference branch: https://git.kernel.org/pub/scm/linux/kernel/git/djiang/linux.git/commit/?id=5944c6e61f14c0dd28d54537be15edb2cadb0e8b

---
 drivers/cxl/Kconfig          |   3 +-
 drivers/cxl/core/hdm_state.c | 266 ++++++++++++++++++++++++++++++++++-
 drivers/cxl/core/region.c    |  14 ++
 drivers/pci/cxl.c            |  87 ++++++++++--
 include/cxl/hdm.h            |  47 ++++++-
 5 files changed, 406 insertions(+), 11 deletions(-)
drivers/cxl/Kconfig +2 -1
index 8b08bfdc4982..e927e69a3f7b 100644
@@ -226,7 +226,8 @@ config CXL_REGION_INVALIDATION_TEST
 	  invalidation mechanism. For example usage of wbinvd is restricted to
 	  bare metal x86. However, for testing purposes toggling this option
 	  can disable that data integrity safety and proceed with enabling
-	  regions when there might be conflicting contents in the CPU cache.
+	  regions or performing CXL reset when there might be conflicting
+	  contents in the CPU cache.
 
 	  If unsure, or if this kernel is meant for production environments,
 	  say N.
drivers/cxl/core/hdm_state.c +265 -1
index 9def4a7439c9..51df56377f7a 100644
@@ -1,8 +1,14 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2026 NVIDIA Corporation & Affiliates */
 #include <linux/cleanup.h>
+#include <linux/device.h>
+#include <linux/errno.h>
 #include <linux/export.h>
 #include <linux/io.h>
+#include <linux/ioport.h>
+#include <linux/list.h>
+#include <linux/memregion.h>
+#include <linux/overflow.h>
 #include <linux/pci.h>
 #include <linux/rwsem.h>
 #include <linux/slab.h>
@@ -13,7 +19,8 @@
 
 /*
  * CXL state that must stay available while no CXL driver is bound: the CXL
- * locks and the per-device HDM cache filled during PCI enumeration.
+ * locks, the per-device HDM cache filled during PCI enumeration, and the
+ * region quiesce used around a reset.
  */
 struct cxl_rwsem cxl_rwsem = {
 	.region = __RWSEM_INITIALIZER(cxl_rwsem.region),
@@ -87,6 +94,27 @@ int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count)
 }
 EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_check_decoder_count, "cxl_core");
 
+/**
+ * cxl_hdm_cache_set_normalized() - record Normalized Addressing in the cache
+ * @pdev: endpoint that owns the cache
+ * @id: endpoint decoder id
+ *
+ * Normalized Addressing is determined during region discovery, after the
+ * cache was filled, so the cached decoder lacks it. Record only that flag: the
+ * decoder's software lock must not become a hardware Lock On Commit when the
+ * cache is restored.
+ */
+void cxl_hdm_cache_set_normalized(struct pci_dev *pdev, int id)
+{
+	guard(rwsem_write)(&cxl_rwsem.dpa);
+	if (!pdev->hdm || id < 0 || id >= pdev->hdm->decoder_count)
+		return;
+
+	pdev->hdm->settings[id].config.flags |=
+		CXL_DECODER_F_NORMALIZED_ADDRESSING;
+}
+EXPORT_SYMBOL_FOR_MODULES(cxl_hdm_cache_set_normalized, "cxl_core");
+
 /**
  * cxl_hdm_cache_release() - unpublish and free cached HDM state
  * @slot: cache pointer owned by the device
@@ -105,3 +133,239 @@ void cxl_hdm_cache_release(struct cxl_hdm_info **slot)
 	}
 	kfree(info);
 }
+
+/**
+ * cxl_hdm_cache_dvsec_decode() - check for memory decoded by DVSEC ranges
+ * @slot: cache pointer owned by the device
+ *
+ * Return: true if the published state shows CXL.mem enabled while HDM
+ * decoders are globally disabled, so that the device decodes memory through
+ * its DVSEC ranges, which the cache does not describe.
+ */
+bool cxl_hdm_cache_dvsec_decode(struct cxl_hdm_info *const *slot)
+{
+	struct cxl_hdm_info *info;
+
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	info = *slot;
+	return info && (info->dvsec_ctrl & PCI_DVSEC_CXL_MEM_ENABLE) &&
+	       !(info->global_ctrl & CXL_HDM_DECODER_ENABLE);
+}
+
+/**
+ * cxl_hdm_cache_snapshot() - copy the published HDM state
+ * @slot: cache pointer owned by the device
+ *
+ * Return: a copy the caller frees with kfree(), ERR_PTR(-ENXIO) when nothing
+ * is published, or another ERR_PTR() on failure.
+ */
+struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot)
+{
+	struct cxl_hdm_info *info, *copy;
+	size_t size;
+
+	guard(rwsem_read)(&cxl_rwsem.dpa);
+	info = *slot;
+	if (!info)
+		return ERR_PTR(-ENXIO);
+	if (info->decoder_count <= 0)
+		return ERR_PTR(-EINVAL);
+
+	size = struct_size(info, settings, info->decoder_count);
+	if (size == SIZE_MAX)
+		return ERR_PTR(-EOVERFLOW);
+
+	copy = kmemdup(info, size, GFP_KERNEL);
+	if (!copy)
+		return ERR_PTR(-ENOMEM);
+
+	return copy;
+}
+
+void cxl_region_quiesce_lock(void)
+	__acquires(cxl_region_quiesce)
+	__context_unsafe(token maps to cxl_rwsem.region)
+{
+	down_write(&cxl_rwsem.region);
+	__acquire(cxl_region_quiesce);
+}
+
+void cxl_region_quiesce_unlock(void)
+	__releases(cxl_region_quiesce)
+	__context_unsafe(token maps to cxl_rwsem.region)
+{
+	__release(cxl_region_quiesce);
+	up_write(&cxl_rwsem.region);
+}
+
+/*
+ * Bound the range twice: request_mem_region() takes resource_size_t while
+ * cpu_cache_invalidate_memregion() takes size_t, and the two differ on
+ * 32-bit builds with CONFIG_PHYS_ADDR_T_64BIT. range_len() can also reach
+ * RESOURCE_SIZE_MAX + 1 for a full-width range, and wraps to zero when
+ * resource_size_t is 64-bit, which the !len test catches.
+ */
+static int cxl_hdm_range_validate(const struct range *hpa_range)
+{
+	u64 len = range_len(hpa_range);
+
+	if (!len)
+		return -EINVAL;
+	if (hpa_range->end > RESOURCE_SIZE_MAX || len > RESOURCE_SIZE_MAX ||
+	    len > SIZE_MAX)
+		return -EOVERFLOW;
+
+	return 0;
+}
+
+static int cxl_hdm_range_add(struct cxl_hdm_quiesce *q,
+			     const struct range *hpa_range)
+{
+	struct cxl_hdm_range *range, *next, *new_range;
+	int rc;
+
+	rc = cxl_hdm_range_validate(hpa_range);
+	if (rc)
+		return rc;
+
+	list_for_each_entry(range, &q->ranges, list)
+		if (range_contains(&range->hpa_range, hpa_range))
+			return 0;
+
+	new_range = kzalloc_obj(*new_range);
+	if (!new_range)
+		return -ENOMEM;
+
+	new_range->hpa_range = *hpa_range;
+	new_range->len = range_len(hpa_range);
+
+	list_for_each_entry_safe(range, next, &q->ranges, list) {
+		if (range_contains(hpa_range, &range->hpa_range)) {
+			list_del(&range->list);
+			kfree(range);
+		}
+	}
+	list_add_tail(&new_range->list, &q->ranges);
+
+	return 0;
+}
+
+static int cxl_hdm_ranges_collect(struct cxl_hdm_quiesce *q,
+				  const struct cxl_hdm_info *snapshot)
+{
+	int rc;
+
+	for (int i = 0; i < snapshot->decoder_count; i++) {
+		const struct cxl_decoder_config *config =
+			&snapshot->settings[i].config;
+
+		/* A committed zero-size decoder maps no HPA. */
+		if (!(config->flags & CXL_DECODER_F_ENABLE) ||
+		    !range_len(&config->hpa_range))
+			continue;
+
+		if (config->flags & CXL_DECODER_F_NORMALIZED_ADDRESSING)
+			return -EOPNOTSUPP;
+
+		rc = cxl_hdm_range_add(q, &config->hpa_range);
+		if (rc)
+			return rc;
+	}
+
+	return 0;
+}
+
+static int cxl_hdm_ranges_request(struct cxl_hdm_quiesce *q)
+{
+	struct cxl_hdm_range *range;
+
+	lockdep_assert_held_write(&cxl_rwsem.region);
+
+	list_for_each_entry(range, &q->ranges, list) {
+		const struct range *hpa_range = &range->hpa_range;
+
+		range->res = request_mem_region(hpa_range->start, range->len,
+						"cxl_reset");
+		if (!range->res)
+			return -EBUSY;
+	}
+
+	return 0;
+}
+
+static int cxl_hdm_ranges_invalidate(struct cxl_hdm_quiesce *q)
+{
+	struct cxl_hdm_range *range;
+	int rc = 0;
+
+	lockdep_assert_held_write(&cxl_rwsem.region);
+
+	if (!cpu_cache_has_invalidate_memregion() &&
+	    IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST)) {
+		pr_info_once("CXL reset: bypassing CPU cache invalidation for testing\n");
+		return 0;
+	}
+
+	list_for_each_entry(range, &q->ranges, list) {
+		const struct range *hpa_range = &range->hpa_range;
+		int rc2;
+
+		rc2 = cpu_cache_invalidate_memregion(hpa_range->start, range->len);
+		rc = rc ?: rc2;
+	}
+
+	return rc;
+}
+
+/**
+ * cxl_hdm_quiesce_prepare() - take the HPA ranges of a device out of use
+ * @q: quiesce state to initialize
+ * @snapshot: HDM state from cxl_hdm_cache_snapshot()
+ *
+ * Reserve every enabled system-physical range in @snapshot exclusively, then
+ * write back and invalidate CPU caches for them. Call
+ * cxl_hdm_quiesce_destroy() afterwards whether or not this succeeds.
+ *
+ * Return: 0 on success, or a negative errno.
+ */
+int cxl_hdm_quiesce_prepare(struct cxl_hdm_quiesce *q,
+			    const struct cxl_hdm_info *snapshot)
+{
+	int rc;
+
+	lockdep_assert_held_write(&cxl_rwsem.region);
+	INIT_LIST_HEAD(&q->ranges);
+
+	if (!cpu_cache_has_invalidate_memregion() &&
+	    !IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST))
+		return -ENXIO;
+
+	rc = cxl_hdm_ranges_collect(q, snapshot);
+	if (rc)
+		return rc;
+
+	rc = cxl_hdm_ranges_request(q);
+	if (rc)
+		return rc;
+
+	return cxl_hdm_ranges_invalidate(q);
+}
+
+/* Evict lines fetched during reset before DMA exclusion ends. */
+int cxl_hdm_quiesce_flush(struct cxl_hdm_quiesce *q)
+{
+	return cxl_hdm_ranges_invalidate(q);
+}
+
+void cxl_hdm_quiesce_destroy(struct cxl_hdm_quiesce *q)
+{
+	struct cxl_hdm_range *range, *next;
+
+	list_for_each_entry_safe(range, next, &q->ranges, list) {
+		list_del(&range->list);
+		if (range->res)
+			release_mem_region(range->hpa_range.start,
+					   resource_size(range->res));
+		kfree(range);
+	}
+}
drivers/cxl/core/region.c +14 -0
index 8cfc06df3134..b06dd9b901f0 100644
@@ -12,6 +12,7 @@
 #include <linux/idr.h>
 #include <linux/memory-tiers.h>
 #include <linux/string_choices.h>
+#include <cxl/hdm.h>
 #include <cxlmem.h>
 #include <cxl.h>
 #include "core.h"
@@ -3840,6 +3841,19 @@ int cxl_add_to_region(struct cxl_endpoint_decoder *cxled)
 	if (IS_ERR(cxlrd))
 		return PTR_ERR(cxlrd);
 
+	/*
+	 * Translation setup may have marked the decoder as Normalized
+	 * Addressing, after the PCI cache was filled. Record it for reset.
+	 */
+	if (cxled->cxld.config.flags & CXL_DECODER_F_NORMALIZED_ADDRESSING) {
+		struct pci_dev *pdev __free(pci_dev_put) =
+			cxl_port_get_uport_pci_dev(cxled_to_port(cxled));
+
+		if (pdev)
+			cxl_hdm_cache_set_normalized(pdev,
+						     cxled->cxld.config.id);
+	}
+
 	/*
 	 * Ensure that, if multiple threads race to construct_region()
 	 * for the HPA range, one does the construction and the others
drivers/pci/cxl.c +79 -8
index 9ac5948f595b..af8ec8db20f1 100644
@@ -15,6 +15,7 @@
 #include <linux/iommu.h>
 #include <linux/jiffies.h>
 #include <linux/kernel.h>
+#include <linux/memregion.h>
 #include <linux/pci.h>
 #include <linux/slab.h>
 
@@ -23,6 +24,13 @@
 
 #include "pci.h"
 
+struct cxl_pci_cache {
+	struct cxl_hdm_quiesce quiesce;
+	u16 saved_ctrl2;
+	/* A cache-policy write was attempted and may need undoing. */
+	bool cache_disabled;
+};
+
 /* Find the CXL Device DVSEC and read its capability register. */
 static int cxl_pci_device_dvsec(struct pci_dev *pdev, u16 *dvsec, u16 *cap)
 {
@@ -335,6 +343,23 @@ static int cxl_reset_restore_cache_policy(struct pci_dev *pdev, int dvsec,
 	return rc;
 }
 
+/* Shared range reservation, host invalidation, and device cache writeback. */
+static int cxl_reset_cache_prepare(struct pci_dev *pdev, int dvsec, u16 cap,
+				   const struct cxl_hdm_info *snapshot,
+				   struct cxl_pci_cache *cache)
+	__must_hold(cxl_region_quiesce)
+{
+	int rc;
+
+	rc = cxl_hdm_quiesce_prepare(&cache->quiesce, snapshot);
+	if (rc)
+		return rc;
+
+	/* Track an attempted change so partial failures still restore policy. */
+	cache->cache_disabled = true;
+	return cxl_reset_disable_cache(pdev, dvsec, cap);
+}
+
 static int cxl_reset_wait_done(struct pci_dev *pdev, int dvsec, u16 cap)
 {
 	unsigned long deadline;
@@ -389,7 +414,9 @@ static int cxl_clear_memory(struct pci_dev *pdev, int dvsec, bool initiate)
 				      PCI_DVSEC_CXL_RST_MEM_CLR_EN);
 }
 
-static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap,
+			      struct cxl_hdm_quiesce *q)
+	__must_hold(cxl_region_quiesce)
 {
 	int rc, rc2;
 
@@ -414,29 +441,61 @@ static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
 		pci_err(pdev, "failed to clear CXL Reset Memory Clear: %d\n", rc2);
 	rc = rc ?: rc2;
 
+	rc2 = cxl_hdm_quiesce_flush(q);
+	if (rc2)
+		pci_err(pdev, "failed to invalidate CPU cache after CXL reset: %d\n", rc2);
+	rc = rc ?: rc2;
+
 	pci_dev_reset_iommu_done(pdev);
 	return rc;
 }
 
-static int cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+static int cxl_reset_quiesced(struct pci_dev *pdev, int dvsec, u16 cap)
+	__must_hold(cxl_region_quiesce)
 {
-	u16 saved_ctrl2;
+	struct cxl_hdm_info *snapshot __free(kfree) = NULL;
+	struct cxl_pci_cache cache = {};
 	int rc, rc2;
 
-	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2, &saved_ctrl2);
+	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL2,
+				  &cache.saved_ctrl2);
 	if (rc)
 		return pcibios_err_to_errno(rc);
-	if (PCI_POSSIBLE_ERROR(saved_ctrl2))
+	if (PCI_POSSIBLE_ERROR(cache.saved_ctrl2))
 		return -ENODEV;
 
-	rc = cxl_reset_disable_cache(pdev, dvsec, cap);
+	snapshot = cxl_hdm_cache_snapshot(&pdev->hdm);
+	if (IS_ERR(snapshot)) {
+		pci_err(pdev, "CXL HDM decoder state unavailable: %ld\n",
+			PTR_ERR(snapshot));
+		return PTR_ERR(snapshot);
+	}
+
+	rc = cxl_reset_cache_prepare(pdev, dvsec, cap, snapshot, &cache);
+	if (rc && !cache.cache_disabled) {
+		pci_err(pdev, "failed to prepare CXL reset ranges: %d\n", rc);
+		cxl_hdm_quiesce_destroy(&cache.quiesce);
+		return rc;
+	}
 	if (!rc)
-		rc = __cxl_reset_execute(pdev, dvsec, cap);
+		rc = __cxl_reset_execute(pdev, dvsec, cap, &cache.quiesce);
 	/* Restore cache policy after any attempt to disable caching. */
-	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, saved_ctrl2);
+	rc2 = cxl_reset_restore_cache_policy(pdev, dvsec, cache.saved_ctrl2);
+	cxl_hdm_quiesce_destroy(&cache.quiesce);
 	return rc ?: rc2;
 }
 
+static int cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+	int rc;
+
+	cxl_region_quiesce_lock();
+	rc = cxl_reset_quiesced(pdev, dvsec, cap);
+	cxl_region_quiesce_unlock();
+
+	return rc;
+}
+
 int cxl_reset_function(struct pci_dev *pdev, bool probe)
 {
 	u16 dvsec, cap, ctrl;
@@ -463,5 +522,17 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	if (probe)
 		return 0;
 
+	/* The cache is owned by @pdev and does not require a bound CXL driver. */
+	if (!pdev->hdm)
+		return -ENOTTY;
+
+	/* Memory decoded through DVSEC ranges has no HPA ranges to quiesce. */
+	if (cxl_hdm_cache_dvsec_decode(&pdev->hdm))
+		return -ENOTTY;
+
+	if (!cpu_cache_has_invalidate_memregion() &&
+	    !IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST))
+		return -ENOTTY;
+
 	return cxl_reset_execute(pdev, dvsec, cap);
 }
include/cxl/hdm.h +46 -1
index 0604dcc439c9..49b36a45c682 100644
@@ -3,10 +3,14 @@
 #ifndef __CXL_HDM_H__
 #define __CXL_HDM_H__
 
+#include <linux/list.h>
 #include <linux/types.h>
+
 #include <cxl/cxl.h>
 
+struct device;
 struct pci_dev;
+struct resource;
 struct cxl_endpoint_decoder;
 
 /**
@@ -45,7 +49,6 @@ struct cxl_hdm_info {
 	bool dvsec_ctrl_valid;
 	struct cxl_endpoint_decoder_settings settings[] __counted_by(decoder_count);
 };
-struct device;
 
 int cxl_hdm_decoder_count_mapped(struct device *dev, void __iomem *hdm,
 				 resource_size_t size);
@@ -55,6 +58,48 @@ void cxl_hdm_cache_set_dvsec_ctrl(struct pci_dev *pdev, u16 ctrl);
 void cxl_hdm_cache_refresh_decoder(struct pci_dev *pdev, void __iomem *hdm,
 				   struct cxl_endpoint_decoder *cxled);
 int cxl_hdm_cache_check_decoder_count(struct pci_dev *pdev, int count);
+void cxl_hdm_cache_set_normalized(struct pci_dev *pdev, int id);
 void cxl_hdm_cache_release(struct cxl_hdm_info **slot);
+bool cxl_hdm_cache_dvsec_decode(struct cxl_hdm_info *const *slot);
+struct cxl_hdm_info *cxl_hdm_cache_snapshot(struct cxl_hdm_info *const *slot);
+
+/*
+ * Region quiesce blocks CXL region commit and teardown, and with them decoder
+ * reprogramming, while reset handling captures or restores HDM decoder state.
+ */
+token_context_lock(cxl_region_quiesce);
+
+/**
+ * struct cxl_hdm_range - HPA range held exclusively across a reset
+ * @list: entry in &cxl_hdm_quiesce.ranges
+ * @hpa_range: system physical address range decoded by the device
+ * @len: length of @hpa_range
+ * @res: reservation of @hpa_range, once requested
+ */
+struct cxl_hdm_range {
+	struct list_head list;
+	struct range hpa_range;
+	u64 len;
+	struct resource *res;
+};
+
+/**
+ * struct cxl_hdm_quiesce - HPA ranges held exclusively across a reset
+ * @ranges: list of &struct cxl_hdm_range, see cxl_hdm_quiesce_prepare()
+ */
+struct cxl_hdm_quiesce {
+	struct list_head ranges;
+};
+
+void cxl_region_quiesce_lock(void)
+	__acquires(cxl_region_quiesce);
+void cxl_region_quiesce_unlock(void)
+	__releases(cxl_region_quiesce);
+int cxl_hdm_quiesce_prepare(struct cxl_hdm_quiesce *q,
+			    const struct cxl_hdm_info *snapshot)
+	__must_hold(cxl_region_quiesce);
+int cxl_hdm_quiesce_flush(struct cxl_hdm_quiesce *q)
+	__must_hold(cxl_region_quiesce);
+void cxl_hdm_quiesce_destroy(struct cxl_hdm_quiesce *q);
 
 #endif /* __CXL_HDM_H__ */
Signature · 1 line
2.43.0
maintainer
#49 lore raw

Re: [PATCH v17 16/19] PCI/CXL: Expose CXL Reset as a PCI reset method

In reply to Srirangan Madhavan
Quoted 2 lines · Srirangan Madhavan

Register cxl_reset with the PCI reset-method interface and place it before FLR, which does not reset CXL.cache or CXL.mem protocol state.

Same theme, trying to understand -
Can you clarify when cxl_reset first becomes visible in reset_method and when it can actually execute? Can userspace initiate reset before endpoint and region discovery have completed, and is that intentional?

-- Alison

Quoted 77 lines

Return -ENOTTY when device capabilities, function scope, cached HDM state, or required cache synchronization do not permit a safe reset.

---
 drivers/pci/cxl.c   | 12 +++++++++---
 drivers/pci/pci.c   |  1 +
 include/linux/pci.h |  2 +-
 3 files changed, 11 insertions(+), 4 deletions(-)
drivers/pci/cxl.c +9 -3
index 77d0e30841d9..c68b08f7f95b 100644
@@ -679,7 +679,7 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 
 	rc = cxl_pci_device_dvsec(pdev, &dvsec, &cap);
 	if (rc)
-		return rc;
+		return probe ? -ENOTTY : rc;
 	if (!(cap & PCI_DVSEC_CXL_CACHE_CAPABLE) ||
 	    !(cap & PCI_DVSEC_CXL_MEM_CAPABLE) ||
 	    !(cap & PCI_DVSEC_CXL_RST_CAPABLE) ||
@@ -688,9 +688,9 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 
 	rc = pci_read_config_word(pdev, dvsec + PCI_DVSEC_CXL_CTRL, &ctrl);
 	if (rc)
-		return pcibios_err_to_errno(rc);
+		return probe ? -ENOTTY : pcibios_err_to_errno(rc);
 	if (PCI_POSSIBLE_ERROR(ctrl))
-		return -ENODEV;
+		return probe ? -ENOTTY : -ENODEV;
 	if (!(ctrl & PCI_DVSEC_CXL_CACHE_ENABLE) ||
 	    !(ctrl & PCI_DVSEC_CXL_MEM_ENABLE))
 		return -ENOTTY;
@@ -710,5 +710,11 @@ int cxl_reset_function(struct pci_dev *pdev, bool probe)
 	    !IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST))
 		return -ENOTTY;
 
+	/* Raw reset callers may not have saved the PCI state needed for restore. */
+	if (!pdev->state_saved) {
+		pci_err(pdev, "CXL reset requires saved PCI state\n");
+		return -EINVAL;
+	}
+
 	return cxl_reset_execute(pdev, dvsec, cap);
 }
drivers/pci/pci.c +1 -0
index aef976d0c850..426b5ee38d04 100644
@@ -5152,6 +5152,7 @@ const struct pci_reset_fn_method pci_reset_fn_methods[] = {
 	{ },
 	{ pci_dev_specific_reset, .name = "device_specific" },
 	{ pci_dev_acpi_reset, .name = "acpi" },
+	{ cxl_reset_function, .name = "cxl_reset" },
 	{ pcie_reset_flr, .name = "flr" },
 	{ pci_af_flr, .name = "af_flr" },
 	{ pci_pm_reset, .name = "pm" },
include/linux/pci.h +1 -1
index 7bb37fcb556d..743b57ff885a 100644
@@ -52,7 +52,7 @@
 			       PCI_STATUS_PARITY)
 
 /* Number of reset methods used in pci_reset_fn_methods array in pci.c */
-#define PCI_NUM_RESET_METHODS 8
+#define PCI_NUM_RESET_METHODS 9
 
 #define PCI_RESET_PROBE		true
 #define PCI_RESET_DO_RESET	false
Signature · 1 line
2.43.0
#60 lore raw
In reply to Dave Jiang
Quoted 118 lines · Dave Jiang

External email: Use caution opening links or attachments

Quoted 34 lines · Srirangan Madhavan

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

     /sys/bus/pci/devices/.../reset_method
     /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

Quoted 3 lines

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

I think holding it across the bus reset can deadlock with pciehp and a PCI remove. I tested in QEMU with two cxl-type2 devices from Manish's RFC [1].

For a device in a pciehp slot, pci_reset_bus_function() ends up in pciehp_reset_slot(), which takes the slot's reset_lock. The reset still holds cxl_rwsem.region at that point.

Two other tasks can complete a cycle. pciehp_ist() for that slot can hold reset_lock and wait for pci_rescan_remove_lock in pciehp_unconfigure_device(). A PCI remove of a second Type 2 device can hold pci_rescan_remove_lock while cxl_decoder_detach() waits for cxl_rwsem.region.

On v17 as posted, lockdep reports the cycle:

   [   60.891789] WARNING: possible circular locking dependency detected
   [   60.893014] irq/24-pciehp/103 is trying to acquire lock:
   [   60.893367] ffff888072b4f128 (&cxl_memdev_key){+.+.}-{4:4}, at: device_del+0x8d/0x580
                  but task is already holding lock:
   [   60.894498] ffffffff84699e80 (pci_rescan_remove_lock){+.+.}-{4:4}, at: pciehp_unconfigure_device+0x93/0x210
   [...]
                  -> #3 (&ctrl->reset_lock){++++}-{4:4}:
   [   60.916794]        down_write_nested+0x80/0x170
   [   60.917826]        pciehp_reset_slot+0x6c/0xc0
   [   60.918893]        pci_reset_hotplug_slot+0x5c/0x90
   [   60.919928]        pci_reset_bus_function+0x161/0x330
   [   60.920951]        cxl_reset_bus_function+0x1c6/0x280
   [   60.921958]        __pci_reset_function_locked+0x96/0x170
   [   60.922990]        pci_reset_function+0xc8/0x180
   [   60.923977]        reset_store+0x84/0xd0
   [...]
                  -> #2 (cxl_rwsem.region){++++}-{4:4}:
   [...]
   [   61.013490] Chain exists of:
                    &cxl_memdev_key --> &ctrl->reset_lock --> pci_rescan_remove_lock

With a test-only msleep() after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(), it turns into a real hang. The reset, a sysfs remove of the second device and a power off of the first device's slot all got stuck.

Two region reads blocked behind the reset as well. A read of region1/commit timed out after 5 s, and cxl list -R stayed in D state in decoders_committed_show().

To reproduce, I used Manish's RFC as posted. It allows one cxl-type2 per pxb-cxl, so each device has its own host bridge and window. On q35 with cxl=on, plus the memory backends:

   -device pxb-cxl,id=cxl.0,bus=pcie.0,bus_nr=53
   -device cxl-rp,id=hb0rp0,bus=cxl.0,chassis=0,slot=0,port=0
   -device cxl-type2,bus=hb0rp0,volatile-memdev=t2mem0,id=cxl-t2,fmw-index=0
   -device pxb-cxl,id=cxl.1,bus=pcie.0,bus_nr=191
   -device cxl-rp,id=hb1rp0,bus=cxl.1,chassis=0,slot=2,port=0
   -device cxl-type2,bus=hb1rp0,volatile-memdev=t2mem1,id=cxl-t2b,fmw-index=1
   -M cxl-fmw.0.targets.0=cxl.0,cxl-fmw.0.size=4G,cxl-fmw.1.targets.0=cxl.1,cxl-fmw.1.size=4G

The guest kernel needs CONFIG_CXL_REGION_INVALIDATION_TEST=y. Without it, the cxl_bus reset fails in an x86 guest with "failed to prepare CXL bus reset ranges: -6".

I drove both devices with a small test module based on tools/testing/cxl/test/accel.c. It attaches each firmware-committed region with devm_cxl_probe_mem() and has no reset handlers. Then, with lockdep on:

   echo cxl_bus > /sys/bus/pci/devices/0000:36:00.0/reset_method
   echo 1 > /sys/bus/pci/devices/0000:36:00.0/reset
   echo 0 > /sys/bus/pci/slots/2/power     # second device, 0000:c0:00.0

For the hang, add msleep(10000) after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(). Start the cxl_bus reset, remove 0000:c0:00.0 through sysfs two seconds later, and power off slot 0 two seconds after that.

Quoted 8 lines

Separately, pci_cxl_reset_prepare() returns with the quiesce held on its success path only, and cxl_restore_state_after_pci_reset() releases it. With Clang 23 and CONTEXT_ANALYSIS=y passed to make, that gives five cxl_region_quiesce warnings in drivers/pci/cxl.c.

[1]: https://lore.kernel.org/all/[email protected]/

DJ

Hi Dave,

Thank you for the repro. Please let me know your opinion on the following fix. It also covers Alison's lock scope question.

Reordering the locks won't work, since pci_reset_bus_function() itself takes reset_lock. So I'd like to drop the region lock before the reset starts, and take it only for two short windows:

pci_cxl_reset_prepare()
lock(region): cxl_hdm_cache_snapshot(), set reset_pending,
cxl_hdm_ranges_collect() + cxl_hdm_ranges_request()
cxl_hdm_quiesce_flush() [no lock]
pci_reset_bus_function() [no region lock]
cxl_restore_state_after_pci_reset()
lock(region): cxl_hdm_cache_copy_decoders(), pci_cxl_restore_state(),
clear reset_pending
cxl_hdm_quiesce_flush() [no lock]

  cxl_decoder_commit():  reset_pending -> -EBUSY   [next to sanitize_active]
  disable_hdm():         also update the cached global_ctrl
  cxl_reset_execute():   same two windows for the DVSEC reset

With this,
- If a region gets torn down mid-reset, the cache is already refreshed (cxl_hdm_cache_refresh_decoder()), so restore just re-reads it with cxl_hdm_cache_copy_decoders(). Patch 17 had that call, and patch 18 dropped it when I moved the lock into prepare.
- A new commit mid-reset gets -EBUSY. Regions committed before the reset shouldn't be able to come online, since the exclusive request_mem_region() makes the kmem and pmem claims fail, as far as I can tell.

Questions
1. Is reset_pending in struct cxl_hdm_info, checked in cxl_decoder_commit(), OK?
2. Can I keep cxl_hdm_cache_copy_decoders(), now used again, instead of dropping it?
3. cxl_hdm_ranges_invalidate() and cxl_hdm_quiesce_prepare() assert the region lock is held. To flush outside it I'd relax that and rely on the HPA reservation. OK?

If this plan sounds okay, I can implement it this way in v18 (and rerun your reproducer against it)

Signature · 2 lines
Regards,
Srirangan
#63 lore raw
In reply to Alison Schofield
Quoted 37 lines · Alison Schofield
Quoted 34 lines

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

     /sys/bus/pci/devices/.../reset_method
     /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

Quoted 3 lines

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

Quoted 8 lines

Hi Srirangan,

Thanks for all the followups on review feedback. I think you answer some of my question above, 'For sysfs reset...' Could you explain the intended use cases for this reset method? Like why and when would userspace issue a CXL reset. In particular, is reset intended to be available before endpoint and region discovery have completed?

Hi Alison,

I am looking at these types of use cases: a VMM handing a Type 2 accelerator from one guest to another (the vfio-cxl series), where we need the device's memory cleared and its CXL state reset and restored, which FLR doesn't give us. Or an admin or a tool resetting a hung or errored device through reset_method and reset, without taking down the whole link. In those cases we need the CXL reset. The CXL 4.0 spec says FLRs do not affect the CXL.cache and CXL.mem protocols, and that errors in CXL.cache and CXL.mem logic cannot be recovered by an FLR.

My understanding is that it is intended to be available at enumeration, before endpoint and region discovery. I can fix the gaps in the address caching mechanism to make it work.

cxl_reset is listed at device add, like the other reset methods. It can execute once the HDM cache exists, which is right after enumeration.

Quoted 3 lines

I see how the series saves state for restoration after reset. I don't see what ensures discovery has progressed far enough for reset to be safe.

Nothing as of v17. Normalized Addressing is recorded after the HDM cache is filled, so an early reset can treat a range that isn't a HPA as one.

What I'm thinking of for v18 is a check that doesn't wait for the flag:
also reject an enabled decoder whose range isn't inside a platform CXL window (the "CXL Window" resources cxl_acpi registers). Until cxl_acpi has registered them nothing matches, so the reset is refused. The flag check stays as it is.

Both cxl_reset and cxl_bus reach it through cxl_reset_cache_prepare():

cxl_reset_cache_prepare()
cxl_hdm_quiesce_prepare()
cxl_hdm_ranges_collect() per enabled, non-zero-size decoder:
NORMALIZED flag set -> -EOPNOTSUPP (today)
range not in a CXL window -> -EOPNOTSUPP (new)
cxl_hdm_range_add()
cxl_hdm_ranges_request() reserve the ranges
cxl_hdm_ranges_invalidate() flush host caches

So a reset on a range we can't validate is refused before anything is reserved or flushed. Does this sounds like a good idea?

Quoted 10 lines

I also see DaveJ's cxl_bus deadlock report. My concern is related but separate. Even without a deadlock, a reset could hold the global region lock for up to 100 seconds plus cache maintenance and restoration, blocking discovery and region assembly on unrelated devices. Understanding the intended usage would help assess whether that disruption is acceptable. Note that my simple concern is a user issuing those cxl_reset's on repeat and blocking CXL bringup. Yeah, that's a bad user, but is there any protection against that?

Adding specific questions on patches 11, 13, and 16

I rechecked the code for avoiding the global lock. For v18, I think I can reduce both resets to take the lock briefly twice instead:

  prepare:     lock -> snapshot, reserve ranges, set reset_pending -> unlock
  do reset:    no region lock
  restore:     lock -> re-read the cache, restore, clear reset_pending -> unlock

While reset_pending is set, cxl_decoder_commit() on that device returns -EBUSY.

This way, the long lock is not held and remaining is scoped to the device being reset: only commits of that device's decoders return -EBUSY during the reset, so a region that includes it can't commit until the reset is done. The two brief windows are still global. I couldn't find a norrower option.

I posted the same proposal with some more details in reply to DaveJ
https://lore.kernel.org/linux-cxl/[email protected]/T/#mcea903d781c011fe22abf76ddd16d4f78a3c14f3
Please let me know if this could work.

Quoted 1 line

-- Alison

Signature · 2 lines
Regards,
Srirangan
#33 lore raw

Re: [PATCH v17 11/19] PCI/CXL: Cache endpoint HDM state during PCI enumeration

In reply to Alison Schofield
Quoted 11 lines · Alison Schofield
Quoted 2 lines

Cache HDM state in pci_dev->hdm after BAR resource setup and before driver binding, so reset can restore it without a bound CXL driver.

Does having this cache make the device ready for reset before its CXL endpoint and region discovery have run?

I understand why restoration needs to work without a bound CXL driver, but what establishes that the cached state is sufficiently complete for reset at this point? Some information, such as normalized addressing in patch 13, is only recorded later during discovery.

-- Alison

The cache only holds the HDM register state read at enumeration, so it
doesn't make the device ready for reset on its own. I answered this in my
reply to the cover letter: https://lore.kernel.org/linux-cxl/[email protected]/T/#m82b76ee0215d67d91f67ec6fa72036615f1adb4f

Signature · 2 lines
Regards,
Srirangan
#42 lore raw

Re: [PATCH v17 13/19] cxl: Validate and synchronize HDM ranges around reset

In reply to Alison Schofield
Quoted 17 lines · Alison Schofield
Quoted 12 lines

Refuse reset unless enabled system-physical HDM ranges can be reserved exclusively and CPU-cache invalidation is available. Invalidate before reset and again before ending IOMMU exclusion, holding range reservations until the second invalidation completes. A later patch places state restoration before the second invalidation.

Userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges: the reset fails while a conflicting resource is claimed, and no one can claim the range during the reset. It cannot see accesses by code that uses the range without claiming it, which the offline expectation also covers.

Quoted 5 lines

Reject normalized-addressing decoders because their cached ranges are not system physical addresses. Record Normalized Addressing in the cache when region discovery sets it, since the cache is filled earlier. A reset that takes its snapshot between endpoint probe and that update can still miss it.

Quoted 8 lines

What prevents reset during this window? If the snapshot misses the normalized-addressing flag can a reset proceed and use a range that is not a system physical address?

Does this mean we need to prevent reset until discovery has resolved the address interpretation, or is there another check that makes reset safe before then?

On this first part: nothing prevents it in v17. For v18 I'd reject a range that isn't inside a platform CXL window, on top of the existing flag check.

Quoted 12 lines
Quoted 10 lines

Ignore zero-size decoders because they map no address range. Refuse reset when the device decodes memory through its DVSEC ranges instead of HDM decoders, since the cache holds no range to reserve for that memory.

Hold the global cxl_rwsem.region write lock across snapshot, reset and restoration to keep the decoder state and reserved ranges stable. This also blocks region and decoder sysfs, region probe, poison operations, sanitize and region-aware event tracing across CXL devices. The Memory Clear wait lasts up to the timeout the device advertises, at most 100 seconds; cache flushes and other reset work extend the hold.

Similar to questions on previous versions and in cover letter -

Quoted 7 lines

Can a reset acquire this lock while other CXL devices are still being discovered and their regions assembled, and block that work for the full reset duration?

What limits the disruption to unrelated devices, including repeated resets? Could the locking be scoped to the affected device or regions rather than holding the global region lock throughout the wait?

On this part, yes. As posted the lock is held across the whole reset.
For v18 I'm proposing to hold it only briefly to snapshot and restore, and refuse commits of that device's decoders while it resets.

Details are in my reply to the cover letter: https://lore.kernel.org/linux-cxl/[email protected]/T/#m82b76ee0215d67d91f67ec6fa72036615f1adb4f

Signature · 2 lines
Regards,
Srirangan
#50 lore raw

Re: [PATCH v17 16/19] PCI/CXL: Expose CXL Reset as a PCI reset method

In reply to Alison Schofield
Quoted 8 lines · Alison Schofield
Quoted 2 lines

Register cxl_reset with the PCI reset-method interface and place it before FLR, which does not reset CXL.cache or CXL.mem protocol state.

Same theme, trying to understand -
Can you clarify when cxl_reset first becomes visible in reset_method and when it can actually execute? Can userspace initiate reset before endpoint and region discovery have completed, and is that intentional?

-- Alison

It is listed at device add and can run once the HDM cache exists, so yes,
before discovery completes. That isn't intended for ranges discovery
hasn't resolved. Proposing a fix in my reply to the cover letter: https://lore.kernel.org/linux-cxl/[email protected]/T/#m82b76ee0215d67d91f67ec6fa72036615f1adb4f

Signature · 2 lines
Regards,
Srirangan
#38 lore raw

Re: [PATCH v17 12/19] PCI/CXL: Add CXL Device Reset sequencing

In reply to Lucero Palau, Alejandro
Quoted 61 lines · Alejandro

External email: Use caution opening links or attachments

Quoted 12 lines · Srirangan Madhavan

Implement CXL Device Reset for eligible Type 2 devices: disable CXL.cache, perform supported writeback, drain transactions, prepare the IOMMU, initiate reset with Memory Clear enabled, and wait for completion.

Observe the 100 ms post-reset quiet period before polling Status2, and treat an all-ones read as not ready. Wait for the timeout the device advertises, up to 100 seconds, and access only Status2 until reset completion, error or expiry, as CXL 4.0 section 9.7.3 requires. Control2 cleanup runs only afterwards. Treat Control2 command bits as transient state, restore cache policy on exit, preserve the primary error, and abort when IOMMU preparation fails.

Quoted 4 lines

Reuse Device DVSEC discovery from cache initialization and keep the reset entry point declaration private to PCI core.

Hi Srirangan,

A concern regarding IOMMU handling below. If it turns to be unfounded, you can add my review tag.

Thank you,

Alejandro

<snip>

drivers/pci/cxl.c void pci_cxl_hdm_cache_release(struct pci_dev *pdev) · line 401

Quoted 10 lines
drivers/pci/cxl.c +10 -0
+static int __cxl_reset_execute(struct pci_dev *pdev, int dvsec, u16 cap)
+{
+     int rc, rc2;
+
+     if (!pci_wait_for_pending_transaction(pdev)) {
+             pci_err(pdev, "timed out waiting for pending transactions\n");
+             return -ETIMEDOUT;
+     }
+
+     rc = pci_dev_reset_iommu_prepare(pdev);

I'm not sure if this is safe enough. I can see a situation where a Type2 device could not be using CXL.mem and CXL.cache but CXL.io. This would imply no CXL initialization from the Type2 driver but:

    1) Such a driver could be giving functionality without CXL

    2) The device belonging to an IOMMU domain which such functionality
is using

    3) The HDM decoder range as a system resource is free.

Quoted 7 lines

If I am right, a CXL reset could happen, and although it should not be triggered by user space under these circumstances, the door is open ...

The solution would be, currently, to check for a  driver not bound to the device in an IOMMU enabled system. I say currently because CXL.cache will need extra work with IOMMU mapping which are not yet there.

Hi Alejandro,

Thanks for the review.

I don't think I can add a bound-driver check in this series. For VFIO passthrough, vfio-pci is always the bound driver at every reset VFIO starts, and VFIO needs an IOMMU outside no-IOMMU mode, so the check would always fire. VFIO resets through the PCI reset methods, so a refusal would make every reset of a Type 2 device fail or fall back to FLR, which isn't what passthrough needs. Manish describes the vfio-cxl side in his reply to patch 15 of the v6 series:
https://lore.kernel.org/linux-cxl/[email protected]/

I guess the same exposure also exists for FLR and the other methods, which go through the same pci_dev_reset_iommu_prepare()?
For now, the reset file is root-only, and a CXL.io-only device doesn't reach cxl_reset: cxl_reset_function() needs CXL.cache and CXL.mem enabled, otherwise it returns -ENOTTY and the normal methods are used. If this is okay, can we revisit the point once vfio-cxl's reset model is settled and the CXL.cache IOMMU side lands as you mentioned?

Signature · 2 lines
Regards,
Srirangan
maintainer
#61 lore raw
In reply to Srirangan Madhavan
Quoted 151 lines · Srirangan Madhavan
Quoted 118 lines · Dave Jiang

External email: Use caution opening links or attachments

Quoted 34 lines · Srirangan Madhavan

Hi folks,

This series adds CXL Reset for Type 2 devices through the existing PCI reset_method and reset sysfs attributes. It disables CXL.cache, performs supported cache writeback, initiates CXL Reset with Memory Clear, and restores cached HDM decoder and CXL Device DVSEC state before PCI use resumes. Active HDM ranges are reserved and CPU caches invalidated before and after reset. The method remains limited to eligible single-function devices with both CXL.cache and CXL.mem enabled. CXL bus reset restores the same cached state and flushes the host and device caches around the reset.

The reset sequence follows the CXL 4.0 specification [4], including CXL.cache disable, optional cache writeback, CXL Reset Memory Clear, ResetComplete polling, and ResetError reporting. Sections 9.7.2 and 9.7.3 define the completion timeout encodings and reset access restrictions.

The userspace ABI is the existing PCI reset interface:

     /sys/bus/pci/devices/.../reset_method
     /sys/bus/pci/devices/.../reset

Userspace selects "cxl_reset" in reset_method and triggers the reset through reset. Following Dan's v6 feedback, this uses the PCI interface instead of adding a memdev-specific sysfs ABI.

For sysfs reset, the generic PCI path invokes the driver's reset_prepare() callback when provided and disables PCI I/O, memory decoding, and bus mastering. The CXL path reserves affected HDM ranges exclusively and blocks IOMMU translations where applicable. It does not offline memory or revoke mappings: userspace is expected to offline CXL.mem users before reset. The reservation enforces this for claimed ranges by failing the reset while a conflicting resource is claimed [9].

Quoted 3 lines

The global region lock is held from snapshot through restoration. Memory Clear completion is awaited for the timeout the device advertises, up to 100 seconds, so the lock can be held for that long plus cache flushes.

I think holding it across the bus reset can deadlock with pciehp and a PCI remove. I tested in QEMU with two cxl-type2 devices from Manish's RFC [1].

For a device in a pciehp slot, pci_reset_bus_function() ends up in pciehp_reset_slot(), which takes the slot's reset_lock. The reset still holds cxl_rwsem.region at that point.

Two other tasks can complete a cycle. pciehp_ist() for that slot can hold reset_lock and wait for pci_rescan_remove_lock in pciehp_unconfigure_device(). A PCI remove of a second Type 2 device can hold pci_rescan_remove_lock while cxl_decoder_detach() waits for cxl_rwsem.region.

On v17 as posted, lockdep reports the cycle:

   [   60.891789] WARNING: possible circular locking dependency detected
   [   60.893014] irq/24-pciehp/103 is trying to acquire lock:
   [   60.893367] ffff888072b4f128 (&cxl_memdev_key){+.+.}-{4:4}, at: device_del+0x8d/0x580
                  but task is already holding lock:
   [   60.894498] ffffffff84699e80 (pci_rescan_remove_lock){+.+.}-{4:4}, at: pciehp_unconfigure_device+0x93/0x210 [...]
                  -> #3 (&ctrl->reset_lock){++++}-{4:4}:
   [   60.916794]        down_write_nested+0x80/0x170
   [   60.917826]        pciehp_reset_slot+0x6c/0xc0
   [   60.918893]        pci_reset_hotplug_slot+0x5c/0x90
   [   60.919928]        pci_reset_bus_function+0x161/0x330
   [   60.920951]        cxl_reset_bus_function+0x1c6/0x280
   [   60.921958]        __pci_reset_function_locked+0x96/0x170
   [   60.922990]        pci_reset_function+0xc8/0x180
   [   60.923977]        reset_store+0x84/0xd0
   [...]
                  -> #2 (cxl_rwsem.region){++++}-{4:4}:
   [...]
   [   61.013490] Chain exists of:
                    &cxl_memdev_key --> &ctrl->reset_lock --> pci_rescan_remove_lock

With a test-only msleep() after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(), it turns into a real hang. The reset, a sysfs remove of the second device and a power off of the first device's slot all got stuck.

Two region reads blocked behind the reset as well. A read of region1/commit timed out after 5 s, and cxl list -R stayed in D state in decoders_committed_show().

To reproduce, I used Manish's RFC as posted. It allows one cxl-type2 per pxb-cxl, so each device has its own host bridge and window. On q35 with cxl=on, plus the memory backends:

   -device pxb-cxl,id=cxl.0,bus=pcie.0,bus_nr=53
   -device cxl-rp,id=hb0rp0,bus=cxl.0,chassis=0,slot=0,port=0
   -device cxl-type2,bus=hb0rp0,volatile-memdev=t2mem0,id=cxl-t2,fmw-index=0 -device pxb-cxl,id=cxl.1,bus=pcie.0,bus_nr=191
   -device cxl-rp,id=hb1rp0,bus=cxl.1,chassis=0,slot=2,port=0
   -device cxl-type2,bus=hb1rp0,volatile-memdev=t2mem1,id=cxl-t2b,fmw-index=1 -M cxl-fmw.0.targets.0=cxl.0,cxl-fmw.0.size=4G,cxl-fmw.1.targets.0=cxl.1,cxl-fmw.1.size=4G

The guest kernel needs CONFIG_CXL_REGION_INVALIDATION_TEST=y. Without it, the cxl_bus reset fails in an x86 guest with "failed to prepare CXL bus reset ranges: -6".

I drove both devices with a small test module based on tools/testing/cxl/test/accel.c. It attaches each firmware-committed region with devm_cxl_probe_mem() and has no reset handlers. Then, with lockdep on:

   echo cxl_bus > /sys/bus/pci/devices/0000:36:00.0/reset_method echo 1 > /sys/bus/pci/devices/0000:36:00.0/reset
   echo 0 > /sys/bus/pci/slots/2/power     # second device, 0000:c0:00.0

For the hang, add msleep(10000) after cxl_region_quiesce_lock() in pci_cxl_reset_prepare(). Start the cxl_bus reset, remove 0000:c0:00.0 through sysfs two seconds later, and power off slot 0 two seconds after that.

Quoted 8 lines

Separately, pci_cxl_reset_prepare() returns with the quiesce held on its success path only, and cxl_restore_state_after_pci_reset() releases it. With Clang 23 and CONTEXT_ANALYSIS=y passed to make, that gives five cxl_region_quiesce warnings in drivers/pci/cxl.c.

[1]: https://lore.kernel.org/all/[email protected]/

DJ

Hi Dave,

Thank you for the repro. Please let me know your opinion on the following fix. It also covers Alison's lock scope question.

Reordering the locks won't work, since pci_reset_bus_function() itself takes reset_lock. So I'd like to drop the region lock before the reset starts, and take it only for two short windows:

  pci_cxl_reset_prepare()
      lock(region):  cxl_hdm_cache_snapshot(), set reset_pending, cxl_hdm_ranges_collect() + cxl_hdm_ranges_request() cxl_hdm_quiesce_flush()                      [no lock] pci_reset_bus_function()                         [no region lock] cxl_restore_state_after_pci_reset()
      lock(region):  cxl_hdm_cache_copy_decoders(), pci_cxl_restore_state(), clear reset_pending
      cxl_hdm_quiesce_flush()                      [no lock]

  cxl_decoder_commit():  reset_pending -> -EBUSY   [next to sanitize_active] disable_hdm():         also update the cached global_ctrl cxl_reset_execute():   same two windows for the DVSEC reset

Quoted 9 lines

With this,
 - If a region gets torn down mid-reset, the cache is already refreshed (cxl_hdm_cache_refresh_decoder()), so restore just re-reads it with cxl_hdm_cache_copy_decoders(). Patch 17 had that call, and patch 18 dropped it when I moved the lock into prepare.
 - A new commit mid-reset gets -EBUSY. Regions committed before the reset shouldn't be able to come online, since the exclusive request_mem_region() makes the kmem and pmem claims fail, as far as I can tell.

I think the direction looks good.

Quoted 4 lines

Questions
 1. Is reset_pending in struct cxl_hdm_info, checked in cxl_decoder_commit(), OK?

Yes.

Quoted 2 lines

 2. Can I keep cxl_hdm_cache_copy_decoders(), now used again, instead of dropping it?

Yes.

Quoted 3 lines

 3. cxl_hdm_ranges_invalidate() and cxl_hdm_quiesce_prepare() assert the region lock is held. To flush outside it I'd relax that and rely on the HPA reservation. OK?

Sounds reasonable.

Quoted 4 lines

If this plan sounds okay, I can implement it this way in v18 (and rerun your reproducer against it)

Sounds good!