Skip to contentSkip to conversation

PCI: Add DOE support for endpoint

PATCH New Aksh Garg 2 participants 9 messages Jun 23

Subsystems (3)
lore
Share & tools
lore

Aksh Garg

author
#0 lore raw

v6 cover PCI: Add DOE support for endpoint

This patch series introduces the framework for supporting the Data Object Exchange (DOE) feature for PCIe endpoint devices. Please refer to the documentation added in patch 4 for details on the feature and implementation architecture.

The implementation provides a common framework for all PCIe endpoint controllers, not specific to any particular SoC vendor.

Currently, there are no EPC drivers which support DOE. Hence, there are no users of the APIs introduced in this series. To avoid dead code being merged to the kernel, this series can't be merged as of now, hence I am posting this series to be reviewed by the time the EPC driver gets submitted as discussed at [1].
[1]: https://lore.kernel.org/all/[email protected]/

The changes since v1 are documented in the respective patch descriptions.

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1 (RFC): https://lore.kernel.org/all/[email protected]/

Below is a code demonstration showing the integration of DOE-EP APIs with EPC drivers.

Note: The provided code is just to show how an EPC driver is expected to
utilize the pci_ep_doe_process_request() and pci_ep_doe_abort() APIs, and might not cover all the corner cases. The below implementation also expects the EPC hardware to have some memory buffer to store the data from(for) write_mailbox(read_mailbox) DOE capability registers.

============================================================================

/* ========== DOE Completion Callback (invoked by DOE-EP core) ========== */

static void doe_completion_cb(struct pci_epc *epc, u8 func_no, u16 cap_offset,
int status, u16 vendor, u8 type, void *response_pl, size_t response_pl_sz)

{
	struct epc_driver *drv = epc_get_drvdata(epc);
	u32 *response = (u32 *)response_pl;
	u32 header1, header2;
	int payload_dw, i;
	
	if (readl(drv->base + PF_DOE_CTRL_REG(func_no, cap_offset)) & DOE_CTRL_ABORT) {
		/* Aborted: do not send response */
		goto free;
	}

	if (status < 0) {
		/* Error: set ERROR bit in DOE Status register */
		writel(1 << DOE_STATUS_ERROR,
		       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));
		goto free;
	}

	/* Success: write DOE headers first, then response to the read memory */

	/* Header 1: Vendor ID (bits 15:0) | Type (bits 23:16) */
	header1 = (type << 16) | vendor;
	writel(header1, drv->base + PF_DOE_RD_MEMORY_WR_REG(func_no, cap_offset));

	/* Header 2: Length in DW (including 2 DW of headers + payload) */
	payload_dw = DIV_ROUND_UP(response_pl_sz, sizeof(u32));
	header2 = 2 + payload_dw;  /* 2 header DWs + payload */
	writel(header2, drv->base + PF_DOE_RD_MEMORY_WR_REG(func_no, cap_offset));
	
	/* Set READY bit to signal response ready */
	writel(1 << DOE_STATUS_READY,
	       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));

	/* Write response payload DWORDs to Read memory */
	for (i = 0; i < payload_dw; i++)
		writel(response[i],
		       drv->base + PF_DOE_RD_MEMORY_WR_REG(func_no, cap_offset));

	/* Wait for the memory to empty before clearing the READY bit */
	while (!RD_MEMORY_EMPTY()) {/* wait */}

	writel(0 << DOE_STATUS_READY,
	       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));

free:

	/* unset BUSY bit */
	writel(0 << DOE_STATUS_BUSY,
	       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));

	kfree(response_pl);
}

/* ========== DOE Interrupt Handler (triggered on GO bit from root complex) ========== */

static irqreturn_t doe_interrupt_handler(int irq, void *priv)

{
	struct epc_driver *drv = priv;
	u16 cap_offset = extract_cap_offset_from_irq(irq);
	u8 func_no = extract_func_from_irq(irq);
	u32 header1, header2, length_dw, *request;
	u16 vendor;
	u8 type;
	int i, ret;

	/* Read first header DWORD: Vendor ID (bits 15:0) | Type (bits 23:16) */
	header1 = readl(drv->base + PF_DOE_WR_MEMORY_RD_REG(func_no, cap_offset));
	vendor = header1 & 0xFFFF;
	type = (header1 >> 16) & 0xFF;

	/* Read second header DWORD: Length in DW (includes 2 DW of headers) */
	header2 = readl(drv->base + PF_DOE_WR_MEMORY_RD_REG(func_no, cap_offset));
	length_dw = header2 & 0x3FFFF;  /* Bits 17:0 */

	if (!length_dw)
		length_dw = PCI_DOE_MAX_LENGTH;

	length_dw -= 2;  /* Subtract 2 DW of headers to get payload length */
	/* Allocate buffer for complete request (headers + payload) */
	request = kzalloc(length_dw * sizeof(u32), GFP_ATOMIC);
	if (!request) {
		writel(1 << DOE_STATUS_ERROR,
		       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));
		return IRQ_HANDLED;
	}

	/* Read remaining payload DWORDs from Write memory */
	for (i = 0; i < length_dw; i++) {
		while (WR_MEMORY_EMPTY()) { /* wait */ }
		request[i] = readl(drv->base + PF_DOE_WR_MEMORY_RD_REG(func_no, cap_offset));
	}
	
	mutex_lock(&lock);
	/* Check the ABORT bit, if set then return */
	if (readl(drv->base + PF_DOE_CTRL_REG(func_no, cap_offset)) & DOE_CTRL_ABORT) {
		kfree(request);
		mutex_unlock(&lock);
		return IRQ_HANDLED;
	}

	/* Set BUSY bit */
	writel(1 << DOE_STATUS_BUSY,
	       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));
	mutex_unlock(&lock);

	/* Hand off to DOE-EP core for asynchronous processing */
	ret = pci_ep_doe_process_request(drv->epc, func_no, cap_offset,
					 vendor, type, (void *)request,
					 length_dw * sizeof(u32),
					 doe_completion_cb);
	if (ret) {
		writel(1 << DOE_STATUS_ERROR,
		       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));
		kfree(request);
	}

	return IRQ_HANDLED;
}

/* ========== Abort Handler (triggered on ABORT bit from root complex) ========== */

static irqreturn_t doe_abort_handler(int irq, void *priv)

{
	struct epc_driver *drv = priv;
	u16 cap_offset = extract_cap_offset_from_irq(irq);
	u8 func_no = extract_func_from_irq(irq);
	
	mutex_lock(&lock);
	
	/* call abort API only if BUSY bit set (pci_ep_doe_process_request() called) */
	if (readl(drv->base + PF_DOE_STATUS_REG(func_no, cap_offset)) & DOE_STATUS_BUSY)
		pci_ep_doe_abort(drv->epc, func_no, cap_offset);
	
	mutex_unlock(&lock);

	/* Discard Write memory contents */
	writel(DOE_WR_MEMORY_CTRL_DISCARD,
	       drv->base + PF_DOE_WR_MEMORY_CTRL_REG(func_no, cap_offset));

	/* Clear status bits */
	writel((0 << DOE_STATUS_ERROR) | (0 << DOE_STATUS_READY),
	       drv->base + PF_DOE_STATUS_REG(func_no, cap_offset));

	return IRQ_HANDLED;
}

====================================================================================

Aksh Garg (4):
PCI/DOE: Move common definitions to the header file
PCI: endpoint: Add DOE mailbox support for endpoint functions
PCI: endpoint: Add support for DOE initialization and setup in EPC
core
Documentation: PCI: Add documentation for DOE endpoint support

 Documentation/PCI/endpoint/index.rst          |   1 +
 .../PCI/endpoint/pci-endpoint-doe.rst         | 352 +++++++++++
 drivers/pci/doe.c                             |  11 -
 drivers/pci/endpoint/Kconfig                  |  14 +
 drivers/pci/endpoint/Makefile                 |   1 +
 drivers/pci/endpoint/pci-ep-doe.c             | 591 ++++++++++++++++++
 drivers/pci/endpoint/pci-epc-core.c           | 101 +++
 drivers/pci/pci.h                             |  51 ++
 include/linux/pci-doe.h                       |   8 +
 include/linux/pci-epc.h                       |   9 +
 10 files changed, 1128 insertions(+), 11 deletions(-)
 create mode 100644 Documentation/PCI/endpoint/pci-endpoint-doe.rst
 create mode 100644 drivers/pci/endpoint/pci-ep-doe.c
Signature · 1 line
2.34.1
author
#1 lore raw

PATCH v6 1/4 PCI/DOE: Move common definitions to the header file

Move common macros and structures from drivers/pci/doe.c to drivers/pci/pci.h to allow reuse across root complex and endpoint DOE implementations.

PCI_DOE_MAX_LENGTH macro can be used outside the PCI core as well, hence move the macro to include/linux/pci-doe.h.

These changes prepare the groundwork for the DOE endpoint implementation that will reuse these common definitions.

---

Changes from v5 to v6:
- None.

Changes from v4 to v5:
- None.

Changes from v3 to v4:
- None.

Changes from v2 to v3:
- Rebased on 7.1-rc1.

Changes since v1:
- Moved the common macros that need not be visible outside the PCI core to drivers/pci/pci.h instead to include/linux/pci-doe.h as suggested by Lukas Wunner
- Removed the redundant empty inlines guarded with CONFIG_PCI_DOE in include/linux/pci-doe.h.

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1: https://lore.kernel.org/all/[email protected]/

 drivers/pci/doe.c       | 11 -----------
 drivers/pci/pci.h       |  9 +++++++++
 include/linux/pci-doe.h |  3 +++
 3 files changed, 12 insertions(+), 11 deletions(-)
drivers/pci/doe.c +0 -11
index 7b41da4ec11a..e8d9e95644b3 100644
@@ -28,12 +28,6 @@
 #define PCI_DOE_TIMEOUT HZ
 #define PCI_DOE_POLL_INTERVAL	(PCI_DOE_TIMEOUT / 128)
 
-#define PCI_DOE_FLAG_CANCEL	0
-#define PCI_DOE_FLAG_DEAD	1
-
-/* Max data object length is 2^18 dwords */
-#define PCI_DOE_MAX_LENGTH	(1 << 18)
-
 /**
  * struct pci_doe_mb - State for a single DOE mailbox
  *
@@ -63,11 +57,6 @@ struct pci_doe_mb {
 #endif
 };
 
-struct pci_doe_feature {
-	u16 vid;
-	u8 type;
-};
-
 /**
  * struct pci_doe_task - represents a single query/response
  *
drivers/pci/pci.h +9 -0
index 4a14f88e543a..5844deee2b5f 100644
@@ -683,6 +683,15 @@ struct pci_sriov {
 	bool		drivers_autoprobe; /* Auto probing of VFs by driver */
 };
 
+/* DOE Mailbox state flags */
+#define PCI_DOE_FLAG_CANCEL	0
+#define PCI_DOE_FLAG_DEAD	1
+
+struct pci_doe_feature {
+	u16 vid;
+	u8 type;
+};
+
 #ifdef CONFIG_PCI_DOE
 void pci_doe_init(struct pci_dev *pdev);
 void pci_doe_destroy(struct pci_dev *pdev);
include/linux/pci-doe.h +3 -0
index bd4346a7c4e7..abb9b7ae8029 100644
@@ -19,6 +19,9 @@ struct pci_doe_mb;
 #define PCI_DOE_FEATURE_CMA 1
 #define PCI_DOE_FEATURE_SSESSION 2
 
+/* Max data object length is 2^18 dwords */
+#define PCI_DOE_MAX_LENGTH		(1 << 18)
+
 struct pci_doe_mb *pci_find_doe_mailbox(struct pci_dev *pdev, u16 vendor,
 					u8 type);
 
Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH v6 1/4] PCI/DOE: Move common definitions to the header file

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

Move common macros and structures from drivers/pci/doe.c to drivers/pci/pci.h to allow reuse across root complex and endpoint DOE implementations.

PCI_DOE_MAX_LENGTH macro can be used outside the PCI core as well, hence move the macro to include/linux/pci-doe.h.

Quoted 7 lines

These changes prepare the groundwork for the DOE endpoint implementation that will reuse these common definitions.

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
author
#3 lore raw

PATCH v6 2/4 PCI: endpoint: Add DOE mailbox support for endpoint functions

In reply to Aksh Garg

DOE (Data Object Exchange) is a standard PCIe extended capability feature defined in PCI Express Base Specification Revision 7.0, Section 6.30. It provides a communication mechanism primarily used for implementing PCIe security features such as device authentication, and secure link establishment. Think of DOE as a sophisticated mailbox system built into PCIe. The root complex can send structured requests to the endpoint device through DOE mailboxes, and the endpoint device responds with appropriate data.

Add the DOE support for PCIe endpoint devices, enabling endpoint functions to process the DOE requests from the host. The implementation provides framework APIs for EPC core driver and controller drivers to register mailboxes, and request processing with workqueues ensuring sequential handling per mailbox, and parallel handling across mailboxes. The Discovery protocol is handled internally by the DOE core.

This implementation complements the existing DOE implementation for root complex in drivers/pci/doe.c.

---

Changes from v5 yo v6:
- Addressed the review comments provided by Bjorn Helgaas at v5
- Used xa_lock_irqsave() instead of xa_lock() in pci_ep_doe_get_mailbox()
- Added a spinlock to protect the work_queue of the doe_mb struct from being destroyed while being called

Changes from v4 to v5:
- Addressed the review comments by Sashiko
- Added refcount per DOE Mailbox to fix Use-After-Free bug
- Change in the Abort Sequence:
* Instead of waiting on flush_workqueue() to clear the CANCEL flag, return immediately after setting the CANCEL flag. The CANCEL flag gets cleared in signal_task_complete(), allowing the mailbox to accept new requests
* Abort sequence handling in various scenarios is updated and explained in the documentation at PATCH 4/4

Changes from v3 to v4:
- Used 'Returns' instead of 'RETURNS' in the function docstrings to comply with kernel-doc format, as suggested by Manivannan Sadhasivam.
- In pci_ep_doe_process_request(), changed the type of request buffer from "const void *" to "void *", as the ownership is transferred to DOE-EP framework, which is responsible to free the buffer.
- Added "struct pci_epc *epc" to typedef "pci_ep_doe_complete_t", to be used by the EPC driver.

Changes from v2 to v3:
- Rebased on 7.1-rc1.

Changes since v1:
- Moved the DOE-EP core file to drivers/pci/endpoint/pci-ep-doe.c, and corresponding Kconfig and Makefile to match the existing naming scheme, as suggested by Niklas Cassel.
- Renamed the config from PCI_DOE_EP to PCI_ENDPOINT_DOE
- Moved the function declarations that need not be visible outside the PCI core to drivers/pci/pci.h instead to include/linux/pci-doe.h as suggested by Lukas Wunner
- Converted from synchronous to asynchronous request processing:
* Removed wait_for_completion() from pci_ep_doe_process_request()
* Function returns immediately after queuing to workqueue, hence removed private data for completion in the task structure
* Added completion callback as an additional argument to pci_ep_doe_process_request(), which takes the response and status parameters as arguments (along with other required arguments), hence removed task_status in the task structure
* Created a typedef pci_ep_doe_complete_t for completion callback
* Removed the pci_ep_doe_task_complete() function, as it would not be required anymore with these changes
* Moved from INIT_WORK_ONSTACK() to INIT_WORK(), to initialize the work on heap instead of stack
* signal_task_complete() now invokes the completion callback, once the protocol handler completes its task
- Changed from dynamic xarray-based protocol registration to static array:
* Removed the register/unregister protocol APIs
* Replaced the dynamic xarray with static array of struct pci_doe_protocol
* Added discovery protocol to static array, instead of treating it specially, hence removed the special handling for Discovery protocol in doe_ep_task_work()
* Updated pci_ep_doe_handle_discovery() and pci_ep_doe_find_protocol() accordingly.
- Memory Management:
* DOE core frees request buffer in signal_task_complete()
or during error handling
* pci_ep_doe_process_request() defines response_pl and response_pl_sz as NULL and 0 respectively, whose pointer is passed to the protocol handler, hence removed the arguments void **response, size_t *response_sz to this function.
- Task structure refactoring:
* Response buffer: void **response_pl to void *response_pl
* Response size: size_t *response_pl_sz to size_t response_pl_sz
* Changed the completion callback to type pci_ep_doe_complete_t
* Removed void *private and int task_status
- Updated documentation comments of the functions according to the changes

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1: https://lore.kernel.org/all/[email protected]/

 drivers/pci/endpoint/Kconfig      |  14 +
 drivers/pci/endpoint/Makefile     |   1 +
 drivers/pci/endpoint/pci-ep-doe.c | 591 ++++++++++++++++++++++++++++++
 drivers/pci/pci.h                 |  42 +++
 include/linux/pci-doe.h           |   5 +
 include/linux/pci-epc.h           |   3 +
 6 files changed, 656 insertions(+)
 create mode 100644 drivers/pci/endpoint/pci-ep-doe.c
drivers/pci/endpoint/Kconfig +14 -0
index 8dad291be8b8..15ae16aaa58f 100644
@@ -36,6 +36,20 @@ config PCI_ENDPOINT_MSI_DOORBELL
 	  doorbell. The RC can trigger doorbell in EP by writing data to a
 	  dedicated BAR, which the EP maps to the controller's message address.
 
+config PCI_ENDPOINT_DOE
+	bool "PCI Endpoint Data Object Exchange (DOE) support"
+	depends on PCI_ENDPOINT
+	help
+	  This enables support for Data Object Exchange (DOE) protocol
+	  on PCI Endpoint controllers. It provides a communication
+	  mechanism through mailboxes, primarily used for PCIe security
+	  features.
+
+	  Say Y here if you want be able to communicate using PCIe DOE
+	  mailboxes.
+
+	  If unsure, say N.
+
 source "drivers/pci/endpoint/functions/Kconfig"
 
 endmenu
drivers/pci/endpoint/Makefile +1 -0
index b4869d52053a..1fa176b6792b 100644
@@ -7,3 +7,4 @@ obj-$(CONFIG_PCI_ENDPOINT_CONFIGFS)	+= pci-ep-cfs.o
 obj-$(CONFIG_PCI_ENDPOINT)		+= pci-epc-core.o pci-epf-core.o\
 					   pci-epc-mem.o functions/
 obj-$(CONFIG_PCI_ENDPOINT_MSI_DOORBELL)	+= pci-ep-msi.o
+obj-$(CONFIG_PCI_ENDPOINT_DOE)		+= pci-ep-doe.o
drivers/pci/endpoint/pci-ep-doe.c new file +591 -0

591 lines not on this page · raw message

drivers/pci/pci.h +42 -0

54 lines not on this page · raw message

include/linux/pci-doe.h +5 -0
index abb9b7ae8029..c46e42f3ce78 100644
@@ -22,6 +22,11 @@ struct pci_doe_mb;
 /* Max data object length is 2^18 dwords */
 #define PCI_DOE_MAX_LENGTH		(1 << 18)
 
+typedef int (*pci_doe_protocol_handler_t)(const void *request,
+					  size_t request_sz,
+					  void **response,
+					  size_t *response_sz);
+
 struct pci_doe_mb *pci_find_doe_mailbox(struct pci_dev *pdev, u16 vendor,
 					u8 type);
 
include/linux/pci-epc.h +3 -0
index 1eca1264815b..dd26294c8175 100644
@@ -182,6 +182,9 @@ struct pci_epc {
 	unsigned long			function_num_map;
 	int				domain_nr;
 	bool				init_complete;
+#ifdef CONFIG_PCI_ENDPOINT_DOE
+	struct xarray			doe_mbs;
+#endif
 };
 
 /**
Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v6 2/4] PCI: endpoint: Add DOE mailbox support for endpoint functions

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The `pci_ep_doe_process_request()` fallback stub leaks the request buffer when…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The pci_ep_doe_process_request() fallback stub leaks the request buffer when CONFIG_PCI_ENDPOINT_DOE=n.
- [High] Flawed DOE Abort mechanism causes a state leak of the CANCEL flag, silently dropping valid requests. --

commit b18fff73f747154acf71d1ff81a4731b89d384ad
Author: Aksh Garg <[email protected]>

PCI: endpoint: Add DOE mailbox support for endpoint functions

This patch adds Data Object Exchange (DOE) support for PCIe endpoint devices. It implements framework APIs for the EPC core driver and controller drivers to register mailboxes and process DOE requests from the host.

Quoted 4 lines
drivers/pci/endpoint/pci-ep-doe.c new file +0 -0
index 0000000000000..b2832253eaca6

[ ... ]

Quoted 10 lines
drivers/pci/endpoint/pci-ep-doe.c new file +10 -0
+static void signal_task_complete(struct pci_ep_doe_task *task, int status)
+{
+	struct pci_ep_doe_mb *doe_mb = task->doe_mb;
+
+	task->complete(doe_mb->epc, doe_mb->func_no, doe_mb->cap_offset,
+		       status, task->feat.vid, task->feat.type,
+		       task->response_pl, task->response_pl_sz);
+
+	/* Clear the CANCEL flag for next DOE request */
+	clear_bit(PCI_DOE_FLAG_CANCEL, &doe_mb->flags);

[ ... ]

drivers/pci/endpoint/pci-ep-doe.c line 535

Quoted 10 lines
drivers/pci/endpoint/pci-ep-doe.c new file +10 -0
+int pci_ep_doe_abort(struct pci_epc *epc, u8 func_no, u16 cap_offset)
+{
+	struct pci_ep_doe_mb *doe_mb;
+
+	doe_mb = pci_ep_doe_get_mailbox(epc, func_no, cap_offset);
+	if (!doe_mb)
+		return -ENODEV;
+
+	/* Set CANCEL flag - worker will abort queued requests */
+	set_bit(PCI_DOE_FLAG_CANCEL, &doe_mb->flags);

[Severity: High]
Can a race condition here cause the CANCEL flag to be permanently set, silently dropping the next valid request?

If the host sends a DOE Abort just as a task completes, the controller driver could evaluate the busy state and call pci_ep_doe_abort().

Concurrently, the worker thread might finish processing, invoke signal_task_complete(), and clear the flag:

worker thread in signal_task_complete():

    clear_bit(PCI_DOE_FLAG_CANCEL, &doe_mb->flags);

If pci_ep_doe_abort() then executes on the controller thread:

controller thread in pci_ep_doe_abort():

    set_bit(PCI_DOE_FLAG_CANCEL, &doe_mb->flags);

The mailbox becomes idle but still has the CANCEL flag set. Would the next valid request then be immediately cancelled when doe_ep_task_work() checks the flag?

Quoted 8 lines
drivers/pci/endpoint/pci-ep-doe.c new file +8 -0
+
+	dev_dbg_ratelimited(epc->dev.parent,
+			    "DOE mailbox abort initialized: PF%d offset 0x%x\n",
+			    func_no, cap_offset);
+
+	pci_ep_doe_put_mailbox(doe_mb);
+	return 0;
+}

[ ... ]

Quoted 4 lines
drivers/pci/pci.h +0 -0
index 5844deee2b5f1..6d3b4b779d157 100644

[ ... ]

Quoted 5 lines
drivers/pci/pci.h +5 -0
+#else
+static inline void pci_ep_doe_init(struct pci_epc *epc) { }
+static inline int pci_ep_doe_add_mailbox(struct pci_epc *epc, u8 func_no,
+					 u16 cap_offset)
+{

drivers/pci/pci.h static inline void pci_doe_destroy(struct pci_dev *pdev) { } · line 735

Quoted 10 lines
drivers/pci/pci.h +10 -0
+	return -EOPNOTSUPP;
+}
+
+static inline int pci_ep_doe_process_request(struct pci_epc *epc,
+					     u8 func_no, u16 cap_offset,
+					     u16 vendor, u8 type,
+					     void *request, size_t request_sz,
+					     pci_ep_doe_complete_t complete)
+{
+	return -EOPNOTSUPP;

[Severity: High]
Does this fallback stub leak the request buffer when endpoint DOE support is disabled?

The API documentation in pci-ep-doe.c states that ownership of the request buffer is transferred to the DOE EP core, which frees it. Since this stub just returns -EOPNOTSUPP, it looks like the buffer is never freed when CONFIG_PCI_ENDPOINT_DOE is not enabled.

Quoted 1 line

+}

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

PATCH v6 3/4 PCI: endpoint: Add support for DOE initialization and setup in EPC core

In reply to Aksh Garg

Add pci_epc_init_capabilities() in EPC core driver to initialize and setup the capabilities supported by the EPC driver. This calls pci_epc_doe_setup() to setup the DOE framework for an endpoint controller, which discovers the DOE capabilities (extended capability ID 0x2E), and registers each discovered DOE mailbox for all the functions in the endpoint controller.

Add pci_epc_deinit_capabilities() in EPC core driver for cleanup of the resources used by the capabilities of the EPC driver. This calls pci_ep_doe_destroy() to destroy all DOE mailboxes and free associated resources.

---

Changes from v5 to v6:
- Addressed the review comments provided by Bjorn Helgaas at v5

Changes from v4 to v5:
- Addressed the review comments by Sashiko

Changes from v3 to v4:
- Call DOE setup and destroy APIs directly within the EPC core, instead of relying on the EPC drivers to call them individually. EPC drivers do not need to explicitly handle DOE setup, rather the EPC core manages this transparently. (Suggested by Manivannan Sadhasivam).
- Removed pci_epc_doe_destroy() API, which was just calling pci_ep_doe_destroy(). Instead, called pci_ep_doe_destroy() directly during cleanup.
- Called pci_ep_doe_init() before the "!epc->ops->find_ext_capability" check, because if doe-capable=1 and find_ext_capability() op is undefined, this would not initialize the epc->doe_mbs xarray. However during cleanup, the check "!epc->ops->find_ext_capability" would be unnecessary, and it will try to destroy the epc->doe_mbs xarray even when it was not initialized.

Changes from v2 to v3:
- Rebased on 7.1-rc1.

Changes since v1:
- New patch added to v2 (not present in v1)

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/

This patch is introduced based on the feedback provided by Manivannan Sadhasivam at [1].

[1]: https://lore.kernel.org/all/p57x6jleaim5w7t2k3v7tioujnaxuovfpj5euop5ogefvw23se@y5fw3che5p5d/

 drivers/pci/endpoint/pci-epc-core.c | 101 ++++++++++++++++++++++++++++
 include/linux/pci-epc.h             |   6 ++
 2 files changed, 107 insertions(+)
drivers/pci/endpoint/pci-epc-core.c +101 -0
index 6c3c58185fc5..96bd624559f2 100644
@@ -14,6 +14,8 @@
 #include <linux/pci-epf.h>
 #include <linux/pci-ep-cfs.h>
 
+#include "../pci.h"
+
 static const struct class pci_epc_class = {
 	.name = "pci_epc",
 };
@@ -842,6 +844,78 @@ void pci_epc_linkdown(struct pci_epc *epc)
 }
 EXPORT_SYMBOL_GPL(pci_epc_linkdown);
 
+/**
+ * pci_epc_doe_setup() - Discover and setup DOE mailboxes for all functions
+ * @epc: the EPC device on which DOE mailboxes has to be setup
+ *
+ * Discover DOE (Data Object Exchange) capabilities for all physical
+ * functions in the endpoint controller and register DOE mailboxes.
+ *
+ * Return: 0 on success, -errno on failure
+ */
+static int pci_epc_doe_setup(struct pci_epc *epc)
+{
+	u8 func_no, vfunc_no = 0;
+	u16 cap_offset;
+	int ret;
+
+	if (!epc->ops || !epc->ops->find_ext_capability)
+		return -EINVAL;
+
+	/* Discover DOE capabilities for all functions */
+	for (func_no = 0; func_no < epc->max_functions; func_no++) {
+		mutex_lock(&epc->lock);
+		cap_offset = epc->ops->find_ext_capability(epc, func_no,
+							   vfunc_no, 0,
+							   PCI_EXT_CAP_ID_DOE);
+		mutex_unlock(&epc->lock);
+
+		while (cap_offset) {
+			/* Register this DOE mailbox */
+			ret = pci_ep_doe_add_mailbox(epc, func_no, cap_offset);
+			if (ret) {
+				dev_warn(&epc->dev,
+					 "[pf%d:offset %x] failed to add DOE mailbox\n",
+					 func_no, cap_offset);
+			}
+
+			mutex_lock(&epc->lock);
+			cap_offset = epc->ops->find_ext_capability(epc, func_no,
+								   vfunc_no,
+								   cap_offset,
+								   PCI_EXT_CAP_ID_DOE);
+			mutex_unlock(&epc->lock);
+		}
+	}
+
+	dev_dbg(&epc->dev, "DOE mailboxes setup complete\n");
+	return 0;
+}
+
+/**
+ * pci_epc_init_capabilities() - Initialize EPC capabilities
+ * @epc: the EPC device whose capabilities need to be initialized
+ *
+ * Initialize capabilities supported by the EPC device.
+ */
+static void pci_epc_init_capabilities(struct pci_epc *epc)
+{
+	const struct pci_epc_features *epc_features;
+	int ret;
+
+	epc_features = pci_epc_get_features(epc, 0, 0);
+	if (!epc_features)
+		return;
+
+	if (IS_ENABLED(CONFIG_PCI_ENDPOINT_DOE) && epc_features->doe_capable) {
+		pci_ep_doe_init(epc);
+
+		ret = pci_epc_doe_setup(epc);
+		if (ret)
+			dev_warn(&epc->dev, "DOE setup failed: %d\n", ret);
+	}
+}
+
 /**
  * pci_epc_init_notify() - Notify the EPF device that EPC device initialization
  *                         is completed.
@@ -857,6 +931,9 @@ void pci_epc_init_notify(struct pci_epc *epc)
 	if (IS_ERR_OR_NULL(epc))
 		return;
 
+	if (!epc->init_complete)
+		pci_epc_init_capabilities(epc);
+
 	mutex_lock(&epc->list_lock);
 	list_for_each_entry(epf, &epc->pci_epf, list) {
 		mutex_lock(&epf->lock);
@@ -890,6 +967,27 @@ void pci_epc_notify_pending_init(struct pci_epc *epc, struct pci_epf *epf)
 }
 EXPORT_SYMBOL_GPL(pci_epc_notify_pending_init);
 
+/**
+ * pci_epc_deinit_capabilities() - Clean up EPC capabilities
+ * @epc: the EPC device whose capabilities need to be cleaned up
+ *
+ * Clean up capabilities supported by the EPC device,
+ * and free the associated resources.
+ */
+static void pci_epc_deinit_capabilities(struct pci_epc *epc)
+{
+	const struct pci_epc_features *epc_features;
+
+	epc_features = pci_epc_get_features(epc, 0, 0);
+	if (!epc_features)
+		return;
+
+	if (IS_ENABLED(CONFIG_PCI_ENDPOINT_DOE) && epc_features->doe_capable) {
+		pci_ep_doe_destroy(epc);
+		dev_dbg(&epc->dev, "DOE mailboxes destroyed\n");
+	}
+}
+
 /**
  * pci_epc_deinit_notify() - Notify the EPF device about EPC deinitialization
  * @epc: the EPC device whose deinitialization is completed
@@ -903,6 +1001,9 @@ void pci_epc_deinit_notify(struct pci_epc *epc)
 	if (IS_ERR_OR_NULL(epc))
 		return;
 
+	if (epc->init_complete)
+		pci_epc_deinit_capabilities(epc);
+
 	mutex_lock(&epc->list_lock);
 	list_for_each_entry(epf, &epc->pci_epf, list) {
 		mutex_lock(&epf->lock);
include/linux/pci-epc.h +6 -0
index dd26294c8175..11474e337db3 100644
@@ -84,6 +84,8 @@ struct pci_epc_map {
  * @start: ops to start the PCI link
  * @stop: ops to stop the PCI link
  * @get_features: ops to get the features supported by the EPC
+ * @find_ext_capability: ops to find extended capability offset for a function
+ *			 in endpoint controller
  * @owner: the module owner containing the ops
  */
 struct pci_epc_ops {
@@ -115,6 +117,8 @@ struct pci_epc_ops {
 	void	(*stop)(struct pci_epc *epc);
 	const struct pci_epc_features* (*get_features)(struct pci_epc *epc,
 						       u8 func_no, u8 vfunc_no);
+	u16	(*find_ext_capability)(struct pci_epc *epc, u8 func_no,
+				       u8 vfunc_no, u16 start, u8 cap);
 	struct module *owner;
 };
 
@@ -270,6 +274,7 @@ struct pci_epc_bar_desc {
  * @msi_capable: indicate if the endpoint function has MSI capability
  * @msix_capable: indicate if the endpoint function has MSI-X capability
  * @intx_capable: indicate if the endpoint can raise INTx interrupts
+ * @doe_capable: indicate if the endpoint function has DOE capability
  * @bar: array specifying the hardware description for each BAR
  * @align: alignment size required for BAR buffer allocation
  */
@@ -280,6 +285,7 @@ struct pci_epc_features {
 	unsigned int	msi_capable : 1;
 	unsigned int	msix_capable : 1;
 	unsigned int	intx_capable : 1;
+	unsigned int	doe_capable : 1;
 	struct	pci_epc_bar_desc bar[PCI_STD_NUM_BARS];
 	size_t	align;
 };
Signature · 1 line
2.34.1
#6 lore raw

Re: [PATCH v6 3/4] PCI: endpoint: Add support for DOE initialization and setup in EPC core

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [High] Unprotected check of epc->init_complete causes a TOCTOU race in pci_epc_init_notify() and pci_epc_deinit_notify(), leading to double initialization, memory leaks, and xarray corruption.
- [High] Logic Flaw: DOE mailboxes are never initialized because pci_epc_init_notify() is called before functions are bound.
- [High] Incorrect teardown ordering in pci_epc_deinit_notify() causes a Use-After-Free during shutdown.

Pre-existing issues:
- [High] TOCTOU data race in pci_epc_notify_pending_init() sends spurious epc_init events after deinitialization. --

commit 1a369cd1d0a1ffe8ebc7c7242501b1fde9e422c9
Author: Aksh Garg <[email protected]>

PCI: endpoint: Add support for DOE initialization and setup in EPC core

Add pci_epc_init_capabilities() in EPC core driver to initialize and setup capabilities supported by the EPC driver. This calls pci_epc_doe_setup() to setup the DOE framework for an endpoint controller, which discovers DOE capabilities and registers mailboxes. It also adds cleanup.

Quoted 4 lines
drivers/pci/endpoint/pci-epc-core.c +0 -0
index 6c3c58185fc5d..96bd624559f2a 100644

[ ... ]

Quoted 18 lines
drivers/pci/endpoint/pci-epc-core.c +14 -0
@@ -842,6 +844,78 @@ void pci_epc_linkdown(struct pci_epc *epc)
 }
 EXPORT_SYMBOL_GPL(pci_epc_linkdown);
 
+/**
+ * pci_epc_doe_setup() - Discover and setup DOE mailboxes for all functions
+ * @epc: the EPC device on which DOE mailboxes has to be setup
+ *
+ * Discover DOE (Data Object Exchange) capabilities for all physical
+ * functions in the endpoint controller and register DOE mailboxes.
+ *
+ * Return: 0 on success, -errno on failure
+ */
+static int pci_epc_doe_setup(struct pci_epc *epc)
+{
+	u8 func_no, vfunc_no = 0;
+	u16 cap_offset;
+	int ret;

drivers/pci/endpoint/pci-epc-core.c void pci_epc_linkdown(struct pci_epc *epc) · line 870

Quoted 10 lines
drivers/pci/endpoint/pci-epc-core.c +10 -0
+
+	if (!epc->ops || !epc->ops->find_ext_capability)
+		return -EINVAL;
+
+	/* Discover DOE capabilities for all functions */
+	for (func_no = 0; func_no < epc->max_functions; func_no++) {
+		mutex_lock(&epc->lock);
+		cap_offset = epc->ops->find_ext_capability(epc, func_no,
+							   vfunc_no, 0,
+							   PCI_EXT_CAP_ID_DOE);

[Severity: High]
Does hardcoding vfunc_no to 0 completely omit DOE mailbox discovery and initialization for SR-IOV virtual functions?

Quoted 3 lines
drivers/pci/endpoint/pci-epc-core.c +3 -0
+		mutex_unlock(&epc->lock);
+
+		while (cap_offset) {

[ ... ]

Quoted 11 lines
drivers/pci/endpoint/pci-epc-core.c +11 -0
+		}
+	}
+
+	dev_dbg(&epc->dev, "DOE mailboxes setup complete\n");
+	return 0;
+}
+
+/**
+ * pci_epc_init_capabilities() - Initialize EPC capabilities
+ * @epc: the EPC device whose capabilities need to be initialized
+ *

drivers/pci/endpoint/pci-epc-core.c void pci_epc_linkdown(struct pci_epc *epc) · line 908

Quoted 10 lines
drivers/pci/endpoint/pci-epc-core.c +10 -0
+ * Initialize capabilities supported by the EPC device.
+ */
+static void pci_epc_init_capabilities(struct pci_epc *epc)
+{
+	const struct pci_epc_features *epc_features;
+	int ret;
+
+	epc_features = pci_epc_get_features(epc, 0, 0);
+	if (!epc_features)
+		return;

[Severity: High]
Could pci_epc_get_features() return NULL here and silently bypass DOE initialization?

If pci_epc_init_notify() is invoked during controller probe before any Endpoint Function (EPF) drivers are bound, pci_epc_get_features() may fail.

Since the functions are not bound yet, the function_num_map could be 0, causing the initialization to abort immediately without setting up the mailboxes.

Quoted 2 lines
drivers/pci/endpoint/pci-epc-core.c +2 -0
+
+	if (IS_ENABLED(CONFIG_PCI_ENDPOINT_DOE) && epc_features->doe_capable) {

[ ... ]

drivers/pci/endpoint/pci-epc-core.c void pci_epc_init_notify(struct pci_epc *epc) · line 936

Quoted 13 lines
drivers/pci/endpoint/pci-epc-core.c +6 -0
+	}
+}
+
 /**
  * pci_epc_init_notify() - Notify the EPF device that EPC device initialization
  *                         is completed.
@@ -857,6 +931,9 @@ void pci_epc_init_notify(struct pci_epc *epc)
 	if (IS_ERR_OR_NULL(epc))
 		return;
 
+	if (!epc->init_complete)
+		pci_epc_init_capabilities(epc);
+

[Severity: High]
Can a concurrent caller hit this unprotected check, bypassing the intended protection?

Because the epc->init_complete condition is evaluated locklessly outside epc->list_lock, multiple threads could proceed to initialize the capabilities.

This double initialization might lead to memory leaks, as xa_init() would reset the xarray pointers without freeing the already allocated elements.

Quoted 2 lines
drivers/pci/endpoint/pci-epc-core.c +0 -0
 	mutex_lock(&epc->list_lock);
 	list_for_each_entry(epf, &epc->pci_epf, list) {

[ ... ]

drivers/pci/endpoint/pci-epc-core.c void pci_epc_notify_pending_init(struct pci_epc *epc, struct pci_epf *epf) · line 968

Quoted 3 lines
drivers/pci/endpoint/pci-epc-core.c +0 -0
@@ -890,6 +967,27 @@ void pci_epc_notify_pending_init(struct pci_epc *epc, struct pci_epf *epf)
 }
 EXPORT_SYMBOL_GPL(pci_epc_notify_pending_init);

[Severity: High]
This isn't a bug introduced by this patch, but does the lockless check of init_complete in pci_epc_notify_pending_init() allow a race condition with deinitialization?

If a hardware link-down event triggers pci_epc_deinit_notify() concurrently, pci_epc_notify_pending_init() could read the flag before it is cleared, and subsequently send spurious epc_init events after the hardware has been stopped.

Quoted 3 lines
drivers/pci/endpoint/pci-epc-core.c +3 -0
+
+/**
+ * pci_epc_deinit_capabilities() - Clean up EPC capabilities

[ ... ]

drivers/pci/endpoint/pci-epc-core.c void pci_epc_deinit_notify(struct pci_epc *epc) · line 1006

Quoted 7 lines
drivers/pci/endpoint/pci-epc-core.c +3 -0
@@ -903,6 +1001,9 @@ void pci_epc_deinit_notify(struct pci_epc *epc)
 	if (IS_ERR_OR_NULL(epc))
 		return;
 
+	if (epc->init_complete)
+		pci_epc_deinit_capabilities(epc);
+

[Severity: High]
Does this unprotected check of init_complete allow multiple threads to concurrently destroy the mailboxes, potentially leading to double-free crashes?

drivers/pci/endpoint/pci-epc-core.c

Quoted 7 lines
drivers/pci/endpoint/pci-epc-core.c +0 -0
 	mutex_lock(&epc->list_lock);
 	list_for_each_entry(epf, &epc->pci_epf, list) {
 		mutex_lock(&epf->lock);
drivers/pci/endpoint/pci-epc-core.c +0 -0
 		if (epf->event_ops && epf->event_ops->epc_deinit)
 			epf->event_ops->epc_deinit(epf);
 		mutex_unlock(&epf->lock);
 	}

[Severity: High]
Does freeing the capability before iterating over the EPF list to send the epc_deinit notification cause a use-after-free?

If an EPF driver attempts to flush or interact with a DOE mailbox during its shutdown callback, it would access already freed memory. Teardown generally needs to be the exact reverse of initialization, notifying EPFs to stop using the hardware before destroying the underlying capabilities.

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

PATCH v6 4/4 Documentation: PCI: Add documentation for DOE endpoint support

In reply to Aksh Garg

Document the architecture and implementation details for the Data Object Exchange (DOE) framework for PCIe Endpoint devices.

---

Changes from v5 to v6:
- Addressed the review comments provided by Bjorn Helgaas at v5

Changes from v4 to v5:
- Updated the DOE Abort handling setion.

Changes from v3 to v4:
- Updated the maximum size of the DOE object from 256KB to 1MB, as per PCIe spec.
- Updated the DOE setup and cleanup sections.

Changes from v2 to v3:
- Rebased on 7.1-rc1.

Changes since v1:
- Squashed the patches [1] and [2], and moved the documentation file to Documentation/PCI/endpoint/pci-endpoint-doe.rst to match the existing naming scheme, as suggested by Niklas Cassel
- Updated the documentation as per the design and implementaion changes made to previous patches in this series:
* Updated for static protocol array instead of dynamic registration
* Documented asynchronous callback model
* Updated request/response flow with new callback signature
* Updated memory ownership: DOE core frees request, driver frees response
* Updated initialization and cleanup sections for new APIs

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1: [1] https://lore.kernel.org/all/[email protected]/

    [2] https://lore.kernel.org/all/[email protected]/
 Documentation/PCI/endpoint/index.rst          |   1 +
 .../PCI/endpoint/pci-endpoint-doe.rst         | 352 ++++++++++++++++++
 2 files changed, 353 insertions(+)
 create mode 100644 Documentation/PCI/endpoint/pci-endpoint-doe.rst
Documentation/PCI/endpoint/index.rst +1 -0
index dd1f62e731c9..7c03d5abd2ef 100644
@@ -9,6 +9,7 @@ PCI Endpoint Framework
 
    pci-endpoint
    pci-endpoint-cfs
+   pci-endpoint-doe
    pci-test-function
    pci-test-howto
    pci-ntb-function
Documentation/PCI/endpoint/pci-endpoint-doe.rst new file +352 -0

352 lines not on this page · raw message

Signature · 1 line
2.34.1
#8 lore raw

Re: [PATCH v6 4/4] Documentation: PCI: Add documentation for DOE endpoint support

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

Document the architecture and implementation details for the Data Object Exchange (DOE) framework for PCIe Endpoint devices.

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=4