ratelimit.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * ratelimit.c - Do something with rate limit.
  4. *
  5. * Isolated from kernel/printk.c by Dave Young <hidave.darkstar@gmail.com>
  6. *
  7. * 2008-05-01 rewrite the function and use a ratelimit_state data struct as
  8. * parameter. Now every user can use their own standalone ratelimit_state.
  9. */
  10. #include <linux/ratelimit.h>
  11. #include <linux/jiffies.h>
  12. #include <linux/export.h>
  13. /*
  14. * __ratelimit - rate limiting
  15. * @rs: ratelimit_state data
  16. * @func: name of calling function
  17. *
  18. * This enforces a rate limit: not more than @rs->burst callbacks
  19. * in every @rs->interval
  20. *
  21. * RETURNS:
  22. * 0 means callbacks will be suppressed.
  23. * 1 means go ahead and do it.
  24. */
  25. int ___ratelimit(struct ratelimit_state *rs, const char *func)
  26. {
  27. unsigned long flags;
  28. int ret;
  29. if (!rs->interval)
  30. return 1;
  31. /*
  32. * If we contend on this state's lock then almost
  33. * by definition we are too busy to print a message,
  34. * in addition to the one that will be printed by
  35. * the entity that is holding the lock already:
  36. */
  37. if (!raw_spin_trylock_irqsave(&rs->lock, flags))
  38. return 0;
  39. if (!rs->begin)
  40. rs->begin = jiffies;
  41. if (time_is_before_jiffies(rs->begin + rs->interval)) {
  42. if (rs->missed) {
  43. if (!(rs->flags & RATELIMIT_MSG_ON_RELEASE)) {
  44. printk_deferred(KERN_WARNING
  45. "%s: %d callbacks suppressed\n",
  46. func, rs->missed);
  47. rs->missed = 0;
  48. }
  49. }
  50. rs->begin = jiffies;
  51. rs->printed = 0;
  52. }
  53. if (rs->burst && rs->burst > rs->printed) {
  54. rs->printed++;
  55. ret = 1;
  56. } else {
  57. rs->missed++;
  58. ret = 0;
  59. }
  60. raw_spin_unlock_irqrestore(&rs->lock, flags);
  61. return ret;
  62. }
  63. EXPORT_SYMBOL(___ratelimit);