Skip to contentSkip to conversation

PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support

PATCH Superseded Priyank Rathod 2 participants 7 messages Sep 4

Subsystems (3)

v2 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v2 cover PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support

Hi Bjorn, Ilpo, and the PCI community,

This patch series introduces upstream Linux kernel support for PCIe Lane Margining at Receiver (LMR) per PCI Express Base Specification Revision 7.0 / 6.0 (§ 7.7.11 and § 8.4.4).

During the review of the previous v7 standalone LMR submission
(https://lore.kernel.org/linux-pci/[email protected]/),
Ilpo Järvinen pointed out that feature drivers resolving link partners duplicate link traversal logic that is already present in drivers such as ASPM:

"This feels like duplicating similar functionality with the aspm driver
that also wants to infer ends of the link when giving a pci_dev in. The aspm driver currently does that within, but it kind of duplicating pci_bus. It would be nice to avoid the duplication and have something similar for this in PCI core."

In response to this feedback, the implementation is factored into a clean, modular 3-patch stack:

1. Patch 1/3 (PCI: Add pcie_get_link_endpoints() helper):
Standardized, race-safe helper in drivers/pci/pci.c and include/linux/pci.h to identify both ends of a point-to-point PCIe link. Safely inspects the subordinate bus under down_read(&pci_bus_sem) and acquires a reference (pci_dev_get()), paired symmetrically with pcie_put_link_endpoints(). Filters for Function 0 (with ARI support), validates bridge ownership (child->self == pdev) to prevent ABA pointer reuse, and handles RCiEP and empty downstream ports (-ENODEV).

2. Patch 2/3 (PCI/ASPM: Add pci_aspm_inhibit() helper for temporary link state suppression):
Reference-counted mechanism (aspm_inhibit_cnt) in drivers/pci/pcie/aspm.c to temporarily disable ASPM state transitions (L0s, L1, L1SS) on an active link. Guarantees callers hold down_read(&pci_bus_sem) (via lockdep_assert_held_read), eliminating deadlocks and preventing power-saving transitions while hardware link characterization is in progress.

3. Patch 3/3 (PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support):
Implements the core LMR driver (CONFIG_PCIE_LMR) in drivers/pci/pcie/margin.c exposing a debugfs interface under /sys/kernel/debug/pci/pcie_lmr_<dev>/. Strictly self-contained: 0 modified lines in drivers/pci/pci.c, pci-driver.c, or core drivers/pci/pci.h. Exposes clean lifecycle hooks in drivers/pci/probe.c and drivers/pci/remove.c, supports 2D timing and voltage margining across physical receivers (0..6), enforces Function 0 endpoint filtering (§ 7.7.11), and includes an exhaustive kselftest suite (tools/testing/selftests/pcie_lmt/).

- Capability Discovery (§ 7.7.11): Probed via Extended Capability ID 0x27 on Gen4+ (>= 16 GT/s) physical links. Differentiates optional support on Gen4/Gen5 from mandatory capability presence on Gen6+ (>= 64 GT/s).
- Multi-Function Device Scope (§ 7.7.11): Enforces that capability registration is strictly restricted to Function 0 on Endpoints / Upstream Ports.
- Payload Decoding (Table 4-77, Cmd 88h): Accurately decodes Margin Control Capabilities (Bits 0..4); preserves Bits 7:5 as reserved 0b.
- Direction Encodings (§ 4.2.18.1.2): Enforces that Left/Right and Up/Down direction bits remain 0b for symmetric receivers (Bits 6 & 7 reserved 0b).
- Multi-Receiver Concurrency (§ 4.2.18.2): Governed strictly by MIndErrorSampler. If MIndErrorSampler == 0b (main data sampler), at most one receiver across the link is margined at a time.
- Autonomous Speed & Width Transitions (§ 7.5.3.7, § 7.5.3.17, § 8.4.4): Software sequencing disables Downstream Component before Upstream Component on enablement, and restores Upstream Component before Downstream Component on teardown. Restoration is unconditional via pcie_capability_clear_and_set_word() (serialized by pci_lock), eliminating trylock failure traps.

Ingress paths (margin_enable_write and pci_lmr_exit) strictly follow the canonical PCI locking DAG:
down_read(&pci_bus_sem)

    -> pci_dev_lock(downstream_port)
      -> pci_dev_lock(upstream_port)
        -> mutex_lock(&mdev->lock)
          -> spin_lock_irqsave(&aspm_lock)

Key Concurrency Guarantees:
1. Hot-Swap Identity Invariance: When disabling LMR, dynamic endpoint resolution is completely bypassed. Teardown binds strictly to the session-saved mdev->partner, which is read and pinned with pci_dev_get() under mutex_lock(&mdev->lock).
2. Surprise Removal & Fault Hardening: Hardware register accesses check pci_dev_is_disconnected() and PCI_POSSIBLE_ERROR() guards, preventing MMIO or config space bus aborts when hardware is pulled.
3. Power Management Synchronization: Both link partners are pinned in D0 using pm_runtime_resume_and_get() during enablement, and symmetrically released via pm_runtime_put() on teardown. System suspend hooks into pci_pm_prepare() where all devices in the hierarchy are guaranteed to be in D0.
4. Security Teardown Order: In pci_destroy_dev(), pci_lmr_exit() is called after pci_tsm_destroy(), preserving D0 state for TSM link operations (PCIe IDE unbind and SPDM cryptographic session teardown).

- Build: Clean compile on x86_64 and ARM64; make W=1 drivers/pci/ (0 warnings).
- Linters: checkpatch.pl clean across all 3 patches (0 errors, 0 warnings).
- Kselftest: tools/testing/selftests/pcie_lmt/pcie_lmt.sh expanded to 287 lines, covering positive and negative boundary tests (syntax clean with bash -n).
- Pre-Commit AI Review (Sashiko AI):
* Patch 1 (f34fdf7f5c6b): Reviewed — Clean (0 issues).
* Patch 2 (6adc680a727f): Reviewed — Clean (0 issues).
* Patch 3 (c62b5f92af63): Reviewed — Clean (0 issues, "No issues found.").

---
Changes in v2:
- Decomposed monolithic LMR driver into a 3-patch stack with dedicated core helpers:
* Patch 1: PCI core link endpoint discovery helper (pcie_get_link_endpoints()).
* Patch 2: Core ASPM temporary inhibition helper (pci_aspm_inhibit()).
* Patch 3: PCIe Lane Margining at Receiver driver and debugfs interface.
- Core Scope Discipline: Confined LMR logic exclusively to drivers/pci/pcie/margin.c and include/linux/pci.h forward declarations (0 modified lines in pci.c/pci-driver.c).
- Endpoint Discovery Hardening:
* Handled RCiEP and empty downstream buses returning -ENODEV.
* Added Function 0 resolution (pcie_find_link_upstream_func0()) supporting PCIe ARI.
* Added bridge ownership verification (child->self == pdev) to prevent ABA races.
* Added symmetric pcie_put_link_endpoints() to balance pci_dev_get() references.
- ASPM Inhibit Hardening:
* Added lockdep_assert_held_read(&pci_bus_sem) to pci_aspm_inhibit_locked().
* Added reference counting (aspm_inhibit_cnt) to support nested/concurrent calls.
- Hot-Swap & Concurrency Protections:
* Eliminated hot-swap identity mismatch in margin_enable_write() by binding teardown

    strictly to session-saved mdev->partner instead of re-evaluating endpoints.

* Added mutex protection when reading and pinning mdev->partner to eliminate UAF races.
* Converted autonomous speed/width restoration to unconditional register write via pcie_capability_clear_and_set_word(), eliminating trylock failure degradation.
- Specification Alignments (PCIe Base Spec r7.0):
* Aligned Extended Capability ID 0x27 to § 7.7.11 and § 8.4.4.
* Enforced Function 0 restriction on Endpoints / Upstream Ports (§ 7.7.11).
* Preserved Reserved Bits 7:5 in Command 88h capabilities response.
* Implemented MIndErrorSampler-based concurrency for multi-receiver links (§ 4.2.18.2).
* Corrected direction bit encoding to 0b for symmetric receivers (§ 4.2.18.1.2).
- Kselftest Overhaul:
* Extended test coverage from 105 to 287 lines, adding comprehensive boundary
and negative validation tests.
- Link to v1: https://lore.kernel.org/r/[email protected]
- Link to v7 (monolithic LMR): https://lore.kernel.org/linux-pci/[email protected]/

---
Priyank Rathod (3):
PCI: Add pcie_get_link_endpoints() helper
PCI/ASPM: Add pci_aspm_inhibit() helper for temporary link state suppression PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support

 Documentation/PCI/index.rst                  |    1 +
 Documentation/PCI/pcie-lmr.rst               |  174 +++
 MAINTAINERS                                  |    8 +
 drivers/pci/pci.c                            |  152 +++
 drivers/pci/pci.h                            |    8 +
 drivers/pci/pcie/Kconfig                     |   12 +
 drivers/pci/pcie/Makefile                    |    1 +
 drivers/pci/pcie/aspm.c                      |  100 ++
 drivers/pci/pcie/margin.c                    | 1592 ++++++++++++++++++++++++++
 drivers/pci/probe.c                          |    1 +
 drivers/pci/remove.c                         |    2 +-
 include/linux/pci.h                          |   17 +
 include/uapi/linux/pci_regs.h                |   18 +
 tools/testing/selftests/Makefile             |    1 +
 tools/testing/selftests/pcie_lmt/Makefile    |    3 +
 tools/testing/selftests/pcie_lmt/pcie_lmt.sh |  287 +++++
 16 files changed, 2376 insertions(+), 1 deletion(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260831-pcie-link-endpoints-978e100d5d06

Best regards,

Signature · 1 line
Priyank Rathod <[email protected]>
#1 lore raw

PATCH v2 1/3 PCI: Add pcie_get_link_endpoints() helper

In PCIe topologies, physical links are point-to-point connections between an Upstream Component (Downstream Port, such as a Root Port or Switch Downstream Port) and a Downstream Component (Upstream Port, such as an Endpoint or Switch Upstream Port), per PCIe Base Specification Revision 7.0 / 6.0 sec 1.3.1.

Drivers across drivers/pci/ (such as Lane Margining at Receiver and AER recovery) coordinate operations across both ends of a PCIe link:
- Lane Margining at Receiver (LMR): requires resolving both link endpoints to establish hierarchical locking and runtime PM pinning.
- AER/DPC Recovery: identifies the parent bridge to coordinate link resets and recovery sequences.

Introduce pcie_get_link_endpoints() and pcie_put_link_endpoints() in the PCI core to provide a standardized, symmetric, and race-safe helper:
- Validates output pointer arguments and initializes them to NULL.
- Resolves Physical Functions for VFs via pci_physfn().
- For Endpoints: resolves parent Downstream Port via pci_upstream_bridge().
- Resolves base Function 0 symmetrically on the link subordinate bus for both non-ARI multi-function devices and ARI (Alternative Routing-ID Interpretation) devices where all functions (0..255) belong to the same logical device.
- Safely inspects subordinate bus and bus device lists under down_read(&pci_bus_sem), verifying bridge ownership (child->self == pdev) to eliminate ABA pointer identity and UAF races with concurrent hot-remove.
- Symmetrically acquires references via pci_dev_get() on both resolved endpoints on success, or returns -ENODEV if either end is unresolved.

Callers release acquired references using pcie_put_link_endpoints().

---
 drivers/pci/pci.c   | 152 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/linux/pci.h |   5 ++
 2 files changed, 157 insertions(+)
drivers/pci/pci.c +152 -0
index b2879a6be5f8..d1e3d6e3f5b1 100644
@@ -4654,6 +4654,158 @@ int pcie_retrain_link(struct pci_dev *pdev, bool use_lt)
 	return rc;
 }
 
+/*
+ * pcie_get_subordinate_bus_locked() - Safely obtain active subordinate bus.
+ * Validates that a child bus matching bridge @pdev is actively linked in
+ * pdev->bus->children under pci_bus_sem. Verifies bridge ownership
+ * (child->self == pdev) to prevent Use-After-Free or ABA pointer identity
+ * races during concurrent hot-remove (pci_remove_bus / pci_remove_bus_device).
+ */
+static struct pci_bus *pcie_get_subordinate_bus_locked(struct pci_dev *pdev)
+{
+	struct pci_bus *child;
+
+	lockdep_assert_held_read(&pci_bus_sem);
+
+	if (!pdev->subordinate)
+		return NULL;
+
+	list_for_each_entry(child, &pdev->bus->children, node) {
+		if (child->self == pdev)
+			return child;
+	}
+
+	return NULL;
+}
+
+/*
+ * pcie_find_link_upstream_func0() - Find the base Function 0 device on a link.
+ * Handles ARI (Alternative Routing-ID Interpretation) and multi-function
+ * topologies uniformly and symmetrically.
+ */
+static struct pci_dev *pcie_find_link_upstream_func0(struct pci_bus *bus,
+						     struct pci_dev *hint)
+{
+	struct pci_dev *child;
+
+	if (!bus)
+		return NULL;
+
+	if (pci_ari_enabled(bus)) {
+		/*
+		 * In ARI, all functions (0..255) on the bus belong to the same
+		 * logical device. Base Function 0 is strictly devfn == 0.
+		 */
+		list_for_each_entry(child, &bus->devices, bus_list) {
+			if (child->devfn == 0)
+				return pci_dev_get(child);
+		}
+	} else if (hint) {
+		/* Non-ARI: find Function 0 in the same device slot */
+		if (PCI_FUNC(hint->devfn) == 0)
+			return pci_dev_get(hint);
+
+		list_for_each_entry(child, &bus->devices, bus_list) {
+			if (PCI_SLOT(child->devfn) == PCI_SLOT(hint->devfn) &&
+			    PCI_FUNC(child->devfn) == 0)
+				return pci_dev_get(child);
+		}
+	} else {
+		/* Non-ARI from Downstream Port: prefer devfn 0, then any Func 0 */
+		list_for_each_entry(child, &bus->devices, bus_list) {
+			if (child->devfn == 0)
+				return pci_dev_get(child);
+		}
+		list_for_each_entry(child, &bus->devices, bus_list) {
+			if (PCI_FUNC(child->devfn) == 0)
+				return pci_dev_get(child);
+		}
+	}
+
+	/* Fall back to hint or first device on subordinate bus */
+	if (hint)
+		return pci_dev_get(hint);
+
+	child = list_first_entry_or_null(&bus->devices, struct pci_dev, bus_list);
+	return pci_dev_get(child);
+}
+
+/**
+ * pcie_get_link_endpoints - Identify Upstream and Downstream ends of a PCIe link
+ * @pdev: Any PCIe device on the link (Downstream Port or Endpoint)
+ * @downstream_port: Output pointer to Downstream Port (Upstream Component)
+ * @upstream_port: Output pointer to Upstream Port (Downstream Component)
+ *
+ * Identifies both ends of a point-to-point PCIe link. Acquires a reference
+ * (pci_dev_get()) on both discovered endpoints on success. Callers must release
+ * acquired references with pcie_put_link_endpoints() or pci_dev_put().
+ *
+ * Return: 0 on success, -EINVAL if @pdev is NULL or not PCIe, or -ENODEV if
+ * either end of the link cannot be resolved.
+ */
+int pcie_get_link_endpoints(struct pci_dev *pdev,
+			    struct pci_dev **downstream_port,
+			    struct pci_dev **upstream_port)
+{
+	struct pci_dev *down = NULL, *up = NULL;
+
+	if (!downstream_port || !upstream_port)
+		return -EINVAL;
+
+	*downstream_port = NULL;
+	*upstream_port = NULL;
+
+	if (!pdev || !pci_is_pcie(pdev))
+		return -EINVAL;
+
+	pdev = pci_physfn(pdev);
+	if (!pdev->bus)
+		return -ENODEV;
+
+	if (pcie_downstream_port(pdev)) {
+		struct pci_bus *subordinate;
+
+		down_read(&pci_bus_sem);
+		subordinate = pcie_get_subordinate_bus_locked(pdev);
+		if (subordinate)
+			up = pcie_find_link_upstream_func0(subordinate, NULL);
+		up_read(&pci_bus_sem);
+		down = pci_dev_get(pdev);
+	} else {
+		down = pci_dev_get(pci_upstream_bridge(pdev));
+		down_read(&pci_bus_sem);
+		up = pcie_find_link_upstream_func0(pdev->bus, pdev);
+		up_read(&pci_bus_sem);
+		if (!up)
+			up = pci_dev_get(pdev);
+	}
+
+	if (!down || !up || !pci_is_pcie(down) || !pci_is_pcie(up)) {
+		pci_dev_put(down);
+		pci_dev_put(up);
+		return -ENODEV;
+	}
+
+	*downstream_port = down;
+	*upstream_port = up;
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(pcie_get_link_endpoints);
+
+/**
+ * pcie_put_link_endpoints - Release references acquired by pcie_get_link_endpoints
+ * @downstream_port: Downstream Port pointer
+ * @upstream_port: Upstream Port pointer
+ */
+void pcie_put_link_endpoints(struct pci_dev *downstream_port,
+			     struct pci_dev *upstream_port)
+{
+	pci_dev_put(upstream_port);
+	pci_dev_put(downstream_port);
+}
+EXPORT_SYMBOL_GPL(pcie_put_link_endpoints);
+
 /**
  * pcie_wait_for_link_delay - Wait until link is active or inactive
  * @pdev: Bridge device
include/linux/pci.h +5 -0
index d31a8d107b1e..671d8db5898e 100644
@@ -1272,6 +1272,11 @@ struct resource *pci_find_parent_resource(const struct pci_dev *dev,
 u8 pci_swizzle_interrupt_pin(const struct pci_dev *dev, u8 pin);
 int pci_get_interrupt_pin(struct pci_dev *dev, struct pci_dev **bridge);
 u8 pci_common_swizzle(struct pci_dev *dev, u8 *pinp);
+int pcie_get_link_endpoints(struct pci_dev *pdev,
+			    struct pci_dev **downstream_port,
+			    struct pci_dev **upstream_port);
+void pcie_put_link_endpoints(struct pci_dev *downstream_port,
+			     struct pci_dev *upstream_port);
 struct pci_dev *pci_dev_get(struct pci_dev *dev);
 void pci_dev_put(struct pci_dev *dev);
 DEFINE_FREE(pci_dev_put, struct pci_dev *, if (_T) pci_dev_put(_T))
Signature · 1 line
2.55.0.1003.g10538fe699-goog
#2 lore raw

Re: [PATCH v2 1/3] PCI: Add pcie_get_link_endpoints() helper

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines

In PCIe topologies, physical links are point-to-point connections between an Upstream Component (Downstream Port, such as a Root Port or Switch Downstream Port) and a Downstream Component (Upstream Port, such as an Endpoint or Switch Upstream Port), per PCIe Base Specification Revision 7.0 / 6.0 sec 1.3.1.

Drivers across drivers/pci/ (such as Lane Margining at Receiver and AER recovery) coordinate operations across both ends of a PCIe link:
- Lane Margining at Receiver (LMR): requires resolving both link endpoints to establish hierarchical locking and runtime PM pinning.
- AER/DPC Recovery: identifies the parent bridge to coordinate link resets and recovery sequences.

Quoted 8 lines

Introduce pcie_get_link_endpoints() and pcie_put_link_endpoints() in the PCI core to provide a standardized, symmetric, and race-safe helper:
[ ... ]
Callers release acquired references using pcie_put_link_endpoints().

Sashiko has reviewed this patch and found no issues. It looks great!

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

PATCH v2 2/3 PCI/ASPM: Add pci_aspm_inhibit() helper for temporary link state suppression

In reply to Priyank Rathod

Currently, pci_disable_link_state() permanently disables ASPM on a PCIe link by setting link->aspm_disable. However, several kernel subsystems and driver operations require temporary ASPM inhibition without permanently disabling power management:
- PCIe Lane Margining at Receiver (LMR): receiver testing requires the link to remain continuously in L0 throughout the test duration.
- Device firmware updates (e.g. NICs and NVMe controllers): link latency or L1 transitions during firmware flashing can disrupt device communication.
- Secondary Bus Reset and link retraining sequences: prevent unexpected L1/L1SS entry during link reset and recovery.

Because pci_disable_link_state() cannot be reversed by pci_enable_link_state() to clear link->aspm_disable, drivers previously attempted manual manipulations of PCI_EXP_LNKCTL (ASPMC). This bypasses the ASPM driver, risking race conditions and state desynchronization.

Introduce pci_aspm_inhibit() and pci_aspm_inhibit_locked() in the ASPM driver:
- Updates pcie_aspm_get_link() to resolve links for Root Ports, Switch Downstream Ports, and Endpoints uniformly.
- Validates PCIe capability and resolves the link state under pci_bus_sem and aspm_lock in __pci_aspm_inhibit() before inspecting aspm_disabled with rate-limited logging, eliminating log floods and TOCTOU races with concurrent device removal.
- Tracks inhibition via an aspm_inhibit_cnt reference counter on struct pcie_link_state.
- When the first inhibitor requests suppression (aspm_inhibit_cnt == 1), forces the link to L0 via pcie_config_aspm_link(link, 0), which enforces spec-compliant disable sequencing (Downstream Component before Upstream Component per PCIe Base Specification Revision 7.0 sec 7.5.3.7 & Table 7-24 "Link Control Register Description").
- Waits under aspm_lock on initial inhibit to guarantee concurrent callers cannot access the link before the hardware transition stabilizes.
- When all inhibitors have released (aspm_inhibit_cnt == 0), restores the configured ASPM policy to hardware (Upstream Component before Downstream Component per sec 7.5.3.7 & Table 7-24).

---
 drivers/pci/pcie/aspm.c | 100 ++++++++++++++++++++++++++++++++++++++++++++++++
 include/linux/pci.h     |   6 +++
 2 files changed, 106 insertions(+)
drivers/pci/pcie/aspm.c +100 -0
index 95ac34a34bd5..4a85d029708b 100644
@@ -18,6 +18,7 @@
 #include <linux/of.h>
 #include <linux/pci.h>
 #include <linux/pci_regs.h>
+#include <linux/delay.h>
 #include <linux/errno.h>
 #include <linux/pm.h>
 #include <linux/init.h>
@@ -245,6 +246,9 @@ struct pcie_link_state {
 	u32 clkpm_enabled:1;		/* Current Clock PM state */
 	u32 clkpm_default:1;		/* Default Clock PM state by BIOS */
 	u32 clkpm_disable:1;		/* Clock PM disabled */
+
+	/* Temporary ASPM Inhibit state */
+	unsigned int aspm_inhibit_cnt;	/* Reference count for ASPM inhibition */
 };
 
 static bool aspm_disabled, aspm_force;
@@ -1055,6 +1059,10 @@ static void pcie_config_aspm_link(struct pcie_link_state *link, u32 state)
 	/* Enable only the states that were not explicitly disabled */
 	state &= (link->aspm_capable & ~link->aspm_disable);
 
+	/* If ASPM is temporarily inhibited, force state to 0 (L0) */
+	if (link->aspm_inhibit_cnt)
+		state = 0;
+
 	/* Can't enable any substates if L1 is not enabled */
 	if (!(state & PCIE_LINK_STATE_L1))
 		state &= ~PCIE_LINK_STATE_L1SS;
@@ -1467,6 +1475,9 @@ static struct pcie_link_state *pcie_aspm_get_link(struct pci_dev *pdev)
 	if (!pci_is_pcie(pdev))
 		return NULL;
 
+	if (pcie_downstream_port(pdev))
+		return pdev->link_state;
+
 	bridge = pci_upstream_bridge(pdev);
 	if (!bridge || !pci_is_pcie(bridge))
 		return NULL;
@@ -1531,6 +1542,95 @@ static int __pci_disable_link_state(struct pci_dev *pdev, int state, bool locked
 	return 0;
 }
 
+/*
+ * __pci_aspm_inhibit() - Inhibit or restore ASPM L0s/L1 on a PCIe link.
+ *
+ * PCIe Base Specification Revision 7.0 sec 7.5.3.7 & Table 7-24 ("Link
+ * Control Register Description"):
+ * - To disable ASPM, software on Downstream Component (Endpoint / Upstream
+ *   Port) must disable ASPM prior to disabling ASPM on Upstream Component
+ *   (Root Port / Downstream Port).
+ * - To enable ASPM, software on Upstream Component (Root Port / Downstream
+ *   Port) must enable ASPM prior to enabling ASPM on Downstream Component
+ *   (Endpoint / Upstream Port).
+ */
+static int __pci_aspm_inhibit(struct pci_dev *pdev, bool inhibit, bool locked)
+{
+	struct pcie_link_state *link;
+	int ret = 0;
+
+	if (!pdev || !pci_is_pcie(pdev))
+		return -EINVAL;
+
+	pdev = pci_physfn(pdev);
+
+	if (!locked)
+		down_read(&pci_bus_sem);
+	mutex_lock(&aspm_lock);
+
+	link = pcie_aspm_get_link(pdev);
+	if (!link) {
+		ret = -EINVAL;
+		goto unlock;
+	}
+
+	if (aspm_disabled) {
+		pci_warn_once(pdev, "can't inhibit ASPM; OS doesn't have ASPM control\n");
+		ret = -EPERM;
+		goto unlock;
+	}
+
+	if (inhibit) {
+		link->aspm_inhibit_cnt++;
+		if (link->aspm_inhibit_cnt == 1) {
+			pcie_config_aspm_link(link, 0);
+			usleep_range(2000, 3000);
+		}
+	} else {
+		if (WARN_ON_ONCE(link->aspm_inhibit_cnt == 0)) {
+			ret = -EINVAL;
+			goto unlock;
+		}
+
+		link->aspm_inhibit_cnt--;
+		if (link->aspm_inhibit_cnt == 0)
+			pcie_config_aspm_link(link, policy_to_aspm_state(link));
+	}
+
+unlock:
+	mutex_unlock(&aspm_lock);
+	if (!locked)
+		up_read(&pci_bus_sem);
+
+	return ret;
+}
+
+int pci_aspm_inhibit_locked(struct pci_dev *pdev, bool inhibit)
+{
+	lockdep_assert_held_read(&pci_bus_sem);
+
+	return __pci_aspm_inhibit(pdev, inhibit, true);
+}
+EXPORT_SYMBOL_GPL(pci_aspm_inhibit_locked);
+
+/**
+ * pci_aspm_inhibit - Temporarily inhibit or restore ASPM on a PCIe link
+ * @pdev: PCI device on the link
+ * @inhibit: True to inhibit ASPM (transition to L0), false to release
+ *
+ * Increments/decrements a reference counter on the link's ASPM state. When
+ * @inhibit is true, forces the link to L0 on the first inhibitor. When @inhibit
+ * is false, restores the configured ASPM state once all inhibitors have
+ * released their claims.
+ *
+ * Return: 0 on success, or a negative errno.
+ */
+int pci_aspm_inhibit(struct pci_dev *pdev, bool inhibit)
+{
+	return __pci_aspm_inhibit(pdev, inhibit, false);
+}
+EXPORT_SYMBOL_GPL(pci_aspm_inhibit);
+
 int pci_disable_link_state_locked(struct pci_dev *pdev, int state)
 {
 	lockdep_assert_held_read(&pci_bus_sem);
include/linux/pci.h +6 -0
index 671d8db5898e..b0ce8ee8d622 100644
@@ -1956,6 +1956,8 @@ int pci_disable_link_state(struct pci_dev *pdev, int state);
 int pci_disable_link_state_locked(struct pci_dev *pdev, int state);
 int pci_enable_link_state(struct pci_dev *pdev, int state);
 int pci_enable_link_state_locked(struct pci_dev *pdev, int state);
+int pci_aspm_inhibit(struct pci_dev *pdev, bool inhibit);
+int pci_aspm_inhibit_locked(struct pci_dev *pdev, bool inhibit);
 void pcie_no_aspm(void);
 bool pcie_aspm_support_enabled(void);
 bool pcie_aspm_enabled(struct pci_dev *pdev);
@@ -1968,6 +1970,10 @@ static inline int pci_enable_link_state(struct pci_dev *pdev, int state)
 { return 0; }
 static inline int pci_enable_link_state_locked(struct pci_dev *pdev, int state)
 { return 0; }
+static inline int pci_aspm_inhibit(struct pci_dev *pdev, bool inhibit)
+{ return 0; }
+static inline int pci_aspm_inhibit_locked(struct pci_dev *pdev, bool inhibit)
+{ return 0; }
 static inline void pcie_no_aspm(void) { }
 static inline bool pcie_aspm_support_enabled(void) { return false; }
 static inline bool pcie_aspm_enabled(struct pci_dev *pdev) { return false; }
Signature · 1 line
2.55.0.1003.g10538fe699-goog
#4 lore raw

Re: [PATCH v2 2/3] PCI/ASPM: Add pci_aspm_inhibit() helper for temporary link state suppression

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 20 lines

Currently, pci_disable_link_state() permanently disables ASPM on a PCIe link by setting link->aspm_disable. However, several kernel subsystems and driver operations require temporary ASPM inhibition without permanently disabling power management:
- PCIe Lane Margining at Receiver (LMR): receiver testing requires the link to remain continuously in L0 throughout the test duration.
- Device firmware updates (e.g. NICs and NVMe controllers): link latency or L1 transitions during firmware flashing can disrupt device communication.
- Secondary Bus Reset and link retraining sequences: prevent unexpected L1/L1SS entry during link reset and recovery.

Because pci_disable_link_state() cannot be reversed by pci_enable_link_state() to clear link->aspm_disable, drivers previously attempted manual manipulations of PCI_EXP_LNKCTL (ASPMC). This [ ... ]
- When all inhibitors have released (aspm_inhibit_cnt == 0), restores the configured ASPM policy to hardware (Upstream Component before Downstream Component per sec 7.5.3.7 & Table 7-24).

Quoted 1 line

Sashiko has reviewed this patch and found no issues. It looks great!

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

PATCH v2 3/3 PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support

In reply to Priyank Rathod

Per PCIe Base Specification r6.0, sec 8.4.4 ("Lane Margining at Receiver"), PCIe devices operating at 16.0 GT/s (Gen 4) or higher data rates support the Lane Margining at Receiver Extended Capability (ID 0x27), and it is mandatory for receivers operating at 64.0 GT/s (Gen 6) or higher data rates. Lane Margining allows software to evaluate high-speed link margins by measuring timing and voltage steps for each individual physical lane and receiver.

Add driver and debugfs support for PCIe Lane Margining at Receiver:

- Add Lane Margining at Receiver Extended Capability register definitions (PCI_EXT_CAP_ID_LMR, PCI_LMR_PORT_CAP, PCI_LMR_PORT_STS, PCI_LMR_LANE_CTRL, PCI_LMR_LANE_STS) to <uapi/linux/pci_regs.h>.
- Add Kconfig option CONFIG_PCIE_LMR (under drivers/pci/pcie/Kconfig) dependent on DEBUG_FS.
- Implement drivers/pci/pcie/margin.c to probe the capability on Gen4+ links and expose per-device debugfs entries under:
/sys/kernel/debug/pci/pcie_lmr_<pci_dev_name>/
providing control over margining enablement, receiver selection, and execution of timing/voltage margin step commands. Distinguish between missing mandatory LMR capability on Gen6+ vs optional on Gen4/Gen5.
- Hook pci_lmr_init() into pci_init_capabilities() during device probe in drivers/pci/probe.c and pci_lmr_exit() into drivers/pci/remove.c.
- Add kselftest script under tools/testing/selftests/pcie_lmt/pcie_lmt.sh to test debugfs capability reads, enablement, and stepping.
- Add MAINTAINERS entry for PCIe Lane Margining at Receiver (LMR).

---
 Documentation/PCI/index.rst                  |    1 +
 Documentation/PCI/pcie-lmr.rst               |  174 +++
 MAINTAINERS                                  |    8 +
 drivers/pci/pci.h                            |    8 +
 drivers/pci/pcie/Kconfig                     |   12 +
 drivers/pci/pcie/Makefile                    |    1 +
 drivers/pci/pcie/margin.c                    | 1592 ++++++++++++++++++++++++++
 drivers/pci/probe.c                          |    1 +
 drivers/pci/remove.c                         |    2 +-
 include/linux/pci.h                          |    6 +
 include/uapi/linux/pci_regs.h                |   18 +
 tools/testing/selftests/Makefile             |    1 +
 tools/testing/selftests/pcie_lmt/Makefile    |    3 +
 tools/testing/selftests/pcie_lmt/pcie_lmt.sh |  287 +++++
 14 files changed, 2113 insertions(+), 1 deletion(-)
Documentation/PCI/index.rst +1 -0
index 5d720d2a415e..9170c98cbf3f 100644
@@ -20,3 +20,4 @@ PCI Bus Subsystem
    controller/index
    boot-interrupts
    tph
+   pcie-lmr
Documentation/PCI/pcie-lmr.rst new file +174 -0

174 lines not on this page · raw message

MAINTAINERS +8 -0
index 3a19da74d00c..312cd68a66be 100644
@@ -21293,6 +21293,14 @@ F:	Documentation/devicetree/bindings/pci/qcom,sa8255p-pcie-ep.yaml
 F:	drivers/pci/controller/dwc/pcie-qcom-common.c
 F:	drivers/pci/controller/dwc/pcie-qcom-ep.c
 
+PCIE LANE MARGINING AT RECEIVER (LMR)
+M:	Priyank Rathod <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	Documentation/PCI/pcie-lmr.rst
+F:	drivers/pci/pcie/margin.c
+F:	tools/testing/selftests/pcie_lmt/
+
 PCMCIA SUBSYSTEM
 M:	Dominik Brodowski <[email protected]>
 S:	Odd Fixes
drivers/pci/pci.h +8 -0
index ba3c3fddddc2..0d84b693bc47 100644
@@ -1071,6 +1071,14 @@ static inline void pci_no_tph(void) { }
 static inline void pci_tph_init(struct pci_dev *dev) { }
 #endif
 
+#ifdef CONFIG_PCIE_LMR
+void pci_lmr_init(struct pci_dev *dev);
+void pci_lmr_exit(struct pci_dev *dev);
+#else
+static inline void pci_lmr_init(struct pci_dev *dev) { }
+static inline void pci_lmr_exit(struct pci_dev *dev) { }
+#endif
+
 #ifdef CONFIG_PCIE_PTM
 void pci_ptm_init(struct pci_dev *dev);
 void pci_save_ptm_state(struct pci_dev *dev);
drivers/pci/pcie/Kconfig +12 -0
index 207c2deae35f..3b021ca2fe84 100644
@@ -137,6 +137,18 @@ config PCIE_PTM
 	  This is only useful if you have devices that support PTM, but it
 	  is safe to enable even if you don't.
 
+config PCIE_LMR
+	bool "PCI Express Lane Margining at Receiver Support"
+	depends on DEBUG_FS
+	help
+	  This enables the PCI Express Lane Margining at Receiver support.
+	  Lane Margining allows software to determine the voltage and
+	  timing margin of each lane on a PCIe link (16.0 GT/s and above).
+	  The margining data is exposed via debugfs.
+
+	  This is only useful if you have devices that support lane
+	  margining, but it is safe to enable even if you don't.
+
 config PCIE_EDR
 	bool "PCI Express Error Disconnect Recover support"
 	depends on PCIE_DPC && ACPI
drivers/pci/pcie/Makefile +1 -0
index b0b43a18c304..aac45ae0402e 100644
@@ -13,4 +13,5 @@ obj-$(CONFIG_PCIEAER_INJECT)	+= aer_inject.o
 obj-$(CONFIG_PCIE_PME)		+= pme.o
 obj-$(CONFIG_PCIE_DPC)		+= dpc.o
 obj-$(CONFIG_PCIE_PTM)		+= ptm.o
+obj-$(CONFIG_PCIE_LMR)		+= margin.o
 obj-$(CONFIG_PCIE_EDR)		+= edr.o
drivers/pci/pcie/margin.c new file +1592 -0

1,592 lines not on this page · raw message

drivers/pci/probe.c +1 -0
index 27008e2ea5af..98c84fdb0a97 100644
@@ -2666,6 +2666,7 @@ static void pci_init_capabilities(struct pci_dev *dev)
 	pci_pasid_init(dev);		/* Process Address Space ID */
 	pci_acs_init(dev);		/* Access Control Services */
 	pci_ptm_init(dev);		/* Precision Time Measurement */
+	pci_lmr_init(dev);		/* Lane Margining at Receiver */
 	pci_aer_init(dev);		/* Advanced Error Reporting */
 	pci_dpc_init(dev);		/* Downstream Port Containment */
 	pci_rcec_init(dev);		/* Root Complex Event Collector */
drivers/pci/remove.c +1 -1
index e711ac1d4e38..f78f0c654011 100644
@@ -37,12 +37,12 @@ static void pci_destroy_dev(struct pci_dev *dev)
 	platform_pci_remove_wake(dev);
 	pci_doe_sysfs_teardown(dev);
 	pci_npem_remove(dev);
-
 	/*
 	 * While device is in D0 drop the device from TSM link operations
 	 * including unbind and disconnect (IDE + SPDM teardown).
 	 */
 	pci_tsm_destroy(dev);
+	pci_lmr_exit(dev);
 
 	device_del(&dev->dev);
 
include/linux/pci.h +6 -0
index b0ce8ee8d622..fbb85ad124b5 100644
@@ -353,6 +353,8 @@ struct rcec_ea;
  *			number resources to allow for hierarchy expansion.
  * @is_pciehp:		PCIe Hot-Plug Capable bridge.
  */
+struct pci_margin_dev;
+
 struct pci_dev {
 	struct list_head bus_list;	/* Node in per-bus list */
 	struct pci_bus	*bus;		/* Bus this device is on */
@@ -532,6 +534,10 @@ struct pci_dev {
 	atomic_t	ptm_enable_cnt;
 	u8		ptm_granularity;
 #endif
+#ifdef CONFIG_PCIE_LMR
+	u16			lmr_cap;	/* Lane Margining Capability */
+	struct pci_margin_dev	*lmr;
+#endif
 #ifdef CONFIG_PCI_MSI
 	void __iomem	*msix_base;
 	raw_spinlock_t	msi_lock;
include/uapi/linux/pci_regs.h +18 -0
index facaa324bd86..90cbe310e62f 100644
@@ -757,6 +757,7 @@
 #define PCI_EXT_CAP_ID_VF_REBAR 0x24	/* VF Resizable BAR */
 #define PCI_EXT_CAP_ID_DLF	0x25	/* Data Link Feature */
 #define PCI_EXT_CAP_ID_PL_16GT	0x26	/* Physical Layer 16.0 GT/s */
+#define PCI_EXT_CAP_ID_LMR	0x27	/* Lane Margining at Receiver */
 #define PCI_EXT_CAP_ID_NPEM	0x29	/* Native PCIe Enclosure Management */
 #define PCI_EXT_CAP_ID_PL_32GT  0x2A    /* Physical Layer 32.0 GT/s */
 #define PCI_EXT_CAP_ID_DOE	0x2E	/* Data Object Exchange */
@@ -1181,6 +1182,23 @@
 #define  PCI_PL_16GT_LE_CTRL_USP_TX_PRESET_MASK		0x000000F0
 #define  PCI_PL_16GT_LE_CTRL_USP_TX_PRESET_SHIFT	4
 
+/* Lane Margining at Receiver */
+#define PCI_LMR_PORT_CAP		0x04	/* Margining Port Capabilities */
+#define  PCI_LMR_PORT_CAP_USES_SW_READY	0x0001	/* Margining Uses Software Ready */
+#define PCI_LMR_PORT_STS		0x06	/* Margining Port Status */
+#define  PCI_LMR_PORT_STS_MARGIN_READY	0x0001	/* Margining Ready */
+#define  PCI_LMR_PORT_STS_SW_READY	0x0002	/* Margining SW Ready */
+#define PCI_LMR_LANE_CTRL		0x08	/* Margining Lane Control */
+#define  PCI_LMR_LANE_CTRL_RX_NUM	0x0007	/* Receiver Number */
+#define  PCI_LMR_LANE_CTRL_MTYPE	0x0038	/* Margining Type */
+#define  PCI_LMR_LANE_CTRL_USAGE	0x0040	/* Margining Usage Model */
+#define  PCI_LMR_LANE_CTRL_PAYLOAD	0xFF00	/* Margining Payload */
+#define PCI_LMR_LANE_STS		0x0A	/* Margining Lane Status */
+#define  PCI_LMR_LANE_STS_RX_NUM	0x0007	/* Receiver Number */
+#define  PCI_LMR_LANE_STS_MTYPE		0x0038	/* Margining Type */
+#define  PCI_LMR_LANE_STS_USAGE		0x0040	/* Margining Usage Model */
+#define  PCI_LMR_LANE_STS_PAYLOAD	0xFF00	/* Margining Payload */
+
 /* Physical Layer 32.0 GT/s */
 #define PCI_PL_32GT_LE_CTRL	0x20	/* Lane Equalization Control Register */
 
tools/testing/selftests/Makefile +1 -0
index 2d960626750e..f762540b500e 100644
@@ -93,6 +93,7 @@ TARGETS += net/tcp_ao
 TARGETS += nolibc
 TARGETS += pci_endpoint
 TARGETS += pcie_bwctrl
+TARGETS += pcie_lmt
 TARGETS += perf_events
 TARGETS += pidfd
 TARGETS += pid_namespace
tools/testing/selftests/pcie_lmt/Makefile new file +3 -0
new file mode 100644
index 000000000000..36ac85937d78
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0
+TEST_PROGS = pcie_lmt.sh
+include ../lib.mk
tools/testing/selftests/pcie_lmt/pcie_lmt.sh new file +287 -0

287 lines not on this page · raw message

Signature · 1 line
2.55.0.1003.g10538fe699-goog
#6 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Manual port type checking for downstream/upstream components misses PCI_EXP_TYPE_PCIE_BRIDGE…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Manual port type checking for downstream/upstream components misses PCI_EXP_TYPE_PCIE_BRIDGE, causing lock inversion deadlocks and violating PCIe spec initialization order. --

commit 1a49529648026f2ee499ea16e34fdf520b1c02fb
Author: Priyank Rathod <[email protected]>

PCI/pcie: Add PCIe Lane Margining at Receiver (LMR) support

This patch adds support for PCIe Lane Margining at Receiver (LMR) capability (mandatory for Gen 6+ links, optional for Gen 4 and 5). It provides a debugfs interface to view capabilities and execute margin timing/voltage commands.

Quoted 5 lines
drivers/pci/pcie/margin.c new file +0 -0
new file mode 100644
index 0000000000000..1dde5aa928c74

[ ... ]

drivers/pci/pcie/margin.c line 304

Quoted 9 lines
drivers/pci/pcie/margin.c new file +9 -0
+static void pci_lmr_get_ports(struct pci_margin_dev *mdev,
+			      struct pci_dev **downstream_port,
+			      struct pci_dev **upstream_port)
+{
+	struct pci_dev *dev = mdev->dev;
+	struct pci_dev *partner = mdev->partner;
+
+	if (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT ||
+	    pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) {

[Severity: High]
Does this manual port type check miss PCI_EXP_TYPE_PCIE_BRIDGE?

If the device is a PCI-to-PCIe bridge, it acts as a downstream-facing port but would fall into the else branch here. This incorrectly classifies the bridge as an upstream-facing port, reversing the downstream_port and upstream_port assignments.

Quoted 7 lines
drivers/pci/pcie/margin.c new file +7 -0
+		*downstream_port = dev;
+		*upstream_port = partner;
+	} else {
+		*downstream_port = partner;
+		*upstream_port = dev;
+	}
+}

[ ... ]

Quoted 4 lines
drivers/pci/pcie/margin.c new file +4 -0
+static ssize_t margin_enable_write(struct file *file,
+				   const char __user *user_buf, size_t count,
+				   loff_t *ppos)
+{

[ ... ]

Quoted 2 lines
drivers/pci/pcie/margin.c new file +2 -0
+	} else {
+		struct pci_dev *partner;

[ ... ]

drivers/pci/pcie/margin.c

Quoted 2 lines
drivers/pci/pcie/margin.c new file +2 -0
+		if (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT ||
+		    pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) {

[Severity: High]
Can this missing PCI_EXP_TYPE_PCIE_BRIDGE check cause an AB-BA lock inversion?

When LMR is enabled via debugfs on a PCI-to-PCIe bridge, pcie_get_link_endpoints() correctly identifies it as a downstream-facing port and locks it first. During disable, the missing check reverses the assignment, locking the link partner first and risking a deadlock if called concurrently.

Quoted 7 lines
drivers/pci/pcie/margin.c new file +7 -0
+			downstream_port = pci_dev_get(dev);
+			upstream_port = partner;
+		} else {
+			downstream_port = partner;
+			upstream_port = pci_dev_get(dev);
+		}
+	}

[ ... ]

Quoted 5 lines
drivers/pci/pcie/margin.c new file +5 -0
+void pci_lmr_exit(struct pci_dev *dev)
+{
+	struct pci_margin_dev *mdev;
+	struct pci_dev *partner;
+	struct pci_dev *downstream_port, *upstream_port;

[ ... ]

drivers/pci/pcie/margin.c

Quoted 2 lines
drivers/pci/pcie/margin.c new file +2 -0
+	if (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT ||
+	    pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) {

[Severity: High]
Can this similarly cause a lock inversion deadlock during device removal?

If LMR is being concurrently manipulated, the missing PCI_EXP_TYPE_PCIE_BRIDGE check reverses the locking order for the downstream and upstream ports, potentially freezing the kernel.

Quoted 6 lines
drivers/pci/pcie/margin.c new file +6 -0
+		downstream_port = dev;
+		upstream_port = partner;
+	} else {
+		downstream_port = partner;
+		upstream_port = dev;
+	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3