[PATCH 4/5] PCI: rebar: Guard pci_rebar_bytes_to_size() against overflow

From: shao.mingyin

Date: Fri Nov 06 2026 - 11:23:42 EST


From: Shao Mingyin <shao.mingyin@xxxxxxxxxx>

pci_rebar_bytes_to_size() passes its argument straight to
roundup_pow_of_two(), whose implementation is (1UL << fls(bytes - 1)).
For bytes == 0 and for values above 2^63, fls() returns 64 and the
shift count is undefined behavior. A value with bit 63 set cannot be
encoded either: exactly 2^63 rounds to itself and is encoded as 43,
outside the 5-bit BAR Size field.

Bail out for bytes == 0 and for any value with bit 63 set; a zero size
is returned, which encodes the 1 MB minimum. The largest valid BAR size
is 128 TB, far below the 2^63 boundary, so no legitimate input is
affected.

Fixes: 192f1bf7559e ("PCI: Add pci_rebar_bytes_to_size()")
Signed-off-by: Shao Mingyin <shao.mingyin@xxxxxxxxxx>
---
Tested on 7.3.0-next-20261030 (QEMU/TCG x86_64) with a TEST-ONLY hook
(applied to both kernels) that calls pci_rebar_bytes_to_size() at boot
with pathological inputs (0, 2^63, U64_MAX) and two sane sizes (1 MB,
1 GB), built with CONFIG_UBSAN_SHIFT. No extra hardware is needed.

Unpatched, the 2^63 input is encoded as BAR size 43 (outside the valid
0..31 range) and the 0/U64_MAX inputs shift by 64 (UBSAN reports "shift
exponent 64 is too large for 64-bit type"). With this patch all
pathological inputs return 0, the two sane sizes are unchanged (1 MB -> 0,
1 GB -> 10) and no UBSAN report appears.

unpatched patched
UBSAN shift-out-of-bounds; size 43 size 0, no UBSAN report

diff --git a/drivers/pci/rebar.c b/drivers/pci/rebar.c
index 5bbdc9470a31..fd448dc7c322 100644
--- a/drivers/pci/rebar.c
+++ b/drivers/pci/rebar.c
@@ -31,6 +31,13 @@ int pci_rebar_bytes_to_size(u64 bytes)
{
int rebar_minsize = ilog2(PCI_REBAR_MIN_SIZE);

+ /*
+ * roundup_pow_of_two() is undefined for 0 and above 2^63; any value
+ * with bit 63 set is outside the 5-bit BAR Size field, so bail out.
+ */
+ if (!bytes || bytes & (1ULL << 63))
+ return 0;
+
bytes = roundup_pow_of_two(bytes);

return max(ilog2(bytes), rebar_minsize) - rebar_minsize;