ratelimit.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #ifndef _LINUX_RATELIMIT_H
  2. #define _LINUX_RATELIMIT_H
  3. #include <linux/param.h>
  4. #include <linux/spinlock.h>
  5. #define DEFAULT_RATELIMIT_INTERVAL (5 * HZ)
  6. #define DEFAULT_RATELIMIT_BURST 10
  7. struct ratelimit_state {
  8. raw_spinlock_t lock; /* protect the state */
  9. int interval;
  10. int burst;
  11. int printed;
  12. int missed;
  13. unsigned long begin;
  14. };
  15. #define RATELIMIT_STATE_INIT(name, interval_init, burst_init) { \
  16. .lock = __RAW_SPIN_LOCK_UNLOCKED(name.lock), \
  17. .interval = interval_init, \
  18. .burst = burst_init, \
  19. }
  20. #define RATELIMIT_STATE_INIT_DISABLED \
  21. RATELIMIT_STATE_INIT(ratelimit_state, 0, DEFAULT_RATELIMIT_BURST)
  22. #define DEFINE_RATELIMIT_STATE(name, interval_init, burst_init) \
  23. \
  24. struct ratelimit_state name = \
  25. RATELIMIT_STATE_INIT(name, interval_init, burst_init) \
  26. static inline void ratelimit_state_init(struct ratelimit_state *rs,
  27. int interval, int burst)
  28. {
  29. raw_spin_lock_init(&rs->lock);
  30. rs->interval = interval;
  31. rs->burst = burst;
  32. rs->printed = 0;
  33. rs->missed = 0;
  34. rs->begin = 0;
  35. }
  36. extern struct ratelimit_state printk_ratelimit_state;
  37. extern int ___ratelimit(struct ratelimit_state *rs, const char *func);
  38. #define __ratelimit(state) ___ratelimit(state, __func__)
  39. #ifdef CONFIG_PRINTK
  40. #define WARN_ON_RATELIMIT(condition, state) \
  41. WARN_ON((condition) && __ratelimit(state))
  42. #define WARN_RATELIMIT(condition, format, ...) \
  43. ({ \
  44. static DEFINE_RATELIMIT_STATE(_rs, \
  45. DEFAULT_RATELIMIT_INTERVAL, \
  46. DEFAULT_RATELIMIT_BURST); \
  47. int rtn = !!(condition); \
  48. \
  49. if (unlikely(rtn && __ratelimit(&_rs))) \
  50. WARN(rtn, format, ##__VA_ARGS__); \
  51. \
  52. rtn; \
  53. })
  54. #else
  55. #define WARN_ON_RATELIMIT(condition, state) \
  56. WARN_ON(condition)
  57. #define WARN_RATELIMIT(condition, format, ...) \
  58. ({ \
  59. int rtn = WARN(condition, format, ##__VA_ARGS__); \
  60. rtn; \
  61. })
  62. #endif
  63. #endif /* _LINUX_RATELIMIT_H */