ratelimit.c 1.6 KB

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