blob: 09f5ce1810dcc02ddb99696d255ed3ad6436f30b [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
Ingo Molnar3fff4c42009-09-22 16:18:09 +020012#include <linux/ratelimit.h>
Dave Young5f97a5a2008-04-29 00:59:43 -070013#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 */
Christian Borntraeger5c828712009-10-23 14:58:11 +020023int ___ratelimit(struct ratelimit_state *rs, const char *func)
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 Molnaredaac8e2009-09-22 14:44:11 +020031 /*
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 (!spin_trylock_irqsave(&rs->lock, flags))
38 return 1;
39
Dave Young717115e2008-07-25 01:45:58 -070040 if (!rs->begin)
41 rs->begin = jiffies;
Dave Young5f97a5a2008-04-29 00:59:43 -070042
Dave Young717115e2008-07-25 01:45:58 -070043 if (time_is_before_jiffies(rs->begin + rs->interval)) {
44 if (rs->missed)
45 printk(KERN_WARNING "%s: %d callbacks suppressed\n",
Christian Borntraeger5c828712009-10-23 14:58:11 +020046 func, rs->missed);
Ingo Molnar979f6932009-09-22 14:44:11 +020047 rs->begin = 0;
Dave Young717115e2008-07-25 01:45:58 -070048 rs->printed = 0;
Ingo Molnar979f6932009-09-22 14:44:11 +020049 rs->missed = 0;
Dave Young5f97a5a2008-04-29 00:59:43 -070050 }
Ingo Molnar979f6932009-09-22 14:44:11 +020051 if (rs->burst && rs->burst > rs->printed) {
52 rs->printed++;
53 ret = 1;
54 } else {
55 rs->missed++;
56 ret = 0;
57 }
58 spin_unlock_irqrestore(&rs->lock, flags);
Dave Young717115e2008-07-25 01:45:58 -070059
Ingo Molnar979f6932009-09-22 14:44:11 +020060 return ret;
Dave Young5f97a5a2008-04-29 00:59:43 -070061}
Christian Borntraeger5c828712009-10-23 14:58:11 +020062EXPORT_SYMBOL(___ratelimit);