Commit | Line | Data |
---|---|---|
55716d26 | 1 | // SPDX-License-Identifier: GPL-2.0-only |
5f97a5a8 DY |
2 | /* |
3 | * ratelimit.c - Do something with rate limit. | |
4 | * | |
5 | * Isolated from kernel/printk.c by Dave Young <hidave.darkstar@gmail.com> | |
6 | * | |
717115e1 DY |
7 | * 2008-05-01 rewrite the function and use a ratelimit_state data struct as |
8 | * parameter. Now every user can use their own standalone ratelimit_state. | |
5f97a5a8 DY |
9 | */ |
10 | ||
3fff4c42 | 11 | #include <linux/ratelimit.h> |
5f97a5a8 | 12 | #include <linux/jiffies.h> |
8bc3bcc9 | 13 | #include <linux/export.h> |
5f97a5a8 DY |
14 | |
15 | /* | |
16 | * __ratelimit - rate limiting | |
717115e1 | 17 | * @rs: ratelimit_state data |
2a7268ab | 18 | * @func: name of calling function |
5f97a5a8 | 19 | * |
2a7268ab YZ |
20 | * This enforces a rate limit: not more than @rs->burst callbacks |
21 | * in every @rs->interval | |
22 | * | |
23 | * RETURNS: | |
24 | * 0 means callbacks will be suppressed. | |
25 | * 1 means go ahead and do it. | |
5f97a5a8 | 26 | */ |
5c828713 | 27 | int ___ratelimit(struct ratelimit_state *rs, const char *func) |
5f97a5a8 | 28 | { |
6bae8ceb KI |
29 | /* Paired with WRITE_ONCE() in .proc_handler(). |
30 | * Changing two values seperately could be inconsistent | |
31 | * and some message could be lost. (See: net_ratelimit_state). | |
32 | */ | |
33 | int interval = READ_ONCE(rs->interval); | |
34 | int burst = READ_ONCE(rs->burst); | |
4d9c377c | 35 | unsigned long flags; |
979f693d | 36 | int ret; |
4d9c377c | 37 | |
6bae8ceb | 38 | if (!interval) |
717115e1 | 39 | return 1; |
5f97a5a8 | 40 | |
edaac8e3 IM |
41 | /* |
42 | * If we contend on this state's lock then almost | |
43 | * by definition we are too busy to print a message, | |
44 | * in addition to the one that will be printed by | |
45 | * the entity that is holding the lock already: | |
46 | */ | |
07354eb1 | 47 | if (!raw_spin_trylock_irqsave(&rs->lock, flags)) |
57119c34 | 48 | return 0; |
edaac8e3 | 49 | |
717115e1 DY |
50 | if (!rs->begin) |
51 | rs->begin = jiffies; | |
5f97a5a8 | 52 | |
6bae8ceb | 53 | if (time_is_before_jiffies(rs->begin + interval)) { |
6b1d174b BP |
54 | if (rs->missed) { |
55 | if (!(rs->flags & RATELIMIT_MSG_ON_RELEASE)) { | |
656d61ce SS |
56 | printk_deferred(KERN_WARNING |
57 | "%s: %d callbacks suppressed\n", | |
58 | func, rs->missed); | |
6b1d174b BP |
59 | rs->missed = 0; |
60 | } | |
61 | } | |
c2594bc3 | 62 | rs->begin = jiffies; |
717115e1 | 63 | rs->printed = 0; |
5f97a5a8 | 64 | } |
6bae8ceb | 65 | if (burst && burst > rs->printed) { |
979f693d IM |
66 | rs->printed++; |
67 | ret = 1; | |
68 | } else { | |
69 | rs->missed++; | |
70 | ret = 0; | |
71 | } | |
07354eb1 | 72 | raw_spin_unlock_irqrestore(&rs->lock, flags); |
717115e1 | 73 | |
979f693d | 74 | return ret; |
5f97a5a8 | 75 | } |
5c828713 | 76 | EXPORT_SYMBOL(___ratelimit); |