bitops.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef _TOOLS_LINUX_BITOPS_H_
  3. #define _TOOLS_LINUX_BITOPS_H_
  4. #include <asm/types.h>
  5. #ifndef __WORDSIZE
  6. #define __WORDSIZE (__SIZEOF_LONG__ * 8)
  7. #endif
  8. #ifndef BITS_PER_LONG
  9. # define BITS_PER_LONG __WORDSIZE
  10. #endif
  11. #include <linux/bits.h>
  12. #include <linux/compiler.h>
  13. #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
  14. #define BITS_TO_U64(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(u64))
  15. #define BITS_TO_U32(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(u32))
  16. #define BITS_TO_BYTES(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE)
  17. extern unsigned int __sw_hweight8(unsigned int w);
  18. extern unsigned int __sw_hweight16(unsigned int w);
  19. extern unsigned int __sw_hweight32(unsigned int w);
  20. extern unsigned long __sw_hweight64(__u64 w);
  21. /*
  22. * Include this here because some architectures need generic_ffs/fls in
  23. * scope
  24. *
  25. * XXX: this needs to be asm/bitops.h, when we get to per arch optimizations
  26. */
  27. #include <asm-generic/bitops.h>
  28. #define for_each_set_bit(bit, addr, size) \
  29. for ((bit) = find_first_bit((addr), (size)); \
  30. (bit) < (size); \
  31. (bit) = find_next_bit((addr), (size), (bit) + 1))
  32. #define for_each_clear_bit(bit, addr, size) \
  33. for ((bit) = find_first_zero_bit((addr), (size)); \
  34. (bit) < (size); \
  35. (bit) = find_next_zero_bit((addr), (size), (bit) + 1))
  36. /* same as for_each_set_bit() but use bit as value to start with */
  37. #define for_each_set_bit_from(bit, addr, size) \
  38. for ((bit) = find_next_bit((addr), (size), (bit)); \
  39. (bit) < (size); \
  40. (bit) = find_next_bit((addr), (size), (bit) + 1))
  41. static inline unsigned long hweight_long(unsigned long w)
  42. {
  43. return sizeof(w) == 4 ? hweight32(w) : hweight64(w);
  44. }
  45. static inline unsigned fls_long(unsigned long l)
  46. {
  47. if (sizeof(l) == 4)
  48. return fls(l);
  49. return fls64(l);
  50. }
  51. /**
  52. * rol32 - rotate a 32-bit value left
  53. * @word: value to rotate
  54. * @shift: bits to roll
  55. */
  56. static inline __u32 rol32(__u32 word, unsigned int shift)
  57. {
  58. return (word << shift) | (word >> ((-shift) & 31));
  59. }
  60. #endif