[PATCH v4 4/8] bits: introduce fixed-type BIT

Vincent Mailhol via B4 Relay
2025-03-05T13:01:03Z

From: Lucas De Marchi <lucas.demarchi@intel.com>

Implement fixed-type BIT to help drivers add stricter checks, like was
done for GENMASK().

Signed-off-by: Lucas De Marchi <lucas.demarchi@intel.com>
Acked-by: Jani Nikula <jani.nikula@intel.com>
Signed-off-by: Vincent Mailhol <mailhol.vincent@wanadoo.fr>
---
Changelog:

v3 -> v4:

- Use const_true() to simplify BIT_INPUT_CHECK().

- Make BIT_U8() and BIT_U16() return an unsigned int instead of a
u8 and u16. Because of the integer promotion rules in C, an u8
or an u16 would become a signed integer as soon as these are
used in any expression. By casting these to unsigned ints, at
least the signedness is kept.

- Put the cast next to the BIT() macro.

- In BIT_U64(): use BIT_ULL() instead of BIT().
---
include/linux/bits.h | 16 ++++++++++++++++
1 file changed, 16 insertions(+)

diff --git a/include/linux/bits.h b/include/linux/bits.h
index f202e46d2f4b7899c16d975120f3fa3ae41556ae..1b6f5262b79093a01aae6c14ead944e0e85821cc 100644
--- a/include/linux/bits.h
+++ b/include/linux/bits.h
@@ -68,6 +68,22 @@
#define GENMASK_U128(h, l) \
(GENMASK_INPUT_CHECK(h, l) + __GENMASK_U128(h, l))

+/*
+ * Fixed-type variants of BIT(), with additional checks like GENMASK_t(). The
+ * following examples generate compiler warnings due to shift-count-overflow:
+ *
+ * - BIT_U8(8)
+ * - BIT_U32(-1)
+ * - BIT_U32(40)
+ */
+#define BIT_INPUT_CHECK(type, b) \
+ BUILD_BUG_ON_ZERO(const_true((b) >= BITS_PER_TYPE(type)))
+
+#define BIT_U8(b) (BIT_INPUT_CHECK(u8, b) + (unsigned int)BIT(b))
+#define BIT_U16(b) (BIT_INPUT_CHECK(u16, b) + (unsigned int)BIT(b))
+#define BIT_U32(b) (BIT_INPUT_CHECK(u32, b) + (u32)BIT(b))
+#define BIT_U64(b) (BIT_INPUT_CHECK(u64, b) + (u64)BIT_ULL(b))
+
#else /* defined(__ASSEMBLY__) */

#define GENMASK(h, l) __GENMASK(h, l)

--
2.45.3