ratelimit.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. printk(KERN_WARNING "%s: %d callbacks suppressed\n",
  45. func, rs->missed);
  46. rs->begin = 0;
  47. rs->printed = 0;
  48. rs->missed = 0;
  49. }
  50. if (rs->burst && rs->burst > rs->printed) {
  51. rs->printed++;
  52. ret = 1;
  53. } else {
  54. rs->missed++;
  55. ret = 0;
  56. }
  57. raw_spin_unlock_irqrestore(&rs->lock, flags);
  58. return ret;
  59. }
  60. EXPORT_SYMBOL(___ratelimit);