[PATCH 0/2] bitfield: fix FIELD_FIT() for values that overflow the shift

From: Arnav Kapoor

Date: Fri Dec 04 2026 - 11:33:30 EST


FIELD_FIT() shifts the value up into the field before checking it, so
high bits that fall off the top of the mask's type are lost and a value
that is too big passes. On 32-bit, FIELD_FIT(GENMASK(9, 8), BIT(24)) and
FIELD_FIT(GENMASK(9, 8), INT_MIN) are true; on 64-bit the same happens
with a u32 mask. This came up in the aw96103 v2 review on linux-iio,
where Jonathan suggested shifting the mask down instead and asked
whether the compiler still produces good code.

1: shift the mask down and compare, as FIELD_MAX() does.
2: kunit cases that fail before patch 1 (on um and i386) and pass after.

Code generation, FIELD_FIT(GENMASK(9, 8), int):
- gcc -m32 -O2: cmpl $3 + setbe (was a test against 0x00fffffc, which
is the bug)
- clang ARMv7 -O2: cmp #4 + movwlo
- gcc x86-64 -O2: one instruction shorter than before

Not changed: the value is still cast to the mask's type first, so with
a u8 or u16 mask a wider value is still truncated (FIELD_FIT((u8)0xf0,
0x100) is true). Casting to u64 instead fixes that as well, but gcc -m32
then emits 12 instructions instead of 4 for an int value, so I left it
out; happy to add it if you prefer.

Tested with kunit (bitfields suite) on um and i386, and W=1 builds of
every non-arch FIELD_FIT() user (allmodconfig, x86_64) with no new
warnings.

Arnav Kapoor (2):
bitfield: make FIELD_FIT() check the value, not the shifted value
bitfield: kunit: test FIELD_FIT() with values that overflow the shift

include/linux/bitfield.h | 2 +-
lib/tests/bitfield_kunit.c | 25 +++++++++++++++++++++++++
2 files changed, 26 insertions(+), 1 deletion(-)


base-commit: 209e46e8890d3618ed883eaf816625d9f22df52f
--
2.53.0