pciexp: Refactor extended capability handling

Add some inline functions for the bit-wise operations, change the loop
body to an if-bail-out style and remove stateful variables.

Change-Id: Ia8db915f375737064e3486d313383d9b6c3eb2b8
Signed-off-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/66458
Reviewed-by: Bill XIE <persmule@hardenedlinux.org>
Reviewed-by: Tim Wawrzynczak <twawrzynczak@chromium.org>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
diff --git a/src/device/pciexp_device.c b/src/device/pciexp_device.c
index 903ecdd..05ac4fc 100644
--- a/src/device/pciexp_device.c
+++ b/src/device/pciexp_device.c
@@ -9,22 +9,32 @@
 #include <device/pci_ops.h>
 #include <device/pciexp.h>
 
-static unsigned int pciexp_get_ext_cap_offset(const struct device *dev, unsigned int cap,
-					      unsigned int offset)
+static unsigned int ext_cap_id(unsigned int cap)
+{
+	return cap & 0xffff;
+}
+
+static unsigned int ext_cap_next_offset(unsigned int cap)
+{
+	return cap >> 20;
+}
+
+static unsigned int find_ext_cap_offset(const struct device *dev, unsigned int cap_id,
+					unsigned int offset)
 {
 	unsigned int this_cap_offset = offset;
-	unsigned int next_cap_offset, this_cap;
+
 	while (this_cap_offset != 0) {
-		this_cap = pci_read_config32(dev, this_cap_offset);
+		const unsigned int this_cap = pci_read_config32(dev, this_cap_offset);
+
 		/* Bail out when this request is unsupported */
 		if (this_cap == 0xffffffff)
 			break;
-		if ((this_cap & 0xffff) == cap) {
+
+		if (ext_cap_id(this_cap) == cap_id)
 			return this_cap_offset;
-		} else {
-			next_cap_offset = this_cap >> 20;
-			this_cap_offset = next_cap_offset;
-		}
+
+		this_cap_offset = ext_cap_next_offset(this_cap);
 	}
 
 	return 0;
@@ -46,11 +56,11 @@
 	unsigned int next_cap_offset;
 
 	if (offset)
-		next_cap_offset = pci_read_config32(dev, offset) >> 20;
+		next_cap_offset = ext_cap_next_offset(pci_read_config32(dev, offset));
 	else
 		next_cap_offset = PCIE_EXT_CAP_OFFSET;
 
-	return pciexp_get_ext_cap_offset(dev, cap, next_cap_offset);
+	return find_ext_cap_offset(dev, cap, next_cap_offset);
 }
 
 /*