[PATCH] bitmap: Rephrase read and write bounds checks for sparse

From: Yury Norov

Date: Thu Nov 19 2026 - 16:03:21 EST


Reword bitmap_read/write() conditionals such that it improves on code
generation and performance.

Tested with minimal x86-64 kernels with GCC 15.2 and CONFIG_TEST_BITMAP=y.
Run 400 fresh boots per kernel under virtme/KVM on a Core Ultra 7 268V,
using one vCPU and 256 MiB RAM.

Before, us After, us Change, us t p
Read 277.00 (6.99) 265.33 (17.05) -4.21% -12.695 2.97e-31
Write 496.96 (14.38) 488.56 (10.41) -1.69% -9.615 8.03e-20

Bloat-o-meter reports 60 fewer function bytes in vmlinux and in
lib/test_bitmap.o:

Function Before After Delta
test_bitmap_read_perf 234 227 -7
test_bitmap_write_perf 298 286 -12
test_bitmap_write_helper 880 872 -8
test_bitmap_read_write 800 767 -33

It also fixes the following sparse errors:

include/linux/bitmap.h:854:55: warning: shift too big (64) for type unsigned long
include/linux/bitmap.h:854:55: warning: shift too big (64) for type unsigned long

Reported-by: Andy Shevchenko <andriy.shevchenko@xxxxxxxxxxxxxxx>
Link: https://lore.kernel.org/r/20261119191530.1716850-1-andriy.shevchenko@xxxxxxxxxxxxxxx
Signed-off-by: Yury Norov <ynorov@xxxxxxxxxx>
---
include/linux/bitmap.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/include/linux/bitmap.h b/include/linux/bitmap.h
index adafbcf2016b..08de1467367e 100644
--- a/include/linux/bitmap.h
+++ b/include/linux/bitmap.h
@@ -846,7 +846,7 @@ unsigned long bitmap_read(const unsigned long *map, unsigned long start, unsigne
if (unlikely(!nbits || nbits > BITS_PER_LONG))
return 0;

- if (space >= nbits)
+ if (offset <= BITS_PER_LONG - nbits)
return (map[index] >> offset) & BITMAP_LAST_WORD_MASK(nbits);

value_low = map[index] & BITMAP_FIRST_WORD_MASK(start);
@@ -886,7 +886,7 @@ void bitmap_write(unsigned long *map, unsigned long value,
value &= mask;
offset = start % BITS_PER_LONG;
space = BITS_PER_LONG - offset;
- fit = space >= nbits;
+ fit = offset <= BITS_PER_LONG - nbits;
index = BIT_WORD(start);

map[index] &= (fit ? (~(mask << offset)) : ~BITMAP_FIRST_WORD_MASK(start));
--
2.53.0