[PATCH 3/5] vfio: selftests: Add vfio_pci_find_capability()

From: David Matlack

Date: Thu Oct 29 2026 - 16:34:41 EST


Add a helper to find the config space offset of a capability in a
device's standard capability list, mirroring the kernel's
pci_find_capability(). Return 0 if the device does not have the
capability.

This will be used in a subsequent commit to locate the PM capability.

Signed-off-by: David Matlack <dmatlack@xxxxxxxxxx>
---
.../lib/include/libvfio/vfio_pci_device.h | 7 ++++++
.../selftests/vfio/lib/vfio_pci_device.c | 25 +++++++++++++++++++
2 files changed, 32 insertions(+)

diff --git a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h
index 007adc322c1e..1839e95cc792 100644
--- a/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h
+++ b/tools/testing/selftests/vfio/lib/include/libvfio/vfio_pci_device.h
@@ -79,6 +79,13 @@ void vfio_pci_config_access(struct vfio_pci_device *device, bool write,
#define vfio_pci_config_writew(_d, _o, _v) vfio_pci_config_write(_d, _o, _v, u16)
#define vfio_pci_config_writel(_d, _o, _v) vfio_pci_config_write(_d, _o, _v, u32)

+/*
+ * Return the config space offset of the first capability with the given ID
+ * (PCI_CAP_ID_*) in the device's standard capability list, or 0 if the device
+ * does not have the capability.
+ */
+u8 vfio_pci_find_capability(struct vfio_pci_device *device, u8 cap_id);
+
static inline void vfio_pci_cmd_set(struct vfio_pci_device *device, u16 bits)
{
u16 cmd = vfio_pci_config_readw(device, PCI_COMMAND);
diff --git a/tools/testing/selftests/vfio/lib/vfio_pci_device.c b/tools/testing/selftests/vfio/lib/vfio_pci_device.c
index 4063a0e2b3df..2afbc465d30c 100644
--- a/tools/testing/selftests/vfio/lib/vfio_pci_device.c
+++ b/tools/testing/selftests/vfio/lib/vfio_pci_device.c
@@ -260,6 +260,31 @@ void vfio_pci_config_access(struct vfio_pci_device *device, bool write,
write ? "write to" : "read from", config);
}

+/* Bound the capability list walk in case the list contains a loop. */
+#define PCI_FIND_CAP_TTL 48
+
+u8 vfio_pci_find_capability(struct vfio_pci_device *device, u8 cap_id)
+{
+ int ttl = PCI_FIND_CAP_TTL;
+ u8 pos;
+
+ if (!(vfio_pci_config_readw(device, PCI_STATUS) & PCI_STATUS_CAP_LIST))
+ return 0;
+
+ pos = vfio_pci_config_readb(device, PCI_CAPABILITY_LIST);
+
+ while (pos >= PCI_STD_HEADER_SIZEOF && ttl--) {
+ pos &= ~3;
+
+ if (vfio_pci_config_readb(device, pos + PCI_CAP_LIST_ID) == cap_id)
+ return pos;
+
+ pos = vfio_pci_config_readb(device, pos + PCI_CAP_LIST_NEXT);
+ }
+
+ return 0;
+}
+
int __vfio_pci_device_reset(struct vfio_pci_device *device)
{
if (ioctl(device->fd, VFIO_DEVICE_RESET, NULL))
--
2.56.0.317.g454f8302e1-goog