[PATCH 1/2] bitmap: ignore unused tail bits in bitmap_cut()

From: Jinseob Kim

Date: Sun Nov 22 2026 - 23:33:05 EST


When nbits is not a multiple of BITS_PER_LONG, bitmap_cut() copies
the entire last word. A subsequent right shift can move unused tail
bits into the valid result. For example, cutting bit 0 from a 65-bit
bitmap can move storage bit 65 into output bit 64.

The bitmap API requires unused tail bits to have no effect on the
result. Mask the copied destination word before shifting. Keep the
existing pre-memmove() read of the bits preceding the cut so that
overlapping buffers continue to work.

The last existing test case removes all valid bits above bit 15.
Change its expected value to 0x0000ffff, which contains only the
preserved bits.

Fixes: 2092767168f0 ("bitmap: Introduce bitmap_cut(): cut bits and shift remaining")
Signed-off-by: Jinseob Kim <kimjinseob88@xxxxxxxxx>
---
lib/bitmap.c | 2 ++
lib/test_bitmap.c | 2 +-
2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/bitmap.c b/lib/bitmap.c
index d1cb8a507..50cef429e 100644
--- a/lib/bitmap.c
+++ b/lib/bitmap.c
@@ -210,6 +210,8 @@ void bitmap_cut(unsigned long *dst, const unsigned long *src,
}

memmove(dst, src, len * sizeof(*dst));
+ if (nbits % BITS_PER_LONG)
+ dst[len - 1] &= BITMAP_LAST_WORD_MASK(nbits);

while (cut--) {
for (i = first / BITS_PER_LONG; i < len; i++) {
diff --git a/lib/test_bitmap.c b/lib/test_bitmap.c
index ba09d057f..eb925d576 100644
--- a/lib/test_bitmap.c
+++ b/lib/test_bitmap.c
@@ -1138,7 +1138,7 @@ static struct test_bitmap_cut test_cut[] = {
},
{ 16, BITS_PER_LONG * 2 + 1, BITS_PER_LONG * 2 + 1 + 16,
{ 0x0000ffffUL, 0x5a5a5a5aUL, 0x5a5a5a5aUL, 0x5a5a5a5aUL },
- { 0x2d2dffffUL, },
+ { 0x0000ffffUL, },
},
};