average.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef _LINUX_AVERAGE_H
  3. #define _LINUX_AVERAGE_H
  4. #include <linux/bug.h>
  5. #include <linux/compiler.h>
  6. #include <linux/log2.h>
  7. /*
  8. * Exponentially weighted moving average (EWMA)
  9. *
  10. * This implements a fixed-precision EWMA algorithm, with both the
  11. * precision and fall-off coefficient determined at compile-time
  12. * and built into the generated helper funtions.
  13. *
  14. * The first argument to the macro is the name that will be used
  15. * for the struct and helper functions.
  16. *
  17. * The second argument, the precision, expresses how many bits are
  18. * used for the fractional part of the fixed-precision values.
  19. *
  20. * The third argument, the weight reciprocal, determines how the
  21. * new values will be weighed vs. the old state, new values will
  22. * get weight 1/weight_rcp and old values 1-1/weight_rcp. Note
  23. * that this parameter must be a power of two for efficiency.
  24. */
  25. #define DECLARE_EWMA(name, _precision, _weight_rcp) \
  26. struct ewma_##name { \
  27. unsigned long internal; \
  28. }; \
  29. static inline void ewma_##name##_init(struct ewma_##name *e) \
  30. { \
  31. BUILD_BUG_ON(!__builtin_constant_p(_precision)); \
  32. BUILD_BUG_ON(!__builtin_constant_p(_weight_rcp)); \
  33. /* \
  34. * Even if you want to feed it just 0/1 you should have \
  35. * some bits for the non-fractional part... \
  36. */ \
  37. BUILD_BUG_ON((_precision) > 30); \
  38. BUILD_BUG_ON_NOT_POWER_OF_2(_weight_rcp); \
  39. e->internal = 0; \
  40. } \
  41. static inline unsigned long \
  42. ewma_##name##_read(struct ewma_##name *e) \
  43. { \
  44. BUILD_BUG_ON(!__builtin_constant_p(_precision)); \
  45. BUILD_BUG_ON(!__builtin_constant_p(_weight_rcp)); \
  46. BUILD_BUG_ON((_precision) > 30); \
  47. BUILD_BUG_ON_NOT_POWER_OF_2(_weight_rcp); \
  48. return e->internal >> (_precision); \
  49. } \
  50. static inline void ewma_##name##_add(struct ewma_##name *e, \
  51. unsigned long val) \
  52. { \
  53. unsigned long internal = READ_ONCE(e->internal); \
  54. unsigned long weight_rcp = ilog2(_weight_rcp); \
  55. unsigned long precision = _precision; \
  56. \
  57. BUILD_BUG_ON(!__builtin_constant_p(_precision)); \
  58. BUILD_BUG_ON(!__builtin_constant_p(_weight_rcp)); \
  59. BUILD_BUG_ON((_precision) > 30); \
  60. BUILD_BUG_ON_NOT_POWER_OF_2(_weight_rcp); \
  61. \
  62. WRITE_ONCE(e->internal, internal ? \
  63. (((internal << weight_rcp) - internal) + \
  64. (val << precision)) >> weight_rcp : \
  65. (val << precision)); \
  66. }
  67. #endif /* _LINUX_AVERAGE_H */