[PATCH] bitfield: Use argument type for size comparison on Bitfield access macros

Gwan-gyeong Mun
2022-10-29T05:35:22Z

Fix the size comparison code that implicitly assumes that the mask argument
of bitfield access macros is an unsigned long long type.
If unsigned int type is used for mask, the first argument of Bitfield
access macros, and clang is used to compile, this [1] option causes a build
error.[2]

[1] [-Werror,-Wtautological-constant-out-of-range-compare]
[2] https://lore.kernel.org/intel-gfx/c1c548f8-71a8-0d4d-d591-58a0cd5dac20@intel.com

Cc: Nick Desaulniers <ndesaulniers@google.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: llvm@lists.linux.dev
Cc: Ashutosh Dixit <ashutosh.dixit@intel.com>
Cc: Andi Shyti <andi.shyti@linux.intel.com>
Signed-off-by: Gwan-gyeong Mun <gwan-gyeong.mun@intel.com>
---
include/linux/bitfield.h | 22 +++++++++++++++++-----
1 file changed, 17 insertions(+), 5 deletions(-)

diff --git a/include/linux/bitfield.h b/include/linux/bitfield.h
index c9be1657f03d..4382bd62b14f 100644
--- a/include/linux/bitfield.h
+++ b/include/linux/bitfield.h
@@ -9,6 +9,7 @@

#include <linux/build_bug.h>
#include <asm/byteorder.h>
+#include <linux/overflow.h>

/*
* Bitfield access macros
@@ -69,7 +70,8 @@
~((_mask) >> __bf_shf(_mask)) & (_val) : 0, \
_pfx "value too large for the field"); \
BUILD_BUG_ON_MSG(__bf_cast_unsigned(_mask, _mask) > \
- __bf_cast_unsigned(_reg, ~0ull), \
+ __bf_cast_unsigned(_reg, \
+ type_max(__unsigned_scalar_typeof(_reg))), \
_pfx "type of reg too small for mask"); \
__BUILD_BUG_ON_NOT_POWER_OF_2((_mask) + \
(1ULL << __bf_shf(_mask))); \
@@ -84,7 +86,10 @@
*/
#define FIELD_MAX(_mask) \
({ \
- __BF_FIELD_CHECK(_mask, 0ULL, 0ULL, "FIELD_MAX: "); \
+ __BF_FIELD_CHECK(_mask, \
+ type_min(__unsigned_scalar_typeof(_mask)), \
+ type_min(__unsigned_scalar_typeof(_mask)), \
+ "FIELD_MAX: "); \
(typeof(_mask))((_mask) >> __bf_shf(_mask)); \
})

@@ -97,7 +102,10 @@
*/
#define FIELD_FIT(_mask, _val) \
({ \
- __BF_FIELD_CHECK(_mask, 0ULL, 0ULL, "FIELD_FIT: "); \
+ __BF_FIELD_CHECK(_mask, \
+ type_min(__unsigned_scalar_typeof(_mask)), \
+ type_min(__unsigned_scalar_typeof(_val)), \
+ "FIELD_FIT: "); \
!((((typeof(_mask))_val) << __bf_shf(_mask)) & ~(_mask)); \
})

@@ -111,7 +119,9 @@
*/
#define FIELD_PREP(_mask, _val) \
({ \
- __BF_FIELD_CHECK(_mask, 0ULL, _val, "FIELD_PREP: "); \
+ __BF_FIELD_CHECK(_mask, \
+ type_min(__unsigned_scalar_typeof(_mask)), \
+ _val, "FIELD_PREP: "); \
((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask); \
})

@@ -125,7 +135,9 @@
*/
#define FIELD_GET(_mask, _reg) \
({ \
- __BF_FIELD_CHECK(_mask, _reg, 0U, "FIELD_GET: "); \
+ __BF_FIELD_CHECK(_mask, _reg, \
+ type_min(__unsigned_scalar_typeof(_reg)), \
+ "FIELD_GET: "); \
(typeof(_mask))(((_reg) & (_mask)) >> __bf_shf(_mask)); \
})

--
2.37.1