blob: 0e2c28e8a0ca979a8cf6e2b48b1a43fbea743393 [file] [log] [blame]
Dave Young5f97a5a2008-04-29 00:59:43 -07001/*
2 * ratelimit.c - Do something with rate limit.
3 *
4 * Isolated from kernel/printk.c by Dave Young <hidave.darkstar@gmail.com>
5 *
Dave Young717115e2008-07-25 01:45:58 -07006 * 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 *
Dave Young5f97a5a2008-04-29 00:59:43 -07009 * This file is released under the GPLv2.
Dave Young5f97a5a2008-04-29 00:59:43 -070010 */
11
12#include <linux/kernel.h>
13#include <linux/jiffies.h>
14#include <linux/module.h>
15
16/*
17 * __ratelimit - rate limiting
Dave Young717115e2008-07-25 01:45:58 -070018 * @rs: ratelimit_state data
Dave Young5f97a5a2008-04-29 00:59:43 -070019 *
Dave Young717115e2008-07-25 01:45:58 -070020 * This enforces a rate limit: not more than @rs->ratelimit_burst callbacks
21 * in every @rs->ratelimit_jiffies
Dave Young5f97a5a2008-04-29 00:59:43 -070022 */
Dave Young717115e2008-07-25 01:45:58 -070023int __ratelimit(struct ratelimit_state *rs)
Dave Young5f97a5a2008-04-29 00:59:43 -070024{
Alexey Dobriyan4d9c3772008-07-28 15:46:21 -070025 unsigned long flags;
Ingo Molnar979f6932009-09-22 14:44:11 +020026 int ret;
Alexey Dobriyan4d9c3772008-07-28 15:46:21 -070027
Dave Young717115e2008-07-25 01:45:58 -070028 if (!rs->interval)
29 return 1;
Dave Young5f97a5a2008-04-29 00:59:43 -070030
Ingo Molnar979f6932009-09-22 14:44:11 +020031 spin_lock_irqsave(&rs->lock, flags);
Dave Young717115e2008-07-25 01:45:58 -070032 if (!rs->begin)
33 rs->begin = jiffies;
Dave Young5f97a5a2008-04-29 00:59:43 -070034
Dave Young717115e2008-07-25 01:45:58 -070035 if (time_is_before_jiffies(rs->begin + rs->interval)) {
36 if (rs->missed)
37 printk(KERN_WARNING "%s: %d callbacks suppressed\n",
38 __func__, rs->missed);
Ingo Molnar979f6932009-09-22 14:44:11 +020039 rs->begin = 0;
Dave Young717115e2008-07-25 01:45:58 -070040 rs->printed = 0;
Ingo Molnar979f6932009-09-22 14:44:11 +020041 rs->missed = 0;
Dave Young5f97a5a2008-04-29 00:59:43 -070042 }
Ingo Molnar979f6932009-09-22 14:44:11 +020043 if (rs->burst && rs->burst > rs->printed) {
44 rs->printed++;
45 ret = 1;
46 } else {
47 rs->missed++;
48 ret = 0;
49 }
50 spin_unlock_irqrestore(&rs->lock, flags);
Dave Young717115e2008-07-25 01:45:58 -070051
Ingo Molnar979f6932009-09-22 14:44:11 +020052 return ret;
Dave Young5f97a5a2008-04-29 00:59:43 -070053}
54EXPORT_SYMBOL(__ratelimit);