Merge tag 'iwlwifi-next-for-kalle-2018-10-12' of git://git.kernel.org/pub/scm/linux...
[linux] / net / netfilter / xt_quota.c
1 /*
2  * netfilter module to enforce network quotas
3  *
4  * Sam Johnston <samj@samj.net>
5  */
6 #include <linux/skbuff.h>
7 #include <linux/slab.h>
8 #include <linux/spinlock.h>
9
10 #include <linux/netfilter/x_tables.h>
11 #include <linux/netfilter/xt_quota.h>
12 #include <linux/module.h>
13
14 MODULE_LICENSE("GPL");
15 MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
16 MODULE_DESCRIPTION("Xtables: countdown quota match");
17 MODULE_ALIAS("ipt_quota");
18 MODULE_ALIAS("ip6t_quota");
19
20 static bool
21 quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
22 {
23         struct xt_quota_info *q = (void *)par->matchinfo;
24         u64 current_count = atomic64_read(&q->counter);
25         bool ret = q->flags & XT_QUOTA_INVERT;
26         u64 old_count, new_count;
27
28         do {
29                 if (current_count == 1)
30                         return ret;
31                 if (current_count <= skb->len) {
32                         atomic64_set(&q->counter, 1);
33                         return ret;
34                 }
35                 old_count = current_count;
36                 new_count = current_count - skb->len;
37                 current_count = atomic64_cmpxchg(&q->counter, old_count,
38                                                  new_count);
39         } while (current_count != old_count);
40         return !ret;
41 }
42
43 static int quota_mt_check(const struct xt_mtchk_param *par)
44 {
45         struct xt_quota_info *q = par->matchinfo;
46
47         BUILD_BUG_ON(sizeof(atomic64_t) != sizeof(__u64));
48
49         if (q->flags & ~XT_QUOTA_MASK)
50                 return -EINVAL;
51         if (atomic64_read(&q->counter) > q->quota + 1)
52                 return -ERANGE;
53
54         if (atomic64_read(&q->counter) == 0)
55                 atomic64_set(&q->counter, q->quota + 1);
56         return 0;
57 }
58
59 static struct xt_match quota_mt_reg __read_mostly = {
60         .name       = "quota",
61         .revision   = 0,
62         .family     = NFPROTO_UNSPEC,
63         .match      = quota_mt,
64         .checkentry = quota_mt_check,
65         .matchsize  = sizeof(struct xt_quota_info),
66         .me         = THIS_MODULE,
67 };
68
69 static int __init quota_mt_init(void)
70 {
71         return xt_register_match(&quota_mt_reg);
72 }
73
74 static void __exit quota_mt_exit(void)
75 {
76         xt_unregister_match(&quota_mt_reg);
77 }
78
79 module_init(quota_mt_init);
80 module_exit(quota_mt_exit);