util.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
  3. * Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2
  7. * as published by the Free Software Foundation
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #ifndef __MT76_UTIL_H
  15. #define __MT76_UTIL_H
  16. /*
  17. * Power of two check, this will check
  18. * if the mask that has been given contains and contiguous set of bits.
  19. * Note that we cannot use the is_power_of_2() function since this
  20. * check must be done at compile-time.
  21. */
  22. #define is_power_of_two(x) ( !((x) & ((x)-1)) )
  23. #define low_bit_mask(x) ( ((x)-1) & ~(x) )
  24. #define is_valid_mask(x) is_power_of_two(1LU + (x) + low_bit_mask(x))
  25. /*
  26. * Macros to find first set bit in a variable.
  27. * These macros behave the same as the __ffs() functions but
  28. * the most important difference that this is done during
  29. * compile-time rather then run-time.
  30. */
  31. #define compile_ffs2(__x) \
  32. __builtin_choose_expr(((__x) & 0x1), 0, 1)
  33. #define compile_ffs4(__x) \
  34. __builtin_choose_expr(((__x) & 0x3), \
  35. (compile_ffs2((__x))), \
  36. (compile_ffs2((__x) >> 2) + 2))
  37. #define compile_ffs8(__x) \
  38. __builtin_choose_expr(((__x) & 0xf), \
  39. (compile_ffs4((__x))), \
  40. (compile_ffs4((__x) >> 4) + 4))
  41. #define compile_ffs16(__x) \
  42. __builtin_choose_expr(((__x) & 0xff), \
  43. (compile_ffs8((__x))), \
  44. (compile_ffs8((__x) >> 8) + 8))
  45. #define compile_ffs32(__x) \
  46. __builtin_choose_expr(((__x) & 0xffff), \
  47. (compile_ffs16((__x))), \
  48. (compile_ffs16((__x) >> 16) + 16))
  49. /*
  50. * This macro will check the requirements for the FIELD{8,16,32} macros
  51. * The mask should be a constant non-zero contiguous set of bits which
  52. * does not exceed the given typelimit.
  53. */
  54. #define FIELD_CHECK(__mask) \
  55. BUILD_BUG_ON(!(__mask) || !is_valid_mask(__mask))
  56. #define MT76_SET(_mask, _val) \
  57. ({ \
  58. FIELD_CHECK(_mask); \
  59. (((u32) (_val)) << compile_ffs32(_mask)) & _mask; \
  60. })
  61. #define MT76_GET(_mask, _val) \
  62. ({ \
  63. FIELD_CHECK(_mask); \
  64. (u32) (((_val) & _mask) >> compile_ffs32(_mask)); \
  65. })
  66. #endif