200-v6.3-bitfield-add-FIELD_PREP_CONST.patch 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. From e2192de59e457aef8d1f055a452131f0b3e5d097 Mon Sep 17 00:00:00 2001
  2. From: Johannes Berg <[email protected]>
  3. Date: Wed, 18 Jan 2023 14:26:53 +0100
  4. Subject: [PATCH] bitfield: add FIELD_PREP_CONST()
  5. Neither FIELD_PREP() nor *_encode_bits() can be used
  6. in constant contexts (such as initializers), but we
  7. don't want to define shift constants for all masks
  8. just for use in initializers, and having checks that
  9. the values fit is also useful.
  10. Therefore, add FIELD_PREP_CONST() which is a smaller
  11. version of FIELD_PREP() that can only take constant
  12. arguments and has less friendly (but not less strict)
  13. error checks, and expands to a constant value.
  14. Signed-off-by: Johannes Berg <[email protected]>
  15. Link: https://lore.kernel.org/r/20230118142652.53f20593504b.Iaeea0aee77a6493d70e573b4aa55c91c00e01e4b@changeid
  16. Signed-off-by: Johannes Berg <[email protected]>
  17. ---
  18. include/linux/bitfield.h | 26 ++++++++++++++++++++++++++
  19. 1 file changed, 26 insertions(+)
  20. --- a/include/linux/bitfield.h
  21. +++ b/include/linux/bitfield.h
  22. @@ -115,6 +115,32 @@
  23. ((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask); \
  24. })
  25. +#define __BF_CHECK_POW2(n) BUILD_BUG_ON_ZERO(((n) & ((n) - 1)) != 0)
  26. +
  27. +/**
  28. + * FIELD_PREP_CONST() - prepare a constant bitfield element
  29. + * @_mask: shifted mask defining the field's length and position
  30. + * @_val: value to put in the field
  31. + *
  32. + * FIELD_PREP_CONST() masks and shifts up the value. The result should
  33. + * be combined with other fields of the bitfield using logical OR.
  34. + *
  35. + * Unlike FIELD_PREP() this is a constant expression and can therefore
  36. + * be used in initializers. Error checking is less comfortable for this
  37. + * version, and non-constant masks cannot be used.
  38. + */
  39. +#define FIELD_PREP_CONST(_mask, _val) \
  40. + ( \
  41. + /* mask must be non-zero */ \
  42. + BUILD_BUG_ON_ZERO((_mask) == 0) + \
  43. + /* check if value fits */ \
  44. + BUILD_BUG_ON_ZERO(~((_mask) >> __bf_shf(_mask)) & (_val)) + \
  45. + /* check if mask is contiguous */ \
  46. + __BF_CHECK_POW2((_mask) + (1ULL << __bf_shf(_mask))) + \
  47. + /* and create the value */ \
  48. + (((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask)) \
  49. + )
  50. +
  51. /**
  52. * FIELD_GET() - extract a bitfield element
  53. * @_mask: shifted mask defining the field's length and position