[PATCH] PCI: endpoint: check epf->epc and epf->sec_epc under locks in pci_epc_add_epf()

From: Ziheng Wei

Date: Sun Dec 06 2026 - 03:30:15 EST


pci_epc_add_epf() checks epf->epc and epf->sec_epc before acquiring
epc->list_lock or epf->lock. Concurrent calls binding the same EPF via
configfs can both pass the unlocked check, allocate two function numbers,
and call list_add_tail() twice on the same list_head, corrupting
epc->pci_epf.

Acquire epc->list_lock followed by epf->lock (matching the lock order in
pci_epc_linkup() and the other EPC notification helpers) before checking
and updating epf->epc and epf->sec_epc, and hold epf->lock symmetrically
in pci_epc_remove_epf().

Found by LLM-assisted static analysis. Compile-tested on x86_64.

Fixes: 5e8cb4033807 ("PCI: endpoint: Add EP core layer to enable EP controller and EP functions")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Ziheng Wei <zihengw03@xxxxxxx>
---
drivers/pci/endpoint/pci-epc-core.c | 15 ++++++++++-----
1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/drivers/pci/endpoint/pci-epc-core.c b/drivers/pci/endpoint/pci-epc-core.c
index 831b40458..14deff2cb 100644
--- a/drivers/pci/endpoint/pci-epc-core.c
+++ b/drivers/pci/endpoint/pci-epc-core.c
@@ -797,13 +797,15 @@ int pci_epc_add_epf(struct pci_epc *epc, struct pci_epf *epf,
if (IS_ERR_OR_NULL(epc) || epf->is_vf)
return -EINVAL;

- if (type == PRIMARY_INTERFACE && epf->epc)
- return -EBUSY;
+ mutex_lock(&epc->list_lock);
+ mutex_lock(&epf->lock);

- if (type == SECONDARY_INTERFACE && epf->sec_epc)
- return -EBUSY;
+ if ((type == PRIMARY_INTERFACE && epf->epc) ||
+ (type == SECONDARY_INTERFACE && epf->sec_epc)) {
+ ret = -EBUSY;
+ goto ret;
+ }

- mutex_lock(&epc->list_lock);
func_no = find_first_zero_bit(&epc->function_num_map,
BITS_PER_LONG);
if (func_no >= BITS_PER_LONG) {
@@ -830,6 +832,7 @@ int pci_epc_add_epf(struct pci_epc *epc, struct pci_epf *epf,

list_add_tail(list, &epc->pci_epf);
ret:
+ mutex_unlock(&epf->lock);
mutex_unlock(&epc->list_lock);

return ret;
@@ -855,6 +858,7 @@ void pci_epc_remove_epf(struct pci_epc *epc, struct pci_epf *epf,
return;

mutex_lock(&epc->list_lock);
+ mutex_lock(&epf->lock);
if (type == PRIMARY_INTERFACE) {
func_no = epf->func_no;
list = &epf->list;
@@ -866,6 +870,7 @@ void pci_epc_remove_epf(struct pci_epc *epc, struct pci_epf *epf,
}
clear_bit(func_no, &epc->function_num_map);
list_del(list);
+ mutex_unlock(&epf->lock);
mutex_unlock(&epc->list_lock);
}
EXPORT_SYMBOL_GPL(pci_epc_remove_epf);

base-commit: 97d73c8251226cf27cc6656b4c542869bb8c69fa
--
2.43.0