Skip to contentSkip to conversation

Non-const bitfield helpers

PATCH In review Geert Uytterhoeven 11 participants 57 messages Nov 6, 2025 – Nov 29, 2025

Subsystems (21)
lore
Share & tools
lore

Geert Uytterhoeven

author maintainer
#0 lore raw

v6 cover Non-const bitfield helpers

Hi all,

<linux/bitfield.h> contains various helpers for accessing bitfields, as typically used in hardware registers for memory-mapped I/O blocks. These helpers ensure type safety, and deduce automatically shift values from mask values, avoiding mistakes due to inconsistent shifts and masks, and leading to a reduction in source code size.

The existing FIELD_{GET,PREP}() macros are limited to compile-time constants. However, it is very common to prepare or extract bitfield elements where the bitfield mask is not a compile-time constant (e.g. it comes from a table, or is created by shifting a compile-time constant). To avoid this limitation, the AT91 clock driver introduced its own field_{prep,get}() macros. During the past four years, these have been copied to multiple drivers, and more copies are on their way[1], leading to the obvious review comment "please move this to <linux/bitfield.h>".

Hence this series
1. Takes preparatory steps in drivers definining local

     field_{get,prep}() macros (patches 1-11),
  2. Introduces __FIELD_{PREP,GET}() helpers to avoid clang W=1 warnings
     (patch 12),
  3. Makes field_{prep,get}() available for general use (patch 13),
  4. Converts drivers with local variants to the common helpers (patches
     14-24),
  5. Converts a few Renesas drivers to the existing FIELD_{GET,PREP}()
     and the new field_{get,prep}() helpers (patches 25-26).

Alternatives would be to use the typed {u*,be*,le*,...}_{get,encode}_bits() macros instead (which currently do not work with non-constant masks either, and the first attempt to change that generates much worse code), or to store the low bit and width of the mask instead (which would require changing all code that passes masks directly, and also generates worse code).

Changes compared to v5[2]:
- Add Acked-by, Reviewed-by,
- Update sunxi rawnand driver in linux-next,
- Align \,
- Add Return sections to kerneldoc,
- Document field_{get,prep} in top comment block,
- New patch to add less-checking __FIELD_{GET,PREP}() helpers,
- Use less-checking __FIELD_{GET,PREP}() to avoid build issues with clang and W=1.

Changes compared to v4[3]:
- Add preparatory patches to #undef field_{get,prep}() in individual drivers before defining local variants,
- Update new smi330 IIO IMU driver in linux-next,
- Add Acked-by,
- Document that mask must be non-zero,
- Document typical usage pattern,
- Recommend using FIELD_{PREP,GET}() directly to ensure compile-time constant masks,
- Check BITS_PER_TYPE(mask) instead of sizeof(mask),
- Wire field_{get,prep}() to FIELD_{GET,PREP}() when mask is constant, to improve type checking,
- Extract conversion of individual drivers into separate patches.

Changes compared to v3[4]:
- Update recently introduced FIELD_MODIFY() macro,
- Add Acked-by,
- Rebase on top of commit 7c68005a46108ffa ("crypto: qat - relocate power management debugfs helper APIs") in v6.17-rc1,
- Convert more recently introduced upstream copies:
- drivers/edac/ie31200_edac.c
- drivers/iio/dac/ad3530r.c

Changes compared to v2[5]:
- New patch "[PATCH v3 1/4] bitfield: Drop underscores from macro parameters",
- Add Acked-by,
- Drop underscores from macro parameters,
- Use __auto_type where possible,
- Correctly cast reg to the mask type,
- Introduces __val and __reg intermediates to simplify the actual operation,
- Drop unneeded parentheses,
- Clarify having both FIELD_{GET,PREP}() and field_{get,prep}(),

Changes compared to v1[6]:
- Cast val resp. reg to the mask type,
- Fix 64-bit use on 32-bit architectures,
- Convert new upstream users:
- drivers/crypto/intel/qat/qat_common/adf_gen4_pm_debugfs.c
- drivers/gpio/gpio-aspeed.c
- drivers/iio/temperature/mlx90614.c
- drivers/pinctrl/nuvoton/pinctrl-ma35.c
- sound/usb/mixer_quirks.c
- Convert new user queued in renesas-devel for v6.15:
- drivers/soc/renesas/rz-sysc.c
- Drop the last 14 RFC patches.
They can be updated/resubmitted/applied later.

In the meantime, two more copies ended up in the IIO and MTD trees and in linux-next (commit 89cba586b8b4cde0 ("iio: imu: smi330: Add driver" in next-20251021 and later, commits 6fc2619af1eb6f59 ("mtd: rawnand:
sunxi: rework pattern found registers") and d21b4338159ff7d7 ("mtd:
rawnand: sunxi: introduce ecc_mode_mask in sunxi_nfc_caps") in next-20251029 and later). As these commits are not yet upstream, any updates (patches 10, 11, 23 and 24) for these drivers cannot be applied with the rest of this series yet.

Yury kindly offered to take the lionshare of this series through his bitmap tree, thanks for that!
I am fine with that, if he would also provide an immutable branch + tag, which I can merge into the Renesas tree before taking patches 25 and 26 myself. Once that tag has been merged in subsystem trees or upstream, I plan to update and resend actual conversions (see patches 4-17 in v1[6]).

To avoid build issues in linux-next, the IIO resp. MTD maintainers should:
1. Apply patch 10 resp. 11 now, and
2. Apply patch 23 resp. 24 later, either after
a. merging the immutable branch/tag, or
b. the new helpers in <linux/bitfield.h> are upstream,

Note that there is also a minor conflict with linux-next due to the removal of an include file from drivers/gpio/gpio-aspeed.c.

Thanks!

[1] Work-in-progress new copies posted during the last few months (there
may be more):
- "[PATCH v2 3/3] gpio: gpio-ltc4283: Add support for the LTC4283 Swap Controller"
https://lore.kernel.org/[email protected]
- "[PATCH v7 15/24] media: i2c: add Maxim GMSL2/3 serializer and deserializer framework"
https://lore.kernel.org/[email protected]
[2] "[PATCH v5 00/23] Non-const bitfield helpers"

    https://lore.kernel.org/all/[email protected]
[3] "[PATCH v4 0/4] Non-const bitfield helpers"
    https://lore.kernel.org/[email protected]
[4] "[PATCH v3 0/4] Non-const bitfield helpers"
    https://lore.kernel.org/all/[email protected]
[5] "[PATCH v2 0/3] Non-const bitfield helpers"
    https://lore.kernel.org/all/[email protected]
[6] "[PATCH 00/17] Non-const bitfield helper conversions"
    https://lore.kernel.org/all/[email protected]

Geert Uytterhoeven (26):
clk: at91: pmc: #undef field_{get,prep}() before definition
crypto: qat - #undef field_get() before local definition EDAC/ie31200: #undef field_get() before local definition
gpio: aspeed: #undef field_{get,prep}() before local definition
iio: dac: ad3530r: #undef field_prep() before local definition
iio: mlx90614: #undef field_{get,prep}() before local definition
pinctrl: ma35: #undef field_{get,prep}() before local definition
soc: renesas: rz-sysc: #undef field_get() before local definition
ALSA: usb-audio: #undef field_{get,prep}() before local definition [-next] iio: imu: smi330: #undef field_{get,prep}() before definition [-next] mtd: rawnand: sunxi: #undef field_{get,prep}() before local
definition
bitfield: Add less-checking __FIELD_{GET,PREP}()
bitfield: Add non-constant field_{prep,get}() helpers
clk: at91: Convert to common field_{get,prep}() helpers
crypto: qat - convert to common field_get() helper EDAC/ie31200: Convert to common field_get() helper
gpio: aspeed: Convert to common field_{get,prep}() helpers
iio: dac: Convert to common field_prep() helper
iio: mlx90614: Convert to common field_{get,prep}() helpers
pinctrl: ma35: Convert to common field_{get,prep}() helpers
soc: renesas: rz-sysc: Convert to common field_get() helper
ALSA: usb-audio: Convert to common field_{get,prep}() helpers [-next] iio: imu: smi330: Convert to common field_{get,prep}() helpers [-next] mtd: rawnand: sunxi: Convert to common field_{get,prep}()
helpers
clk: renesas: Use bitfield helpers
soc: renesas: Use bitfield helpers

 drivers/clk/at91/clk-peripheral.c             |  1 +
 drivers/clk/at91/pmc.h                        |  3 -
 drivers/clk/renesas/clk-div6.c                |  6 +-
 drivers/clk/renesas/rcar-gen3-cpg.c           | 15 +--
 drivers/clk/renesas/rcar-gen4-cpg.c           |  9 +-
 .../intel/qat/qat_common/adf_pm_dbgfs_utils.c |  8 +-
 drivers/edac/ie31200_edac.c                   |  4 +-
 drivers/gpio/gpio-aspeed.c                    |  5 +-
 drivers/iio/dac/ad3530r.c                     |  3 -
 drivers/iio/imu/smi330/smi330_core.c          |  4 -
 drivers/iio/temperature/mlx90614.c            |  5 +-
 drivers/mtd/nand/raw/sunxi_nand.c             |  4 -
 drivers/pinctrl/nuvoton/pinctrl-ma35.c        |  4 -
 drivers/soc/renesas/renesas-soc.c             |  4 +-
 drivers/soc/renesas/rz-sysc.c                 |  3 +-
 include/linux/bitfield.h                      | 95 +++++++++++++++++--
 sound/usb/mixer_quirks.c                      |  4 -
 17 files changed, 106 insertions(+), 71 deletions(-)
Signature · 12 lines
2.43.0

Gr{oetje,eeting}s,

						Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
							    -- Linus Torvalds
author maintainer
#1 lore raw

PATCH v6 1/26 clk: at91: pmc: #undef field_{get,prep}() before definition

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- Add Acked-by,

v5:
- New.

---
 drivers/clk/at91/pmc.h | 2 ++
 1 file changed, 2 insertions(+)
drivers/clk/at91/pmc.h +2 -0
index 5daa32c4cf2540d7..78a87d31463e98b0 100644
@@ -117,7 +117,9 @@ struct at91_clk_pms {
 	unsigned int parent;
 };
 
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
 
 #define ndck(a, s) (a[s - 1].id + 1)
Signature · 1 line
2.43.0
author maintainer
#4 lore raw

PATCH v6 2/26 crypto: qat - #undef field_get() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of a globally available common field_get() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

---
v6:
- Add Acked-by,

v5:
- New.

---
 drivers/crypto/intel/qat/qat_common/adf_pm_dbgfs_utils.c | 1 +
 1 file changed, 1 insertion(+)
drivers/crypto/intel/qat/qat_common/adf_pm_dbgfs_utils.c +1 -0
index 69295a9ddf0ac92f..6186fafb4a7b0dab 100644
@@ -11,6 +11,7 @@
  * pm_scnprint_table(), making it not compile time constant, so the compile
  * asserts from FIELD_GET() or u32_get_bits() won't be fulfilled.
  */
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
 
 #define PM_INFO_MAX_KEY_LEN	21
Signature · 1 line
2.43.0
author maintainer
#5 lore raw

PATCH v6 3/26 EDAC/ie31200: #undef field_get() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of a globally available common field_get() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

---
v6:
- No changes,

v5:
- New.

---
 drivers/edac/ie31200_edac.c | 1 +
 1 file changed, 1 insertion(+)
drivers/edac/ie31200_edac.c +1 -0
index 5a080ab65476dacf..72290f430126c631 100644
@@ -140,6 +140,7 @@
 #define IE31200_CAPID0_ECC		BIT(1)
 
 /* Non-constant mask variant of FIELD_GET() */
+#undef field_get
 #define field_get(_mask, _reg)  (((_reg) & (_mask)) >> (ffs(_mask) - 1))
 
 static int nr_channels;
Signature · 1 line
2.43.0
author maintainer
#7 lore raw

PATCH v6 4/26 gpio: aspeed: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- Add Acked-by,

v5:
- New.

---
 drivers/gpio/gpio-aspeed.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpio/gpio-aspeed.c +2 -0
index 7953a9c4e36d7550..ef4ccaf74a5b379e 100644
@@ -32,7 +32,9 @@
 #include "gpiolib.h"
 
 /* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
+#undef field_get
 #define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
 
 #define GPIO_G7_IRQ_STS_BASE 0x100
Signature · 1 line
2.43.0
author maintainer
#8 lore raw

PATCH v6 5/26 iio: dac: ad3530r: #undef field_prep() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of a globally available common field_prep() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/dac/ad3530r.c | 1 +
 1 file changed, 1 insertion(+)
drivers/iio/dac/ad3530r.c +1 -0
index 6134613777b8e1d4..5684d11137f29948 100644
@@ -54,6 +54,7 @@
 #define AD3531R_MAX_CHANNELS			4
 
 /* Non-constant mask variant of FIELD_PREP() */
+#undef field_prep
 #define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
 
 enum ad3530r_mode {
Signature · 1 line
2.43.0
author maintainer
#10 lore raw

PATCH v6 6/26 iio: mlx90614: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/temperature/mlx90614.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/iio/temperature/mlx90614.c +2 -0
index 8a44a00bfd5ece38..de5615fdb396aa3c 100644
@@ -69,7 +69,9 @@
 #define MLX90614_CONST_FIR 0x7 /* Fixed value for FIR part of low pass filter */
 
 /* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
+#undef field_get
 #define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
 
 struct mlx_chip_info {
Signature · 1 line
2.43.0
author maintainer
#12 lore raw

PATCH v6 7/26 pinctrl: ma35: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- Add Acked-by,

v5:
- New.

---
 drivers/pinctrl/nuvoton/pinctrl-ma35.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/pinctrl/nuvoton/pinctrl-ma35.c +2 -0
index cdad01d68a37e365..925dd717c9deead5 100644
@@ -82,7 +82,9 @@
 #define MVOLT_3300			1
 
 /* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
+#undef field_get
 #define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
 
 static const char * const gpio_group_name[] = {
Signature · 1 line
2.43.0
author maintainer
#13 lore raw

PATCH v6 8/26 soc: renesas: rz-sysc: #undef field_get() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of a globally available common field_get() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

---
v6:
- No changes,

v5:
- New.

---
 drivers/soc/renesas/rz-sysc.c | 1 +
 1 file changed, 1 insertion(+)
drivers/soc/renesas/rz-sysc.c +1 -0
index 9f79e299e6f41641..b9880085d3634065 100644
@@ -16,6 +16,7 @@
 
 #include "rz-sysc.h"
 
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
 
 /**
Signature · 1 line
2.43.0
author maintainer
#15 lore raw

PATCH v6 9/26 ALSA: usb-audio: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- Add Acked-by,

v5:
- New.

---
 sound/usb/mixer_quirks.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/mixer_quirks.c +2 -0
index 828af3095b86ee0a..713a8498b975e1ac 100644
@@ -3312,7 +3312,9 @@ static int snd_bbfpro_controls_create(struct usb_mixer_interface *mixer)
 #define RME_DIGIFACE_INVERT BIT(31)
 
 /* Nonconst helpers */
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
 
 static int snd_rme_digiface_write_reg(struct snd_kcontrol *kcontrol, int item, u16 mask, u16 val)
Signature · 1 line
2.43.0
author maintainer
#16 lore raw

PATCH v6 10/26 iio: imu: smi330: #undef field_{get,prep}() before definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/imu/smi330/smi330_core.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/iio/imu/smi330/smi330_core.c +2 -0
index d9178725ade3da83..a79964fe68fadf47 100644
@@ -68,7 +68,9 @@
 #define SMI330_SOFT_RESET_DELAY 2000
 
 /* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
 
 #define SMI330_ACCEL_CHANNEL(_axis) {					\
Signature · 1 line
2.43.0
author maintainer
#18 lore raw

PATCH v6 11/26 mtd: rawnand: sunxi: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---
v6:
- New.

---
 drivers/mtd/nand/raw/sunxi_nand.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/mtd/nand/raw/sunxi_nand.c +2 -0
index 031ab651c5a83b74..9dcdc93734cbff39 100644
@@ -30,7 +30,9 @@
 #include <linux/reset.h>
 
 /* non compile-time field get/prep */
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
 
 #define NFC_REG_CTL		0x0000
Signature · 1 line
2.43.0
author maintainer
#20 lore raw

PATCH v6 12/26 bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

---
v6:
- New.

Alternatively, FIELD_{GET,PREP}() could be duplicated, with the second parameter of __BF_FIELD_CHECK() changed from "0ULL" resp. "_reg" to "_mask":

    #define __FIELD_PREP(_mask, _val)                                      \
	   ({                                                              \
		   __BF_FIELD_CHECK(_mask, _mask, _val, "__FIELD_PREP: "); \
		   ((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask);   \
	   })

    #define __FIELD_GET(_mask, _reg)                                       \
	   ({                                                              \
		   __BF_FIELD_CHECK(_mask, _mask, 0U, "__FIELD_GET: ");    \
		   (typeof(_mask))(((_reg) & (_mask)) >> __bf_shf(_mask)); \
	   })

But I think that is less intuitive, and prevents defining FIELD_{GET,PREP}() using __FIELD_{GET,PREP}().

---
 include/linux/bitfield.h | 36 ++++++++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 8 deletions(-)
include/linux/bitfield.h +28 -8
index 5355f8f806a97974..bf8e0ae4b5b41038 100644
@@ -60,7 +60,7 @@
 
 #define __bf_cast_unsigned(type, x)	((__unsigned_scalar_typeof(type))(x))
 
-#define __BF_FIELD_CHECK(_mask, _reg, _val, _pfx)			\
+#define __BF_FIELD_CHECK_MASK(_mask, _val, _pfx)			\
 	({								\
 		BUILD_BUG_ON_MSG(!__builtin_constant_p(_mask),		\
 				 _pfx "mask is not constant");		\
@@ -69,13 +69,33 @@
 				 ~((_mask) >> __bf_shf(_mask)) &	\
 					(0 + (_val)) : 0,		\
 				 _pfx "value too large for the field"); \
-		BUILD_BUG_ON_MSG(__bf_cast_unsigned(_mask, _mask) >	\
-				 __bf_cast_unsigned(_reg, ~0ull),	\
-				 _pfx "type of reg too small for mask"); \
 		__BUILD_BUG_ON_NOT_POWER_OF_2((_mask) +			\
 					      (1ULL << __bf_shf(_mask))); \
 	})
 
+#define __BF_FIELD_CHECK_REG(mask, reg, pfx)				\
+	BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >		\
+			 __bf_cast_unsigned(reg, ~0ull),		\
+			 pfx "type of reg too small for mask")
+
+#define __BF_FIELD_CHECK(mask, reg, val, pfx)				\
+	({								\
+		__BF_FIELD_CHECK_MASK(mask, val, pfx);			\
+		__BF_FIELD_CHECK_REG(mask, reg, pfx);			\
+	})
+
+#define __FIELD_PREP(mask, val, pfx)					\
+	({								\
+		__BF_FIELD_CHECK_MASK(mask, val, pfx);			\
+		((typeof(mask))(val) << __bf_shf(mask)) & (mask);	\
+	})
+
+#define __FIELD_GET(mask, reg, pfx)					\
+	({								\
+		__BF_FIELD_CHECK_MASK(mask, 0U, pfx);			\
+		(typeof(mask))(((reg) & (mask)) >> __bf_shf(mask));	\
+	})
+
 /**
  * FIELD_MAX() - produce the maximum value representable by a field
  * @_mask: shifted mask defining the field's length and position
@@ -112,8 +132,8 @@
  */
 #define FIELD_PREP(_mask, _val)						\
 	({								\
-		__BF_FIELD_CHECK(_mask, 0ULL, _val, "FIELD_PREP: ");	\
-		((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask);	\
+		__BF_FIELD_CHECK_REG(_mask, 0ULL, "FIELD_PREP: ");	\
+		__FIELD_PREP(_mask, _val, "FIELD_PREP: ");		\
 	})
 
 #define __BF_CHECK_POW2(n)	BUILD_BUG_ON_ZERO(((n) & ((n) - 1)) != 0)
@@ -152,8 +172,8 @@
  */
 #define FIELD_GET(_mask, _reg)						\
 	({								\
-		__BF_FIELD_CHECK(_mask, _reg, 0U, "FIELD_GET: ");	\
-		(typeof(_mask))(((_reg) & (_mask)) >> __bf_shf(_mask));	\
+		__BF_FIELD_CHECK_REG(_mask, _reg, "FIELD_GET: ");	\
+		__FIELD_GET(_mask, _reg, "FIELD_GET: ");		\
 	})
 
 /**
Signature · 1 line
2.43.0
author maintainer
#33 lore raw

PATCH v6 13/26 bitfield: Add non-constant field_{prep,get}() helpers

In reply to Geert Uytterhoeven

The existing FIELD_{GET,PREP}() macros are limited to compile-time constants. However, it is very common to prepare or extract bitfield elements where the bitfield mask is not a compile-time constant.

To avoid this limitation, the AT91 clock driver and several other drivers already have their own non-const field_{prep,get}() macros. Make them available for general use by adding them to <linux/bitfield.h>, and improve them slightly:
1. Avoid evaluating macro parameters more than once,
2. Replace "ffs() - 1" by "__ffs()",
3. Support 64-bit use on 32-bit architectures,
4. Wire field_{get,prep}() to FIELD_{GET,PREP}() when mask is actually constant.

This is deliberately not merged into the existing FIELD_{GET,PREP}() macros, as people expressed the desire to keep stricter variants for increased safety, or for performance critical paths.

---
v6:
- Align \,
- Add Return sections to kerneldoc,
- Add Reviewed-by,
- Document field_{get,prep} in top comment block,
- Use less-checking __FIELD_{GET,PREP}() to avoid build issues with

    clang and W=1:
    https://lore.kernel.org/all/[email protected]
    https://lore.kernel.org/all/[email protected]
    https://lore.kernel.org/all/[email protected]

v5:
- Add Acked-by,
- Split off changes outside <linux/bitfield.h>,
- Document that mask must be non-zero,
- Document typical usage pattern,
- Recommend using FIELD_{PREP,GET}() directly to ensure compile-time constant masks,
- Check BITS_PER_TYPE(mask) instead of sizeof(mask),
- Wire field_{get,prep}() to FIELD_{GET,PREP}() when mask is constant, to improve type checking.

v4:
- Add Acked-by,
- Rebase on top of commit 7c68005a46108ffa ("crypto: qat - relocate power management debugfs helper APIs") in v6.17-rc1,
- Convert more recently introduced upstream copies:
- drivers/edac/ie31200_edac.c
- drivers/iio/dac/ad3530r.c

v3:
- Add Acked-by,
- Drop underscores from macro parameters,
- Use __auto_type where possible,
- Correctly cast reg to the mask type,
- Introduces __val and __reg intermediates to simplify the actual operation,
- Drop unneeded parentheses,
- Clarify having both FIELD_{GET,PREP}() and field_{get,prep}(),

v2:
- Cast val resp. reg to the mask type,
- Fix 64-bit use on 32-bit architectures,
- Convert new upstream users:
- drivers/crypto/intel/qat/qat_common/adf_gen4_pm_debugfs.c
- drivers/gpio/gpio-aspeed.c
- drivers/iio/temperature/mlx90614.c
- drivers/pinctrl/nuvoton/pinctrl-ma35.c
- sound/usb/mixer_quirks.c
- Convert new user queued in renesas-devel for v6.15:
- drivers/soc/renesas/rz-sysc.c

---
 include/linux/bitfield.h | 59 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 59 insertions(+)
include/linux/bitfield.h +59 -0
index bf8e0ae4b5b41038..f92e18c9629a59c6 100644
@@ -17,6 +17,7 @@
  * FIELD_{GET,PREP} macros take as first parameter shifted mask
  * from which they extract the base mask and shift amount.
  * Mask must be a compilation time constant.
+ * field_{get,prep} are variants that take a non-const mask.
  *
  * Example:
  *
@@ -240,4 +241,62 @@ __MAKE_OP(64)
 #undef __MAKE_OP
 #undef ____MAKE_OP
 
+#define __field_prep(mask, val)						\
+	({								\
+		__auto_type __mask = (mask);				\
+		typeof(mask) __val = (val);				\
+		unsigned int __shift = BITS_PER_TYPE(mask) <= 32 ?	\
+				       __ffs(__mask) : __ffs64(__mask);	\
+		(__val << __shift) & __mask;				\
+	})
+
+#define __field_get(mask, reg)						\
+	({								\
+		__auto_type __mask = (mask);				\
+		typeof(mask) __reg =  (reg);				\
+		unsigned int __shift = BITS_PER_TYPE(mask) <= 32 ?	\
+				       __ffs(__mask) : __ffs64(__mask);	\
+		(__reg & __mask) >> __shift;				\
+	})
+
+/**
+ * field_prep() - prepare a bitfield element
+ * @mask: shifted mask defining the field's length and position, must be
+ *        non-zero
+ * @val:  value to put in the field
+ *
+ * Return: field value masked and shifted to its final destination
+ *
+ * field_prep() masks and shifts up the value.  The result should be
+ * combined with other fields of the bitfield using logical OR.
+ * Unlike FIELD_PREP(), @mask is not limited to a compile-time constant.
+ * Typical usage patterns are a value stored in a table, or calculated by
+ * shifting a constant by a variable number of bits.
+ * If you want to ensure that @mask is a compile-time constant, please use
+ * FIELD_PREP() directly instead.
+ */
+#define field_prep(mask, val)						\
+	(__builtin_constant_p(mask) ? __FIELD_PREP(mask, val, "field_prep: ") \
+				    : __field_prep(mask, val))
+
+/**
+ * field_get() - extract a bitfield element
+ * @mask: shifted mask defining the field's length and position, must be
+ *        non-zero
+ * @reg:  value of entire bitfield
+ *
+ * Return: extracted field value
+ *
+ * field_get() extracts the field specified by @mask from the
+ * bitfield passed in as @reg by masking and shifting it down.
+ * Unlike FIELD_GET(), @mask is not limited to a compile-time constant.
+ * Typical usage patterns are a value stored in a table, or calculated by
+ * shifting a constant by a variable number of bits.
+ * If you want to ensure that @mask is a compile-time constant, please use
+ * FIELD_GET() directly instead.
+ */
+#define field_get(mask, reg)						\
+	(__builtin_constant_p(mask) ? __FIELD_GET(mask, reg, "field_get: ") \
+				    : __field_get(mask, reg))
+
 #endif
Signature · 1 line
2.43.0
author maintainer
#35 lore raw

PATCH v6 14/26 clk: at91: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/clk/at91/clk-peripheral.c | 1 +
 drivers/clk/at91/pmc.h            | 5 -----
 2 files changed, 1 insertion(+), 5 deletions(-)
drivers/clk/at91/clk-peripheral.c +1 -0
index e700f40fd87f9327..e7208c47268b6397 100644
@@ -3,6 +3,7 @@
  *  Copyright (C) 2013 Boris BREZILLON <[email protected]>
  */
 
+#include <linux/bitfield.h>
 #include <linux/bitops.h>
 #include <linux/clk-provider.h>
 #include <linux/clkdev.h>
drivers/clk/at91/pmc.h +0 -5
index 78a87d31463e98b0..543d7aee8d248cdb 100644
@@ -117,11 +117,6 @@ struct at91_clk_pms {
 	unsigned int parent;
 };
 
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
-
 #define ndck(a, s) (a[s - 1].id + 1)
 #define nck(a) (a[ARRAY_SIZE(a) - 1].id + 1)
 
Signature · 1 line
2.43.0
author maintainer
#38 lore raw

PATCH v6 15/26 crypto: qat - convert to common field_get() helper

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() macro, in favor of the globally available variant from <linux/bitfield.h>.

---
v6:
- Add Acked-by,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/crypto/intel/qat/qat_common/adf_pm_dbgfs_utils.c | 9 +--------
 1 file changed, 1 insertion(+), 8 deletions(-)
drivers/crypto/intel/qat/qat_common/adf_pm_dbgfs_utils.c +1 -8
index 6186fafb4a7b0dab..4ccc94ed9493a64c 100644
@@ -1,19 +1,12 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright(c) 2025 Intel Corporation */
+#include <linux/bitfield.h>
 #include <linux/bitops.h>
 #include <linux/sprintf.h>
 #include <linux/string_helpers.h>
 
 #include "adf_pm_dbgfs_utils.h"
 
-/*
- * This is needed because a variable is used to index the mask at
- * pm_scnprint_table(), making it not compile time constant, so the compile
- * asserts from FIELD_GET() or u32_get_bits() won't be fulfilled.
- */
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-
 #define PM_INFO_MAX_KEY_LEN	21
 
 static int pm_scnprint_table(char *buff, const struct pm_status_row *table,
Signature · 1 line
2.43.0
author maintainer
#39 lore raw

PATCH v6 16/26 EDAC/ie31200: Convert to common field_get() helper

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() macro, in favor of the globally available variant from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/edac/ie31200_edac.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/edac/ie31200_edac.c +1 -4
index 72290f430126c631..dfc9a9cecd74207d 100644
@@ -44,6 +44,7 @@
  * but lo_hi_readq() ensures that we are safe across all e3-1200 processors.
  */
 
+#include <linux/bitfield.h>
 #include <linux/module.h>
 #include <linux/init.h>
 #include <linux/pci.h>
@@ -139,10 +140,6 @@
 #define IE31200_CAPID0_DDPCD		BIT(6)
 #define IE31200_CAPID0_ECC		BIT(1)
 
-/* Non-constant mask variant of FIELD_GET() */
-#undef field_get
-#define field_get(_mask, _reg)  (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-
 static int nr_channels;
 static struct pci_dev *mci_pdev;
 static int ie31200_registered = 1;
Signature · 1 line
2.43.0
author maintainer
#41 lore raw

PATCH v6 17/26 gpio: aspeed: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/gpio/gpio-aspeed.c | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)
drivers/gpio/gpio-aspeed.c +1 -6
index ef4ccaf74a5b379e..3da999334971d501 100644
@@ -5,6 +5,7 @@
  * Joel Stanley <[email protected]>
  */
 
+#include <linux/bitfield.h>
 #include <linux/cleanup.h>
 #include <linux/clk.h>
 #include <linux/gpio/aspeed.h>
@@ -31,12 +32,6 @@
 #include <linux/gpio/consumer.h>
 #include "gpiolib.h"
 
-/* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
-#undef field_get
-#define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
-
 #define GPIO_G7_IRQ_STS_BASE 0x100
 #define GPIO_G7_IRQ_STS_OFFSET(x) (GPIO_G7_IRQ_STS_BASE + (x) * 0x4)
 #define GPIO_G7_CTRL_REG_BASE 0x180
Signature · 1 line
2.43.0
author maintainer
#42 lore raw

PATCH v6 18/26 iio: dac: Convert to common field_prep() helper

In reply to Geert Uytterhoeven

Drop the driver-specific field_prep() macro, in favor of the globally available variant from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/iio/dac/ad3530r.c | 4 ----
 1 file changed, 4 deletions(-)
drivers/iio/dac/ad3530r.c +0 -4
index 5684d11137f29948..b97b46090d808ee7 100644
@@ -53,10 +53,6 @@
 #define AD3530R_MAX_CHANNELS			8
 #define AD3531R_MAX_CHANNELS			4
 
-/* Non-constant mask variant of FIELD_PREP() */
-#undef field_prep
-#define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
-
 enum ad3530r_mode {
 	AD3530R_NORMAL_OP,
 	AD3530R_POWERDOWN_1K,
Signature · 1 line
2.43.0
author maintainer
#43 lore raw

PATCH v6 19/26 iio: mlx90614: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/iio/temperature/mlx90614.c | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)
drivers/iio/temperature/mlx90614.c +1 -6
index de5615fdb396aa3c..1ad21b73e1b44cb0 100644
@@ -22,6 +22,7 @@
  * the "wakeup" GPIO is not given, power management will be disabled.
  */
 
+#include <linux/bitfield.h>
 #include <linux/delay.h>
 #include <linux/err.h>
 #include <linux/gpio/consumer.h>
@@ -68,12 +69,6 @@
 #define MLX90614_CONST_SCALE 20 /* Scale in milliKelvin (0.02 * 1000) */
 #define MLX90614_CONST_FIR 0x7 /* Fixed value for FIR part of low pass filter */
 
-/* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
-#undef field_get
-#define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
-
 struct mlx_chip_info {
 	/* EEPROM offsets with 16-bit data, MSB first */
 	/* emissivity correction coefficient */
Signature · 1 line
2.43.0
author maintainer
#44 lore raw

PATCH v6 20/26 pinctrl: ma35: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- Add Reviewed-by,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/pinctrl/nuvoton/pinctrl-ma35.c | 6 ------
 1 file changed, 6 deletions(-)
drivers/pinctrl/nuvoton/pinctrl-ma35.c +0 -6
index 925dd717c9deead5..8d71dc53cc1de1f8 100644
@@ -81,12 +81,6 @@
 #define MVOLT_1800			0
 #define MVOLT_3300			1
 
-/* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
-#undef field_get
-#define field_get(_mask, _reg)	(((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
-
 static const char * const gpio_group_name[] = {
 	"gpioa", "gpiob", "gpioc", "gpiod", "gpioe", "gpiof", "gpiog",
 	"gpioh", "gpioi", "gpioj", "gpiok", "gpiol", "gpiom", "gpion",
Signature · 1 line
2.43.0
author maintainer
#45 lore raw

PATCH v6 21/26 soc: renesas: rz-sysc: Convert to common field_get() helper

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() macro, in favor of the globally available variant from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 drivers/soc/renesas/rz-sysc.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/soc/renesas/rz-sysc.c +1 -3
index b9880085d3634065..73eaf8b9d69f7208 100644
@@ -5,6 +5,7 @@
  * Copyright (C) 2024 Renesas Electronics Corp.
  */
 
+#include <linux/bitfield.h>
 #include <linux/cleanup.h>
 #include <linux/io.h>
 #include <linux/mfd/syscon.h>
@@ -16,9 +17,6 @@
 
 #include "rz-sysc.h"
 
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-
 /**
  * struct rz_sysc - RZ SYSC private data structure
  * @base: SYSC base address
Signature · 1 line
2.43.0
author maintainer
#47 lore raw

PATCH v6 22/26 ALSA: usb-audio: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- Add Acked-by,

v5:
- Extracted from "bitfield: Add non-constant field_{prep,get}() helpers".

---
 sound/usb/mixer_quirks.c | 6 ------
 1 file changed, 6 deletions(-)
sound/usb/mixer_quirks.c +0 -6
index 713a8498b975e1ac..6eee89cbc0867f2b 100644
@@ -3311,12 +3311,6 @@ static int snd_bbfpro_controls_create(struct usb_mixer_interface *mixer)
 #define RME_DIGIFACE_REGISTER(reg, mask) (((reg) << 16) | (mask))
 #define RME_DIGIFACE_INVERT BIT(31)
 
-/* Nonconst helpers */
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
-
 static int snd_rme_digiface_write_reg(struct snd_kcontrol *kcontrol, int item, u16 mask, u16 val)
 {
 	struct usb_mixer_elem_list *list = snd_kcontrol_chip(kcontrol);
Signature · 1 line
2.43.0
author maintainer
#48 lore raw

PATCH v6 23/26 iio: imu: smi330: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/imu/smi330/smi330_core.c | 6 ------
 1 file changed, 6 deletions(-)
drivers/iio/imu/smi330/smi330_core.c +0 -6
index a79964fe68fadf47..83e0dff5d973d046 100644
@@ -67,12 +67,6 @@
 #define SMI330_CHIP_ID 0x42
 #define SMI330_SOFT_RESET_DELAY 2000
 
-/* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
-
 #define SMI330_ACCEL_CHANNEL(_axis) {					\
 	.type = IIO_ACCEL,						\
 	.modified = 1,							\
Signature · 1 line
2.43.0
author maintainer
#50 lore raw

PATCH v6 24/26 mtd: rawnand: sunxi: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- New.

---
 drivers/mtd/nand/raw/sunxi_nand.c | 6 ------
 1 file changed, 6 deletions(-)
drivers/mtd/nand/raw/sunxi_nand.c +0 -6
index 9dcdc93734cbff39..e66adfcca7cd63fb 100644
@@ -29,12 +29,6 @@
 #include <linux/iopoll.h>
 #include <linux/reset.h>
 
-/* non compile-time field get/prep */
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
-
 #define NFC_REG_CTL		0x0000
 #define NFC_REG_ST		0x0004
 #define NFC_REG_INT		0x0008
Signature · 1 line
2.43.0
author maintainer
#52 lore raw

PATCH v6 25/26 clk: renesas: Use bitfield helpers

In reply to Geert Uytterhoeven

Use the FIELD_{GET,PREP}() and field_{get,prep}() helpers for const respective non-const bitfields, instead of open-coding the same operations.

---
v6:
- No changes,

v5:
- No changes,

v4:
- No changes,

v3:
- No changes,

v2:
- Rebase on top of commit 470e3f0d0b1529ab ("clk: renesas: rcar-gen4:
Introduce R-Car Gen4 CPG driver").

---
 drivers/clk/renesas/clk-div6.c      |  6 +++---
 drivers/clk/renesas/rcar-gen3-cpg.c | 15 +++++----------
 drivers/clk/renesas/rcar-gen4-cpg.c |  9 +++------
 3 files changed, 11 insertions(+), 19 deletions(-)
drivers/clk/renesas/clk-div6.c +3 -3
index 3abd6e5400aded6a..f7b827b5e9b2dd32 100644
@@ -7,6 +7,7 @@
  * Contact: Laurent Pinchart <[email protected]>
  */
 
+#include <linux/bitfield.h>
 #include <linux/clk-provider.h>
 #include <linux/init.h>
 #include <linux/io.h>
@@ -171,8 +172,7 @@ static u8 cpg_div6_clock_get_parent(struct clk_hw *hw)
 	if (clock->src_mask == 0)
 		return 0;
 
-	hw_index = (readl(clock->reg) & clock->src_mask) >>
-		   __ffs(clock->src_mask);
+	hw_index = field_get(clock->src_mask, readl(clock->reg));
 	for (i = 0; i < clk_hw_get_num_parents(hw); i++) {
 		if (clock->parents[i] == hw_index)
 			return i;
@@ -191,7 +191,7 @@ static int cpg_div6_clock_set_parent(struct clk_hw *hw, u8 index)
 	if (index >= clk_hw_get_num_parents(hw))
 		return -EINVAL;
 
-	src = clock->parents[index] << __ffs(clock->src_mask);
+	src = field_prep(clock->src_mask, clock->parents[index]);
 	writel((readl(clock->reg) & ~clock->src_mask) | src, clock->reg);
 	return 0;
 }
drivers/clk/renesas/rcar-gen3-cpg.c +5 -10
index 10ae20489df9abd8..b954278ddd9d8aa8 100644
@@ -54,10 +54,8 @@ static unsigned long cpg_pll_clk_recalc_rate(struct clk_hw *hw,
 {
 	struct cpg_pll_clk *pll_clk = to_pll_clk(hw);
 	unsigned int mult;
-	u32 val;
 
-	val = readl(pll_clk->pllcr_reg) & CPG_PLLnCR_STC_MASK;
-	mult = (val >> __ffs(CPG_PLLnCR_STC_MASK)) + 1;
+	mult = FIELD_GET(CPG_PLLnCR_STC_MASK, readl(pll_clk->pllcr_reg)) + 1;
 
 	return parent_rate * mult * pll_clk->fixed_mult;
 }
@@ -94,7 +92,7 @@ static int cpg_pll_clk_set_rate(struct clk_hw *hw, unsigned long rate,
 
 	val = readl(pll_clk->pllcr_reg);
 	val &= ~CPG_PLLnCR_STC_MASK;
-	val |= (mult - 1) << __ffs(CPG_PLLnCR_STC_MASK);
+	val |= FIELD_PREP(CPG_PLLnCR_STC_MASK, mult - 1);
 	writel(val, pll_clk->pllcr_reg);
 
 	for (i = 1000; i; i--) {
@@ -176,11 +174,7 @@ static unsigned long cpg_z_clk_recalc_rate(struct clk_hw *hw,
 					   unsigned long parent_rate)
 {
 	struct cpg_z_clk *zclk = to_z_clk(hw);
-	unsigned int mult;
-	u32 val;
-
-	val = readl(zclk->reg) & zclk->mask;
-	mult = 32 - (val >> __ffs(zclk->mask));
+	unsigned int mult = 32 - field_get(zclk->mask, readl(zclk->reg));
 
 	return DIV_ROUND_CLOSEST_ULL((u64)parent_rate * mult,
 				     32 * zclk->fixed_div);
@@ -231,7 +225,8 @@ static int cpg_z_clk_set_rate(struct clk_hw *hw, unsigned long rate,
 	if (readl(zclk->kick_reg) & CPG_FRQCRB_KICK)
 		return -EBUSY;
 
-	cpg_reg_modify(zclk->reg, zclk->mask, (32 - mult) << __ffs(zclk->mask));
+	cpg_reg_modify(zclk->reg, zclk->mask,
+		       field_prep(zclk->mask, 32 - mult));
 
 	/*
 	 * Set KICK bit in FRQCRB to update hardware setting and wait for
drivers/clk/renesas/rcar-gen4-cpg.c +3 -6
index fb9a876aaba5cbcd..db3a0b8ef2b936bb 100644
@@ -279,11 +279,7 @@ static unsigned long cpg_z_clk_recalc_rate(struct clk_hw *hw,
 					   unsigned long parent_rate)
 {
 	struct cpg_z_clk *zclk = to_z_clk(hw);
-	unsigned int mult;
-	u32 val;
-
-	val = readl(zclk->reg) & zclk->mask;
-	mult = 32 - (val >> __ffs(zclk->mask));
+	unsigned int mult = 32 - field_get(zclk->mask, readl(zclk->reg));
 
 	return DIV_ROUND_CLOSEST_ULL((u64)parent_rate * mult,
 				     32 * zclk->fixed_div);
@@ -334,7 +330,8 @@ static int cpg_z_clk_set_rate(struct clk_hw *hw, unsigned long rate,
 	if (readl(zclk->kick_reg) & CPG_FRQCRB_KICK)
 		return -EBUSY;
 
-	cpg_reg_modify(zclk->reg, zclk->mask, (32 - mult) << __ffs(zclk->mask));
+	cpg_reg_modify(zclk->reg, zclk->mask,
+		       field_prep(zclk->mask, 32 - mult));
 
 	/*
 	 * Set KICK bit in FRQCRB to update hardware setting and wait for
Signature · 1 line
2.43.0
author maintainer
#54 lore raw

PATCH v6 26/26 soc: renesas: Use bitfield helpers

In reply to Geert Uytterhoeven

Use the field_get() helper, instead of open-coding the same operation.

---
v6:
- No changes,

v5:
- No changes,

v4:
- No changes,

v3:
- No changes,

v2:
- Drop RFC, as a dependency was applied.

---
 drivers/soc/renesas/renesas-soc.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/soc/renesas/renesas-soc.c +2 -2
index 1eb52356b996bdd7..ee4f17bb4db45db7 100644
@@ -5,6 +5,7 @@
  * Copyright (C) 2014-2016 Glider bvba
  */
 
+#include <linux/bitfield.h>
 #include <linux/io.h>
 #include <linux/of.h>
 #include <linux/of_address.h>
@@ -524,8 +525,7 @@ static int __init renesas_soc_init(void)
 							   eshi, eslo);
 		}
 
-		if (soc->id &&
-		    ((product & id->mask) >> __ffs(id->mask)) != soc->id) {
+		if (soc->id && field_get(id->mask, product) != soc->id) {
 			pr_warn("SoC mismatch (product = 0x%x)\n", product);
 			ret = -ENODEV;
 			goto free_soc_dev_attr;
Signature · 1 line
2.43.0
maintainer Acked-by on v6 24/26
#51 lore raw

Re: [PATCH -next v6 24/26] mtd: rawnand: sunxi: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Hello Geert,

Quoted 7 lines · Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---
v6:
- New.

Thanks for preemptively handling this case!

Thansk,
Miquèl

#21 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Geert Uytterhoeven
Quoted 16 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

Quoted 4 lines

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

Also can be made as

The positive effect that one may click that on Git Web.
Ideally, of course, would be an additional parses on Git Web kernel.org uses to parse that standard "commit ...()" notation to add the respective HREF link.

Quoted 1 line

...

include/linux/bitfield.h line 79

Quoted 3 lines
include/linux/bitfield.h +3 -0
+	BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >		\
+			 __bf_cast_unsigned(reg, ~0ull),		\
+			 pfx "type of reg too small for mask")

Perhaps we may convert this (and others?) to static_assert():s at some point?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#22 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

Hi Andy,

Quoted 17 lines · Andy Shevchenko
Quoted 16 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

Quoted 8 lines
Quoted 4 lines

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

Also can be made as

Nooooh... torvalds might click on it, and complain ;-)

Quoted 5 lines

include/linux/bitfield.h line 79

Quoted 3 lines
include/linux/bitfield.h +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
maintainer Acked-by on v6 1/26
#2 lore raw

Re: [PATCH v6 01/26] clk: at91: pmc: #undef field_{get,prep}() before definition

In reply to Geert Uytterhoeven
Quoted 8 lines · Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

maintainer Reviewed-by on v6 8/26
#14 lore raw

Re: [PATCH v6 08/26] soc: renesas: rz-sysc: #undef field_get() before local definition

In reply to Geert Uytterhoeven
Quoted 7 lines · Geert Uytterhoeven

Prepare for the advent of a globally available common field_get() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

maintainer Acked-by on v6 14/26
#36 lore raw

Re: [PATCH v6 14/26] clk: at91: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven
Quoted 5 lines · Geert Uytterhoeven

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

maintainer
#31 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Andy Shevchenko
Quoted 23 lines · Andy Shevchenko
Quoted 16 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

Quoted 4 lines

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

Quoted 7 lines

Also can be made as

The positive effect that one may click that on Git Web.
Ideally, of course, would be an additional parses on Git Web kernel.org uses to parse that standard "commit ...()" notation to add the respective HREF link.

Those flying over Atlantic or cruising cross Caribbean would disagree. :)

Quoted 15 lines
Quoted 1 line

...

include/linux/bitfield.h line 79

Quoted 3 lines
include/linux/bitfield.h +3 -0
+	BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >		\
+			 __bf_cast_unsigned(reg, ~0ull),		\
+			 pfx "type of reg too small for mask")

Perhaps we may convert this (and others?) to static_assert():s at some point?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#32 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

Quoted 26 lines · Yury Norov
Quoted 25 lines · Andy Shevchenko
Quoted 16 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

Quoted 4 lines

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

Also can be made as

Quoted 7 lines
Quoted 5 lines

The positive effect that one may click that on Git Web.
Ideally, of course, would be an additional parses on Git Web kernel.org uses to parse that standard "commit ...()" notation to add the respective HREF link.

Those flying over Atlantic or cruising cross Caribbean would disagree. :)

They won't. The purpose of these Links is described in the above commit message. Even they read the commit message before clicking.

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#23 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Geert Uytterhoeven
Quoted 26 lines · Geert Uytterhoeven

Hi Andy,

Quoted 22 lines · Andy Shevchenko
Quoted 20 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

[1] commit 5c667d5a5a3ec166 ("clk: sp7021: Adjust width of _m in

    HWM_FIELD_PREP()")

[2] commit cfd6fb45cfaf46fa ("crypto: ccree - avoid out-of-range warnings from clang")

Quoted 5 lines
Quoted 3 lines

Also can be made as

Nooooh... torvalds might click on it, and complain ;-)

See my reply to Yury.

Quoted 8 lines
Quoted 5 lines

include/linux/bitfield.h line 79

Quoted 3 lines
include/linux/bitfield.h +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Ah, this is unfortunate.

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#24 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

Hi Andy,

Quoted 24 lines · Andy Shevchenko
Quoted 23 lines · Geert Uytterhoeven
Quoted 21 lines · Andy Shevchenko
Quoted 19 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

include/linux/bitfield.h +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Ah, this is unfortunate.

Of course, it might be an actual bug in the i915 driver...

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
maintainer Reviewed-by on v6 13/26
#34 lore raw

Re: [PATCH v6 13/26] bitfield: Add non-constant field_{prep,get}() helpers

In reply to Geert Uytterhoeven
Quoted 94 lines · Geert Uytterhoeven

The existing FIELD_{GET,PREP}() macros are limited to compile-time constants. However, it is very common to prepare or extract bitfield elements where the bitfield mask is not a compile-time constant.

To avoid this limitation, the AT91 clock driver and several other drivers already have their own non-const field_{prep,get}() macros. Make them available for general use by adding them to <linux/bitfield.h>, and improve them slightly:
1. Avoid evaluating macro parameters more than once,
2. Replace "ffs() - 1" by "__ffs()",
3. Support 64-bit use on 32-bit architectures,
4. Wire field_{get,prep}() to FIELD_{GET,PREP}() when mask is actually constant.

This is deliberately not merged into the existing FIELD_{GET,PREP}() macros, as people expressed the desire to keep stricter variants for increased safety, or for performance critical paths.

---
v6:
- Align \,
- Add Return sections to kerneldoc,
- Add Reviewed-by,
- Document field_{get,prep} in top comment block,
- Use less-checking __FIELD_{GET,PREP}() to avoid build issues with

    clang and W=1:
    https://lore.kernel.org/all/[email protected]
    https://lore.kernel.org/all/[email protected]
    https://lore.kernel.org/all/[email protected]

v5:
- Add Acked-by,
- Split off changes outside <linux/bitfield.h>,
- Document that mask must be non-zero,
- Document typical usage pattern,
- Recommend using FIELD_{PREP,GET}() directly to ensure compile-time constant masks,
- Check BITS_PER_TYPE(mask) instead of sizeof(mask),
- Wire field_{get,prep}() to FIELD_{GET,PREP}() when mask is constant, to improve type checking.

v4:
- Add Acked-by,
- Rebase on top of commit 7c68005a46108ffa ("crypto: qat - relocate power management debugfs helper APIs") in v6.17-rc1,
- Convert more recently introduced upstream copies:
- drivers/edac/ie31200_edac.c
- drivers/iio/dac/ad3530r.c

v3:
- Add Acked-by,
- Drop underscores from macro parameters,
- Use __auto_type where possible,
- Correctly cast reg to the mask type,
- Introduces __val and __reg intermediates to simplify the actual operation,
- Drop unneeded parentheses,
- Clarify having both FIELD_{GET,PREP}() and field_{get,prep}(),

v2:
- Cast val resp. reg to the mask type,
- Fix 64-bit use on 32-bit architectures,
- Convert new upstream users:
- drivers/crypto/intel/qat/qat_common/adf_gen4_pm_debugfs.c
- drivers/gpio/gpio-aspeed.c
- drivers/iio/temperature/mlx90614.c
- drivers/pinctrl/nuvoton/pinctrl-ma35.c
- sound/usb/mixer_quirks.c
- Convert new user queued in renesas-devel for v6.15:
- drivers/soc/renesas/rz-sysc.c

---
 include/linux/bitfield.h | 59 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 59 insertions(+)
include/linux/bitfield.h +1 -0
index bf8e0ae4b5b41038..f92e18c9629a59c6 100644
@@ -17,6 +17,7 @@
  * FIELD_{GET,PREP} macros take as first parameter shifted mask
  * from which they extract the base mask and shift amount.
  * Mask must be a compilation time constant.
+ * field_{get,prep} are variants that take a non-const mask.
  *
  * Example:
  *

include/linux/bitfield.h __MAKE_OP(64) · line 247

Quoted 7 lines
include/linux/bitfield.h +4 -0
@@ -240,4 +241,62 @@ __MAKE_OP(64)
 #undef __MAKE_OP
 #undef ____MAKE_OP
 
+#define __field_prep(mask, val)						\
+	({								\
+		__auto_type __mask = (mask);				\
+		typeof(mask) __val = (val);				\

typeof(__mask), I guess.

include/linux/bitfield.h __MAKE_OP(64) · line 248

Quoted 1 line
include/linux/bitfield.h +1 -0
+		unsigned int __shift = BITS_PER_TYPE(mask) <= 32 ?	\

Same here: BITS_PER_TYPE(__mask). BITS_PER_TYPE() doesn't evaluate the expression because it is based on sizeof(). But we definitely don't want people check it every time they read the code.

No need to send another version for this. I can fix it inplace.

Quoted 56 lines
include/linux/bitfield.h +53 -0
+				       __ffs(__mask) : __ffs64(__mask);	\
+		(__val << __shift) & __mask;				\
+	})
+
+#define __field_get(mask, reg)						\
+	({								\
+		__auto_type __mask = (mask);				\
+		typeof(mask) __reg =  (reg);				\
+		unsigned int __shift = BITS_PER_TYPE(mask) <= 32 ?	\
+				       __ffs(__mask) : __ffs64(__mask);	\
+		(__reg & __mask) >> __shift;				\
+	})
+
+/**
+ * field_prep() - prepare a bitfield element
+ * @mask: shifted mask defining the field's length and position, must be
+ *        non-zero
+ * @val:  value to put in the field
+ *
+ * Return: field value masked and shifted to its final destination
+ *
+ * field_prep() masks and shifts up the value.  The result should be
+ * combined with other fields of the bitfield using logical OR.
+ * Unlike FIELD_PREP(), @mask is not limited to a compile-time constant.
+ * Typical usage patterns are a value stored in a table, or calculated by
+ * shifting a constant by a variable number of bits.
+ * If you want to ensure that @mask is a compile-time constant, please use
+ * FIELD_PREP() directly instead.
+ */
+#define field_prep(mask, val)						\
+	(__builtin_constant_p(mask) ? __FIELD_PREP(mask, val, "field_prep: ") \
+				    : __field_prep(mask, val))
+
+/**
+ * field_get() - extract a bitfield element
+ * @mask: shifted mask defining the field's length and position, must be
+ *        non-zero
+ * @reg:  value of entire bitfield
+ *
+ * Return: extracted field value
+ *
+ * field_get() extracts the field specified by @mask from the
+ * bitfield passed in as @reg by masking and shifting it down.
+ * Unlike FIELD_GET(), @mask is not limited to a compile-time constant.
+ * Typical usage patterns are a value stored in a table, or calculated by
+ * shifting a constant by a variable number of bits.
+ * If you want to ensure that @mask is a compile-time constant, please use
+ * FIELD_GET() directly instead.
+ */
+#define field_get(mask, reg)						\
+	(__builtin_constant_p(mask) ? __FIELD_GET(mask, reg, "field_get: ") \
+				    : __field_get(mask, reg))
+
 #endif
Signature · 1 line
2.43.0
maintainer
#55 lore raw
In reply to Geert Uytterhoeven
Quoted 28 lines · Geert Uytterhoeven

Hi all,

<linux/bitfield.h> contains various helpers for accessing bitfields, as typically used in hardware registers for memory-mapped I/O blocks. These helpers ensure type safety, and deduce automatically shift values from mask values, avoiding mistakes due to inconsistent shifts and masks, and leading to a reduction in source code size.

The existing FIELD_{GET,PREP}() macros are limited to compile-time constants. However, it is very common to prepare or extract bitfield elements where the bitfield mask is not a compile-time constant (e.g. it comes from a table, or is created by shifting a compile-time constant). To avoid this limitation, the AT91 clock driver introduced its own field_{prep,get}() macros. During the past four years, these have been copied to multiple drivers, and more copies are on their way[1], leading to the obvious review comment "please move this to <linux/bitfield.h>".

Hence this series
1. Takes preparatory steps in drivers definining local

     field_{get,prep}() macros (patches 1-11),
  2. Introduces __FIELD_{PREP,GET}() helpers to avoid clang W=1 warnings
     (patch 12),
  3. Makes field_{prep,get}() available for general use (patch 13),
  4. Converts drivers with local variants to the common helpers (patches
     14-24),
  5. Converts a few Renesas drivers to the existing FIELD_{GET,PREP}()
     and the new field_{get,prep}() helpers (patches 25-26).
Quoted 6 lines

Alternatives would be to use the typed {u*,be*,le*,...}_{get,encode}_bits() macros instead (which currently do not work with non-constant masks either, and the first attempt to change that generates much worse code), or to store the low bit and width of the mask instead (which would require changing all code that passes masks directly, and also generates worse code).

Everyone please send your tags. I'm going to merge it in bitmap-for-next before Monday.

Thanks,
Yury

#25 lore raw

RE: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Geert Uytterhoeven
Quoted 43 lines · Geert Uytterhoeven

Hi Andy,

Quoted 24 lines · Andy Shevchenko
Quoted 23 lines · Geert Uytterhoeven
Quoted 21 lines · Andy Shevchenko
Quoted 19 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

include/linux/bitfield.h +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Ah, this is unfortunate.

Of course, it might be an actual bug in the i915 driver...

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

Ping-Ke

#26 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

Quoted 56 lines · Ping-Ke Shih
Quoted 41 lines · Geert Uytterhoeven
Quoted 24 lines · Andy Shevchenko
Quoted 23 lines · Geert Uytterhoeven
Quoted 21 lines · Andy Shevchenko
Quoted 19 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

include/linux/bitfield.h +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Ah, this is unfortunate.

Of course, it might be an actual bug in the i915 driver...

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

Quoted 6 lines
   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

Isn't FIELD_MODIFY() what you want to use?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#28 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Ping-Ke Shih

Hi Ping-Ke,

Quoted 15 lines · Ping-Ke Shih
Quoted 6 lines · Geert Uytterhoeven

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

Quoted 8 lines

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);

Thanks for your quick confirmation!
So the intention really is to clear bits 22-31, and write the rx_fltr value to bits 0-15?

if the clearing is not needed, it would be better to use #define B_AX_RX_FLTR_CFG_MASK GENMASK(15, 0)

If the clearing is needed, I still think it would be better to change B_AX_RX_FLTR_CFG_MASK, and split the clearing off in a separate operation, to make it more explicit and obvious for the casual reader.

Quoted 2 lines

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

I still have "[PATCH/RFC 17/17] rtw89: Use bitfield helpers"
https://lore.kernel.org/all/f7b81122f7596fa004188bfae68f25a68c2d2392.1637592133.git.geert+renesas@glider.be/
in my local tree, which started flagging the use of a discontiguous mask with the improved checking in field_prep().

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
#29 lore raw

RE: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

Quoted 27 lines · Geert Uytterhoeven

Hi Ping-Ke,

Quoted 15 lines · Ping-Ke Shih
Quoted 6 lines · Geert Uytterhoeven

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

Quoted 8 lines

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);
Quoted 6 lines

Thanks for your quick confirmation!
So the intention really is to clear bits 22-31, and write the rx_fltr value to bits 0-15?

if the clearing is not needed, it would be better to use #define B_AX_RX_FLTR_CFG_MASK GENMASK(15, 0)

But it should be
#define B_AX_RX_FLTR_CFG_MASK (GENMASK(31, 22) | GENMASK(15, 0))

Originally (with bug) we just backup rx_fltr and write whole 32-bits back, but it's incorrect to modify GENMASK(21, 16) which is written by another code.

One way is to implement a special function to replace
rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Such as
rtw89_write_rx_flter(rtwdev, rtwdev->hal.rx_fltr)

  {
    orig = read(reg);
    new = (orig & ~mask) | (data & mask);
    write(new);

}

Another way is that I add value of B_AX_RX_MPDU_MAX_LEN_MASK into rtwdev->hal.rx_fltr. Then, just write whole 32-bit, no need mask.

Quoted 5 lines

If the clearing is needed, I still think it would be better to change B_AX_RX_FLTR_CFG_MASK, and split the clearing off in a separate operation, to make it more explicit and obvious for the casual reader.

Quoted 8 lines
Quoted 2 lines

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

I still have "[PATCH/RFC 17/17] rtw89: Use bitfield helpers"
https://lore.kernel.org/all/f7b81122f7596fa004188bfae68f25a68c2d2392.1637592133.git.geert+renesas@glid
er.be/
in my local tree, which started flagging the use of a discontiguous mask with the improved checking in field_prep().

Got it. You are doing "Non-const bitfield helper conversions".

Ping-Ke

maintainer
#17 lore raw

Re: [PATCH -next v6 10/26] iio: imu: smi330: #undef field_{get,prep}() before definition

In reply to Geert Uytterhoeven
Quoted 7 lines · On Thu, 6 Nov 2025 14:33:58 +0100 Geert Uytterhoeven…

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

I tweaked the original driver to avoid the naming clash so this can be dropped and we can replace with the new function next cycle.

Thanks,

Jonathan

Quoted 24 lines

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/imu/smi330/smi330_core.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/iio/imu/smi330/smi330_core.c +2 -0
index d9178725ade3da83..a79964fe68fadf47 100644
@@ -68,7 +68,9 @@
 #define SMI330_SOFT_RESET_DELAY 2000
 
 /* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
+#undef field_get
 #define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
+#undef field_prep
 #define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
 
 #define SMI330_ACCEL_CHANNEL(_axis) {					\
maintainer Acked-by on v6 5/26
#9 lore raw

Re: [PATCH v6 05/26] iio: dac: ad3530r: #undef field_prep() before local definition

In reply to Geert Uytterhoeven
Quoted 7 lines · On Thu, 6 Nov 2025 14:33:53 +0100 Geert Uytterhoeven…

Prepare for the advent of a globally available common field_prep() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

Quoted 22 lines

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/dac/ad3530r.c | 1 +
 1 file changed, 1 insertion(+)
drivers/iio/dac/ad3530r.c +1 -0
index 6134613777b8e1d4..5684d11137f29948 100644
@@ -54,6 +54,7 @@
 #define AD3531R_MAX_CHANNELS			4
 
 /* Non-constant mask variant of FIELD_PREP() */
+#undef field_prep
 #define field_prep(_mask, _val)	(((_val) << (ffs(_mask) - 1)) & (_mask))
 
 enum ad3530r_mode {
maintainer Acked-by on v6 6/26
#11 lore raw

Re: [PATCH v6 06/26] iio: mlx90614: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven
Quoted 7 lines · On Thu, 6 Nov 2025 14:33:54 +0100 Geert Uytterhoeven…

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

maintainer
#49 lore raw

Re: [PATCH -next v6 23/26] iio: imu: smi330: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven
Quoted 4 lines · On Thu, 6 Nov 2025 14:34:11 +0100 Geert Uytterhoeven…

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

This will need a revist next cycle. I preferred not to have
the odd looking undef in the driver at introduction so prefixed with smi330_ instead. Only one instance so it wasn't worth comments to make ti clear what was going on.

J

Quoted 27 lines

---
v6:
- No changes,

v5:
- New.

---
 drivers/iio/imu/smi330/smi330_core.c | 6 ------
 1 file changed, 6 deletions(-)
drivers/iio/imu/smi330/smi330_core.c +0 -6
index a79964fe68fadf47..83e0dff5d973d046 100644
@@ -67,12 +67,6 @@
 #define SMI330_CHIP_ID 0x42
 #define SMI330_SOFT_RESET_DELAY 2000
 
-/* Non-constant mask variant of FIELD_GET() and FIELD_PREP() */
-#undef field_get
-#define field_get(_mask, _reg) (((_reg) & (_mask)) >> (ffs(_mask) - 1))
-#undef field_prep
-#define field_prep(_mask, _val) (((_val) << (ffs(_mask) - 1)) & (_mask))
-
 #define SMI330_ACCEL_CHANNEL(_axis) {					\
 	.type = IIO_ACCEL,						\
 	.modified = 1,							\
#30 lore raw

RE: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Geert Uytterhoeven

Hi Geert,

Quoted 46 lines · Ping-Ke Shih
Quoted 27 lines · Geert Uytterhoeven

Hi Ping-Ke,

Quoted 15 lines · Ping-Ke Shih
Quoted 6 lines · Geert Uytterhoeven

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

Quoted 8 lines

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);
Quoted 6 lines

Thanks for your quick confirmation!
So the intention really is to clear bits 22-31, and write the rx_fltr value to bits 0-15?

if the clearing is not needed, it would be better to use #define B_AX_RX_FLTR_CFG_MASK GENMASK(15, 0)

But it should be
#define B_AX_RX_FLTR_CFG_MASK (GENMASK(31, 22) | GENMASK(15, 0))

Originally (with bug) we just backup rx_fltr and write whole 32-bits back, but it's incorrect to modify GENMASK(21, 16) which is written by another code.

One way is to implement a special function to replace
rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Such as
rtw89_write_rx_flter(rtwdev, rtwdev->hal.rx_fltr)

Quoted 13 lines
  {
    orig = read(reg);
    new = (orig & ~mask) | (data & mask);
    write(new);

}

Another way is that I add value of B_AX_RX_MPDU_MAX_LEN_MASK into rtwdev->hal.rx_fltr. Then, just write whole 32-bit, no need mask.

Quoted 4 lines

If the clearing is needed, I still think it would be better to change B_AX_RX_FLTR_CFG_MASK, and split the clearing off in a separate operation, to make it more explicit and obvious for the casual reader.

I missed this paragraph last week, but that is like my thought. Then I spin a RFT [1]. Please try if it can work with your changes.

[1] https://lore.kernel.org/linux-wireless/[email protected]/T/#u

Quoted 14 lines
Quoted 6 lines
Quoted 3 lines

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

I still have "[PATCH/RFC 17/17] rtw89: Use bitfield helpers"

https://lore.kernel.org/all/f7b81122f7596fa004188bfae68f25a68c2d2392.1637592133.git.geert+renesas@glid

Quoted 3 lines

er.be/
in my local tree, which started flagging the use of a discontiguous mask with the improved checking in field_prep().

Got it. You are doing "Non-const bitfield helper conversions".

Ping-Ke

#27 lore raw

Re: [PATCH v6 12/26] bitfield: Add less-checking __FIELD_{GET,PREP}()

In reply to Andy Shevchenko

Hi Ady,

Quoted 56 lines · Andy Shevchenko
Quoted 55 lines · Ping-Ke Shih
Quoted 41 lines · Geert Uytterhoeven
Quoted 24 lines · Andy Shevchenko
Quoted 23 lines · Geert Uytterhoeven
Quoted 21 lines · Andy Shevchenko
Quoted 19 lines · Geert Uytterhoeven

The BUILD_BUG_ON_MSG() check against "~0ull" works only with "unsigned (long) long" _mask types. For constant masks, that condition is usually met, as GENMASK() yields an UL value. The few places where the constant mask is stored in an intermediate variable were fixed by changing the variable type to u64 (see e.g. [1] and [2]).

However, for non-constant masks, smaller unsigned types should be valid, too, but currently lead to "result of comparison of constant 18446744073709551615 with expression of type ... is always false"-warnings with clang and W=1.

Hence refactor the __BF_FIELD_CHECK() helper, and factor out __FIELD_{GET,PREP}(). The later lack the single problematic check, but are otherwise identical to FIELD_{GET,PREP}(), and are intended to be used in the fully non-const variants later.

(quoted diff) +3 -0
+     BUILD_BUG_ON_MSG(__bf_cast_unsigned(mask, mask) >               \
+                      __bf_cast_unsigned(reg, ~0ull),                \
+                      pfx "type of reg too small for mask")
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Perhaps we may convert this (and others?) to static_assert():s at some point?

Nick tried that before, without success:
https://lore.kernel.org/all/CAKwvOdm_prtk1UQNJQGidZm44Lk582S3p=of0y46+rVjnSgXJg@mail.gmail.com

Ah, this is unfortunate.

Of course, it might be an actual bug in the i915 driver...

The extra checking in field_prep() in case the compiler can determine that the mask is a constant already found a possible bug in drivers/net/wireless/realtek/rtw89/core.c:rtw89_roc_end():

    rtw89_write32_mask(rtwdev, reg, B_AX_RX_FLTR_CFG_MASK, rtwdev->hal.rx_fltr);
Quoted 7 lines

drivers/net/wireless/realtek/rtw89/reg.h:

    #define B_AX_RX_MPDU_MAX_LEN_MASK GENMASK(21, 16)
    #define B_AX_RX_FLTR_CFG_MASK ((u32)~B_AX_RX_MPDU_MAX_LEN_MASK)

so it looks like B_AX_RX_FLTR_CFG_MASK is not the proper mask for this operation...

The purpose of the statements is to update values excluding bits of B_AX_RX_MPDU_MAX_LEN_MASK. The use of B_AX_RX_FLTR_CFG_MASK is tricky, but the operation is correct because bit 0 is set, so __ffs(mask) returns 0 in rtw89_write32_mask(). Then, operation looks like

Quoted 8 lines
Quoted 6 lines
   orig = read(reg);
   new = (orig & ~mask) | (data & mask);
   write(new);

Since we don't use FIELD_{GET,PREP} macros with B_AX_RX_FLTR_CFG_MASK, how can you find the problem? Please guide us. Thanks.

Isn't FIELD_MODIFY() what you want to use?

FIELD_MODIFY() is a rather recent addition.
That is also the reason why I didn't add a non-const field_modify() yet (I didn't want to risk delaying this series even more ;-)

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
Reviewed-by on v6 3/26
#6 lore raw

RE: [PATCH v6 03/26] EDAC/ie31200: #undef field_get() before local definition

In reply to Geert Uytterhoeven
Quoted 39 lines

From: Geert Uytterhoeven <[email protected]>
Sent: Thursday, November 6, 2025 9:34 PM
To: Yury Norov <[email protected]>; Michael Turquette <[email protected]>; Stephen Boyd <[email protected]>; Nicolas Ferre <[email protected]>; Alexandre Belloni <[email protected]>; Claudiu Beznea <[email protected]>; Cabiddu, Giovanni <[email protected]>; Herbert Xu <[email protected]>; David Miller <[email protected]>; Linus Walleij <[email protected]>; Bartosz Golaszewski <[email protected]>; Joel Stanley <[email protected]>; Andrew Jeffery <[email protected]>; Crt Mori <[email protected]>; Jonathan Cameron <[email protected]>; Lars- Peter Clausen <[email protected]>; Jacky Huang <[email protected]>; Shan-Chun Hung <[email protected]>; Rasmus Villemoes <[email protected]>; Jaroslav Kysela <[email protected]>; Takashi Iwai <[email protected]>; Johannes Berg <[email protected]>; Jakub Kicinski <[email protected]>; Alex Elder <[email protected]>; David Laight <[email protected]>; Vincent Mailhol <[email protected]>; Jason Baron <[email protected]>; Borislav Petkov <[email protected]>; Luck, Tony <[email protected]>; Michael Hennerich <[email protected]>; Kim Seer Paller <[email protected]>; Lechner, David <[email protected]>; Nuno Sá <[email protected]>; Andy Shevchenko <[email protected]>; Richard Genoud <[email protected]>; Cosmin Tanislav <[email protected]>; Biju Das <[email protected]>; Jianping Shen <[email protected]>; Nathan Chancellor <[email protected]>; Nick Desaulniers <[email protected]>; Miquel Raynal <[email protected]>; Richard Weinberger <[email protected]>; Vignesh Raghavendra <[email protected]>
Cc: [email protected]; [email protected]; linux- [email protected]; [email protected]; linux- [email protected]; qat-linux <[email protected]>; linux- [email protected]; [email protected]; linux- [email protected]; [email protected]; linux- [email protected]; [email protected]; Geert Uytterhoeven <[email protected]>
Subject: [PATCH v6 03/26] EDAC/ie31200: #undef field_get() before local definition

Quoted 7 lines

Prepare for the advent of a globally available common field_get() macro by undefining the symbol before defining a local variant. This prevents redefinition warnings from the C preprocessor when introducing the common macro later.

Good to see the global field_{get,prep}() macros are available for use. Thanks.

Quoted 1 line

[...]

Reviewed-by on v6 16/26
#40 lore raw

RE: [PATCH v6 16/26] EDAC/ie31200: Convert to common field_get() helper

In reply to Geert Uytterhoeven
Quoted 39 lines

From: Geert Uytterhoeven <[email protected]>
Sent: Thursday, November 6, 2025 9:34 PM
To: Yury Norov <[email protected]>; Michael Turquette <[email protected]>; Stephen Boyd <[email protected]>; Nicolas Ferre <[email protected]>; Alexandre Belloni <[email protected]>; Claudiu Beznea <[email protected]>; Cabiddu, Giovanni <[email protected]>; Herbert Xu <[email protected]>; David Miller <[email protected]>; Linus Walleij <[email protected]>; Bartosz Golaszewski <[email protected]>; Joel Stanley <[email protected]>; Andrew Jeffery <[email protected]>; Crt Mori <[email protected]>; Jonathan Cameron <[email protected]>; Lars- Peter Clausen <[email protected]>; Jacky Huang <[email protected]>; Shan-Chun Hung <[email protected]>; Rasmus Villemoes <[email protected]>; Jaroslav Kysela <[email protected]>; Takashi Iwai <[email protected]>; Johannes Berg <[email protected]>; Jakub Kicinski <[email protected]>; Alex Elder <[email protected]>; David Laight <[email protected]>; Vincent Mailhol <[email protected]>; Jason Baron <[email protected]>; Borislav Petkov <[email protected]>; Luck, Tony <[email protected]>; Michael Hennerich <[email protected]>; Kim Seer Paller <[email protected]>; Lechner, David <[email protected]>; Nuno Sá <[email protected]>; Andy Shevchenko <[email protected]>; Richard Genoud <[email protected]>; Cosmin Tanislav <[email protected]>; Biju Das <[email protected]>; Jianping Shen <[email protected]>; Nathan Chancellor <[email protected]>; Nick Desaulniers <[email protected]>; Miquel Raynal <[email protected]>; Richard Weinberger <[email protected]>; Vignesh Raghavendra <[email protected]>
Cc: [email protected]; [email protected]; linux- [email protected]; [email protected]; linux- [email protected]; qat-linux <[email protected]>; linux- [email protected]; [email protected]; linux- [email protected]; [email protected]; linux- [email protected]; [email protected]; Geert Uytterhoeven <[email protected]>
Subject: [PATCH v6 16/26] EDAC/ie31200: Convert to common field_get() helper

Quoted 4 lines

Drop the driver-specific field_get() macro, in favor of the globally available variant from <linux/bitfield.h>.

Good to see the global field_{get,prep}() macros are available for use. Thanks.

Quoted 1 line

[...]

maintainer Acked-by on v6 14/26
#37 lore raw

Re: [PATCH v6 14/26] clk: at91: Convert to common field_{get,prep}() helpers

In reply to Geert Uytterhoeven

Quoting Geert Uytterhoeven (2025-11-06 05:34:02)

Quoted 6 lines

Drop the driver-specific field_get() and field_prep() macros, in favor of the globally available variants from <linux/bitfield.h>.

---

maintainer Acked-by on v6 1/26
#3 lore raw

Re: [PATCH v6 01/26] clk: at91: pmc: #undef field_{get,prep}() before definition

In reply to Geert Uytterhoeven

Quoting Geert Uytterhoeven (2025-11-06 05:33:49)

Quoted 9 lines

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---

maintainer
#56 lore raw
In reply to Yury Norov
Quoted 36 lines · Yury Norov
Quoted 28 lines · Geert Uytterhoeven

Hi all,

<linux/bitfield.h> contains various helpers for accessing bitfields, as typically used in hardware registers for memory-mapped I/O blocks. These helpers ensure type safety, and deduce automatically shift values from mask values, avoiding mistakes due to inconsistent shifts and masks, and leading to a reduction in source code size.

The existing FIELD_{GET,PREP}() macros are limited to compile-time constants. However, it is very common to prepare or extract bitfield elements where the bitfield mask is not a compile-time constant (e.g. it comes from a table, or is created by shifting a compile-time constant). To avoid this limitation, the AT91 clock driver introduced its own field_{prep,get}() macros. During the past four years, these have been copied to multiple drivers, and more copies are on their way[1], leading to the obvious review comment "please move this to <linux/bitfield.h>".

Hence this series
1. Takes preparatory steps in drivers definining local

     field_{get,prep}() macros (patches 1-11),
  2. Introduces __FIELD_{PREP,GET}() helpers to avoid clang W=1 warnings
     (patch 12),
  3. Makes field_{prep,get}() available for general use (patch 13),
  4. Converts drivers with local variants to the common helpers (patches
     14-24),
  5. Converts a few Renesas drivers to the existing FIELD_{GET,PREP}()
     and the new field_{get,prep}() helpers (patches 25-26).
Quoted 6 lines

Alternatives would be to use the typed {u*,be*,le*,...}_{get,encode}_bits() macros instead (which currently do not work with non-constant masks either, and the first attempt to change that generates much worse code), or to store the low bit and width of the mask instead (which would require changing all code that passes masks directly, and also generates worse code).

Quoted 2 lines

Everyone please send your tags. I'm going to merge it in bitmap-for-next before Monday.

Fortunately I didn't specify the exact Monday. :)

Now it's in my tree for local testing:

https://github.com/norov/linux/tree/field-prep-for-6.19

Will move in bitmap-for-next shortly.

Thanks,
Yury

maintainer
#19 lore raw

Re: [PATCH -next v6 11/26] mtd: rawnand: sunxi: #undef field_{get,prep}() before local definition

In reply to Geert Uytterhoeven

Hello,

Quoted 8 lines · Geert Uytterhoeven

Prepare for the advent of globally available common field_get() and field_prep() macros by undefining the symbols before defining local variants. This prevents redefinition warnings from the C preprocessor when introducing the common macros later.

---

Finally applied to nand/next, will be part of the next merge window.

Thanks,
Miquèl