ratelimit.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/module.h>
  14. /*
  15. * __ratelimit - rate limiting
  16. * @rs: ratelimit_state data
  17. *
  18. * This enforces a rate limit: not more than @rs->ratelimit_burst callbacks
  19. * in every @rs->ratelimit_jiffies
  20. */
  21. int ___ratelimit(struct ratelimit_state *rs, const char *func)
  22. {
  23. unsigned long flags;
  24. int ret;
  25. if (!rs->interval)
  26. return 1;
  27. /*
  28. * If we contend on this state's lock then almost
  29. * by definition we are too busy to print a message,
  30. * in addition to the one that will be printed by
  31. * the entity that is holding the lock already:
  32. */
  33. if (!spin_trylock_irqsave(&rs->lock, flags))
  34. return 1;
  35. if (!rs->begin)
  36. rs->begin = jiffies;
  37. if (time_is_before_jiffies(rs->begin + rs->interval)) {
  38. if (rs->missed)
  39. printk(KERN_WARNING "%s: %d callbacks suppressed\n",
  40. func, rs->missed);
  41. rs->begin = 0;
  42. rs->printed = 0;
  43. rs->missed = 0;
  44. }
  45. if (rs->burst && rs->burst > rs->printed) {
  46. rs->printed++;
  47. ret = 1;
  48. } else {
  49. rs->missed++;
  50. ret = 0;
  51. }
  52. spin_unlock_irqrestore(&rs->lock, flags);
  53. return ret;
  54. }
  55. EXPORT_SYMBOL(___ratelimit);