bitfield.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright 2013 Broadcom Corporation.
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. /*
  7. * Bitfield operations
  8. *
  9. * These are generic bitfield operations which allow manipulation of variable
  10. * width bitfields within a word. One use of this would be to use data tables
  11. * to determine how to reprogram fields within R/W hardware registers.
  12. *
  13. * Example:
  14. *
  15. * old_reg_val
  16. * +--------+----+---+--+-----+----------+
  17. * | | | | | old | |
  18. * +--------+----+---+--+-----+----------+
  19. *
  20. * new_reg_val
  21. * +--------+----+---+--+-----+----------+
  22. * | | | | | new | |
  23. * +--------+----+---+--+-----+----------+
  24. *
  25. * mask = bitfield_mask(10, 5);
  26. * old = bitfield_extract(old_reg_val, 10, 5);
  27. * new_reg_val = bitfield_replace(old_reg_val, 10, 5, new);
  28. *
  29. * The numbers 10 and 5 could for example come from data
  30. * tables which describe all bitfields in all registers.
  31. */
  32. #include <linux/types.h>
  33. /* Produces a mask of set bits covering a range of a uint value */
  34. static inline uint bitfield_mask(uint shift, uint width)
  35. {
  36. return ((1 << width) - 1) << shift;
  37. }
  38. /* Extract the value of a bitfield found within a given register value */
  39. static inline uint bitfield_extract(uint reg_val, uint shift, uint width)
  40. {
  41. return (reg_val & bitfield_mask(shift, width)) >> shift;
  42. }
  43. /*
  44. * Replace the value of a bitfield found within a given register value
  45. * Returns the newly modified uint value with the replaced field.
  46. */
  47. static inline uint bitfield_replace(uint reg_val, uint shift, uint width,
  48. uint bitfield_val)
  49. {
  50. uint mask = bitfield_mask(shift, width);
  51. return (reg_val & ~mask) | (bitfield_val << shift);
  52. }