5 * Tom Marshall <tommy@home.tig-grr.com>
7 * Mostly copied from netfilter's ipt_limit.c, see that file for
13 #include <linux/module.h>
14 #include <linux/netdevice.h>
15 #include <linux/spinlock.h>
16 #include <linux/netfilter/x_tables.h>
17 #include <linux/netfilter_bridge/ebtables.h>
18 #include <linux/netfilter_bridge/ebt_limit.h>
20 static DEFINE_SPINLOCK(limit_lock
);
22 #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
24 #define _POW2_BELOW2(x) ((x)|((x)>>1))
25 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
26 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
27 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
28 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
29 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
31 #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
34 ebt_limit_mt(const struct sk_buff
*skb
, const struct net_device
*in
,
35 const struct net_device
*out
, const struct xt_match
*match
,
36 const void *data
, int offset
, unsigned int protoff
, bool *hotdrop
)
38 struct ebt_limit_info
*info
= (void *)data
;
39 unsigned long now
= jiffies
;
41 spin_lock_bh(&limit_lock
);
42 info
->credit
+= (now
- xchg(&info
->prev
, now
)) * CREDITS_PER_JIFFY
;
43 if (info
->credit
> info
->credit_cap
)
44 info
->credit
= info
->credit_cap
;
46 if (info
->credit
>= info
->cost
) {
47 /* We're not limited. */
48 info
->credit
-= info
->cost
;
49 spin_unlock_bh(&limit_lock
);
53 spin_unlock_bh(&limit_lock
);
57 /* Precision saver. */
59 user2credits(u_int32_t user
)
61 /* If multiplying would overflow... */
62 if (user
> 0xFFFFFFFF / (HZ
*CREDITS_PER_JIFFY
))
64 return (user
/ EBT_LIMIT_SCALE
) * HZ
* CREDITS_PER_JIFFY
;
66 return (user
* HZ
* CREDITS_PER_JIFFY
) / EBT_LIMIT_SCALE
;
70 ebt_limit_mt_check(const char *table
, const void *e
,
71 const struct xt_match
*match
, void *data
,
72 unsigned int hook_mask
)
74 struct ebt_limit_info
*info
= data
;
76 /* Check for overflow. */
77 if (info
->burst
== 0 ||
78 user2credits(info
->avg
* info
->burst
) < user2credits(info
->avg
)) {
79 printk("Overflow in ebt_limit, try lower: %u/%u\n",
80 info
->avg
, info
->burst
);
84 /* User avg in seconds * EBT_LIMIT_SCALE: convert to jiffies * 128. */
86 info
->credit
= user2credits(info
->avg
* info
->burst
);
87 info
->credit_cap
= user2credits(info
->avg
* info
->burst
);
88 info
->cost
= user2credits(info
->avg
);
92 static struct xt_match ebt_limit_mt_reg __read_mostly
= {
95 .family
= NFPROTO_BRIDGE
,
96 .match
= ebt_limit_mt
,
97 .checkentry
= ebt_limit_mt_check
,
98 .matchsize
= XT_ALIGN(sizeof(struct ebt_limit_info
)),
102 static int __init
ebt_limit_init(void)
104 return xt_register_match(&ebt_limit_mt_reg
);
107 static void __exit
ebt_limit_fini(void)
109 xt_unregister_match(&ebt_limit_mt_reg
);
112 module_init(ebt_limit_init
);
113 module_exit(ebt_limit_fini
);
114 MODULE_DESCRIPTION("Ebtables: Rate-limit match");
115 MODULE_LICENSE("GPL");