Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  *  xt_hashlimit - Netfilter module to limit the number of packets per time
0004  *  separately for each hashbucket (sourceip/sourceport/dstip/dstport)
0005  *
0006  *  (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
0007  *  (C) 2006-2012 Patrick McHardy <kaber@trash.net>
0008  *  Copyright © CC Computer Consultants GmbH, 2007 - 2008
0009  *
0010  * Development of this code was funded by Astaro AG, http://www.astaro.com/
0011  */
0012 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0013 #include <linux/module.h>
0014 #include <linux/spinlock.h>
0015 #include <linux/random.h>
0016 #include <linux/jhash.h>
0017 #include <linux/slab.h>
0018 #include <linux/vmalloc.h>
0019 #include <linux/proc_fs.h>
0020 #include <linux/seq_file.h>
0021 #include <linux/list.h>
0022 #include <linux/skbuff.h>
0023 #include <linux/mm.h>
0024 #include <linux/in.h>
0025 #include <linux/ip.h>
0026 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
0027 #include <linux/ipv6.h>
0028 #include <net/ipv6.h>
0029 #endif
0030 
0031 #include <net/net_namespace.h>
0032 #include <net/netns/generic.h>
0033 
0034 #include <linux/netfilter/x_tables.h>
0035 #include <linux/netfilter_ipv4/ip_tables.h>
0036 #include <linux/netfilter_ipv6/ip6_tables.h>
0037 #include <linux/mutex.h>
0038 #include <linux/kernel.h>
0039 #include <linux/refcount.h>
0040 #include <uapi/linux/netfilter/xt_hashlimit.h>
0041 
0042 #define XT_HASHLIMIT_ALL (XT_HASHLIMIT_HASH_DIP | XT_HASHLIMIT_HASH_DPT | \
0043               XT_HASHLIMIT_HASH_SIP | XT_HASHLIMIT_HASH_SPT | \
0044               XT_HASHLIMIT_INVERT | XT_HASHLIMIT_BYTES |\
0045               XT_HASHLIMIT_RATE_MATCH)
0046 
0047 MODULE_LICENSE("GPL");
0048 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
0049 MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
0050 MODULE_DESCRIPTION("Xtables: per hash-bucket rate-limit match");
0051 MODULE_ALIAS("ipt_hashlimit");
0052 MODULE_ALIAS("ip6t_hashlimit");
0053 
0054 struct hashlimit_net {
0055     struct hlist_head   htables;
0056     struct proc_dir_entry   *ipt_hashlimit;
0057     struct proc_dir_entry   *ip6t_hashlimit;
0058 };
0059 
0060 static unsigned int hashlimit_net_id;
0061 static inline struct hashlimit_net *hashlimit_pernet(struct net *net)
0062 {
0063     return net_generic(net, hashlimit_net_id);
0064 }
0065 
0066 /* need to declare this at the top */
0067 static const struct seq_operations dl_seq_ops_v2;
0068 static const struct seq_operations dl_seq_ops_v1;
0069 static const struct seq_operations dl_seq_ops;
0070 
0071 /* hash table crap */
0072 struct dsthash_dst {
0073     union {
0074         struct {
0075             __be32 src;
0076             __be32 dst;
0077         } ip;
0078 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
0079         struct {
0080             __be32 src[4];
0081             __be32 dst[4];
0082         } ip6;
0083 #endif
0084     };
0085     __be16 src_port;
0086     __be16 dst_port;
0087 };
0088 
0089 struct dsthash_ent {
0090     /* static / read-only parts in the beginning */
0091     struct hlist_node node;
0092     struct dsthash_dst dst;
0093 
0094     /* modified structure members in the end */
0095     spinlock_t lock;
0096     unsigned long expires;      /* precalculated expiry time */
0097     struct {
0098         unsigned long prev; /* last modification */
0099         union {
0100             struct {
0101                 u_int64_t credit;
0102                 u_int64_t credit_cap;
0103                 u_int64_t cost;
0104             };
0105             struct {
0106                 u_int32_t interval, prev_window;
0107                 u_int64_t current_rate;
0108                 u_int64_t rate;
0109                 int64_t burst;
0110             };
0111         };
0112     } rateinfo;
0113     struct rcu_head rcu;
0114 };
0115 
0116 struct xt_hashlimit_htable {
0117     struct hlist_node node;     /* global list of all htables */
0118     refcount_t use;
0119     u_int8_t family;
0120     bool rnd_initialized;
0121 
0122     struct hashlimit_cfg3 cfg;  /* config */
0123 
0124     /* used internally */
0125     spinlock_t lock;        /* lock for list_head */
0126     u_int32_t rnd;          /* random seed for hash */
0127     unsigned int count;     /* number entries in table */
0128     struct delayed_work gc_work;
0129 
0130     /* seq_file stuff */
0131     struct proc_dir_entry *pde;
0132     const char *name;
0133     struct net *net;
0134 
0135     struct hlist_head hash[];   /* hashtable itself */
0136 };
0137 
0138 static int
0139 cfg_copy(struct hashlimit_cfg3 *to, const void *from, int revision)
0140 {
0141     if (revision == 1) {
0142         struct hashlimit_cfg1 *cfg = (struct hashlimit_cfg1 *)from;
0143 
0144         to->mode = cfg->mode;
0145         to->avg = cfg->avg;
0146         to->burst = cfg->burst;
0147         to->size = cfg->size;
0148         to->max = cfg->max;
0149         to->gc_interval = cfg->gc_interval;
0150         to->expire = cfg->expire;
0151         to->srcmask = cfg->srcmask;
0152         to->dstmask = cfg->dstmask;
0153     } else if (revision == 2) {
0154         struct hashlimit_cfg2 *cfg = (struct hashlimit_cfg2 *)from;
0155 
0156         to->mode = cfg->mode;
0157         to->avg = cfg->avg;
0158         to->burst = cfg->burst;
0159         to->size = cfg->size;
0160         to->max = cfg->max;
0161         to->gc_interval = cfg->gc_interval;
0162         to->expire = cfg->expire;
0163         to->srcmask = cfg->srcmask;
0164         to->dstmask = cfg->dstmask;
0165     } else if (revision == 3) {
0166         memcpy(to, from, sizeof(struct hashlimit_cfg3));
0167     } else {
0168         return -EINVAL;
0169     }
0170 
0171     return 0;
0172 }
0173 
0174 static DEFINE_MUTEX(hashlimit_mutex);   /* protects htables list */
0175 static struct kmem_cache *hashlimit_cachep __read_mostly;
0176 
0177 static inline bool dst_cmp(const struct dsthash_ent *ent,
0178                const struct dsthash_dst *b)
0179 {
0180     return !memcmp(&ent->dst, b, sizeof(ent->dst));
0181 }
0182 
0183 static u_int32_t
0184 hash_dst(const struct xt_hashlimit_htable *ht, const struct dsthash_dst *dst)
0185 {
0186     u_int32_t hash = jhash2((const u32 *)dst,
0187                 sizeof(*dst)/sizeof(u32),
0188                 ht->rnd);
0189     /*
0190      * Instead of returning hash % ht->cfg.size (implying a divide)
0191      * we return the high 32 bits of the (hash * ht->cfg.size) that will
0192      * give results between [0 and cfg.size-1] and same hash distribution,
0193      * but using a multiply, less expensive than a divide
0194      */
0195     return reciprocal_scale(hash, ht->cfg.size);
0196 }
0197 
0198 static struct dsthash_ent *
0199 dsthash_find(const struct xt_hashlimit_htable *ht,
0200          const struct dsthash_dst *dst)
0201 {
0202     struct dsthash_ent *ent;
0203     u_int32_t hash = hash_dst(ht, dst);
0204 
0205     if (!hlist_empty(&ht->hash[hash])) {
0206         hlist_for_each_entry_rcu(ent, &ht->hash[hash], node)
0207             if (dst_cmp(ent, dst)) {
0208                 spin_lock(&ent->lock);
0209                 return ent;
0210             }
0211     }
0212     return NULL;
0213 }
0214 
0215 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
0216 static struct dsthash_ent *
0217 dsthash_alloc_init(struct xt_hashlimit_htable *ht,
0218            const struct dsthash_dst *dst, bool *race)
0219 {
0220     struct dsthash_ent *ent;
0221 
0222     spin_lock(&ht->lock);
0223 
0224     /* Two or more packets may race to create the same entry in the
0225      * hashtable, double check if this packet lost race.
0226      */
0227     ent = dsthash_find(ht, dst);
0228     if (ent != NULL) {
0229         spin_unlock(&ht->lock);
0230         *race = true;
0231         return ent;
0232     }
0233 
0234     /* initialize hash with random val at the time we allocate
0235      * the first hashtable entry */
0236     if (unlikely(!ht->rnd_initialized)) {
0237         get_random_bytes(&ht->rnd, sizeof(ht->rnd));
0238         ht->rnd_initialized = true;
0239     }
0240 
0241     if (ht->cfg.max && ht->count >= ht->cfg.max) {
0242         /* FIXME: do something. question is what.. */
0243         net_err_ratelimited("max count of %u reached\n", ht->cfg.max);
0244         ent = NULL;
0245     } else
0246         ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
0247     if (ent) {
0248         memcpy(&ent->dst, dst, sizeof(ent->dst));
0249         spin_lock_init(&ent->lock);
0250 
0251         spin_lock(&ent->lock);
0252         hlist_add_head_rcu(&ent->node, &ht->hash[hash_dst(ht, dst)]);
0253         ht->count++;
0254     }
0255     spin_unlock(&ht->lock);
0256     return ent;
0257 }
0258 
0259 static void dsthash_free_rcu(struct rcu_head *head)
0260 {
0261     struct dsthash_ent *ent = container_of(head, struct dsthash_ent, rcu);
0262 
0263     kmem_cache_free(hashlimit_cachep, ent);
0264 }
0265 
0266 static inline void
0267 dsthash_free(struct xt_hashlimit_htable *ht, struct dsthash_ent *ent)
0268 {
0269     hlist_del_rcu(&ent->node);
0270     call_rcu(&ent->rcu, dsthash_free_rcu);
0271     ht->count--;
0272 }
0273 static void htable_gc(struct work_struct *work);
0274 
0275 static int htable_create(struct net *net, struct hashlimit_cfg3 *cfg,
0276              const char *name, u_int8_t family,
0277              struct xt_hashlimit_htable **out_hinfo,
0278              int revision)
0279 {
0280     struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
0281     struct xt_hashlimit_htable *hinfo;
0282     const struct seq_operations *ops;
0283     unsigned int size, i;
0284     unsigned long nr_pages = totalram_pages();
0285     int ret;
0286 
0287     if (cfg->size) {
0288         size = cfg->size;
0289     } else {
0290         size = (nr_pages << PAGE_SHIFT) / 16384 /
0291                sizeof(struct hlist_head);
0292         if (nr_pages > 1024 * 1024 * 1024 / PAGE_SIZE)
0293             size = 8192;
0294         if (size < 16)
0295             size = 16;
0296     }
0297     /* FIXME: don't use vmalloc() here or anywhere else -HW */
0298     hinfo = vmalloc(struct_size(hinfo, hash, size));
0299     if (hinfo == NULL)
0300         return -ENOMEM;
0301     *out_hinfo = hinfo;
0302 
0303     /* copy match config into hashtable config */
0304     ret = cfg_copy(&hinfo->cfg, (void *)cfg, 3);
0305     if (ret) {
0306         vfree(hinfo);
0307         return ret;
0308     }
0309 
0310     hinfo->cfg.size = size;
0311     if (hinfo->cfg.max == 0)
0312         hinfo->cfg.max = 8 * hinfo->cfg.size;
0313     else if (hinfo->cfg.max < hinfo->cfg.size)
0314         hinfo->cfg.max = hinfo->cfg.size;
0315 
0316     for (i = 0; i < hinfo->cfg.size; i++)
0317         INIT_HLIST_HEAD(&hinfo->hash[i]);
0318 
0319     refcount_set(&hinfo->use, 1);
0320     hinfo->count = 0;
0321     hinfo->family = family;
0322     hinfo->rnd_initialized = false;
0323     hinfo->name = kstrdup(name, GFP_KERNEL);
0324     if (!hinfo->name) {
0325         vfree(hinfo);
0326         return -ENOMEM;
0327     }
0328     spin_lock_init(&hinfo->lock);
0329 
0330     switch (revision) {
0331     case 1:
0332         ops = &dl_seq_ops_v1;
0333         break;
0334     case 2:
0335         ops = &dl_seq_ops_v2;
0336         break;
0337     default:
0338         ops = &dl_seq_ops;
0339     }
0340 
0341     hinfo->pde = proc_create_seq_data(name, 0,
0342         (family == NFPROTO_IPV4) ?
0343         hashlimit_net->ipt_hashlimit : hashlimit_net->ip6t_hashlimit,
0344         ops, hinfo);
0345     if (hinfo->pde == NULL) {
0346         kfree(hinfo->name);
0347         vfree(hinfo);
0348         return -ENOMEM;
0349     }
0350     hinfo->net = net;
0351 
0352     INIT_DEFERRABLE_WORK(&hinfo->gc_work, htable_gc);
0353     queue_delayed_work(system_power_efficient_wq, &hinfo->gc_work,
0354                msecs_to_jiffies(hinfo->cfg.gc_interval));
0355 
0356     hlist_add_head(&hinfo->node, &hashlimit_net->htables);
0357 
0358     return 0;
0359 }
0360 
0361 static void htable_selective_cleanup(struct xt_hashlimit_htable *ht, bool select_all)
0362 {
0363     unsigned int i;
0364 
0365     for (i = 0; i < ht->cfg.size; i++) {
0366         struct dsthash_ent *dh;
0367         struct hlist_node *n;
0368 
0369         spin_lock_bh(&ht->lock);
0370         hlist_for_each_entry_safe(dh, n, &ht->hash[i], node) {
0371             if (time_after_eq(jiffies, dh->expires) || select_all)
0372                 dsthash_free(ht, dh);
0373         }
0374         spin_unlock_bh(&ht->lock);
0375         cond_resched();
0376     }
0377 }
0378 
0379 static void htable_gc(struct work_struct *work)
0380 {
0381     struct xt_hashlimit_htable *ht;
0382 
0383     ht = container_of(work, struct xt_hashlimit_htable, gc_work.work);
0384 
0385     htable_selective_cleanup(ht, false);
0386 
0387     queue_delayed_work(system_power_efficient_wq,
0388                &ht->gc_work, msecs_to_jiffies(ht->cfg.gc_interval));
0389 }
0390 
0391 static void htable_remove_proc_entry(struct xt_hashlimit_htable *hinfo)
0392 {
0393     struct hashlimit_net *hashlimit_net = hashlimit_pernet(hinfo->net);
0394     struct proc_dir_entry *parent;
0395 
0396     if (hinfo->family == NFPROTO_IPV4)
0397         parent = hashlimit_net->ipt_hashlimit;
0398     else
0399         parent = hashlimit_net->ip6t_hashlimit;
0400 
0401     if (parent != NULL)
0402         remove_proc_entry(hinfo->name, parent);
0403 }
0404 
0405 static struct xt_hashlimit_htable *htable_find_get(struct net *net,
0406                            const char *name,
0407                            u_int8_t family)
0408 {
0409     struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
0410     struct xt_hashlimit_htable *hinfo;
0411 
0412     hlist_for_each_entry(hinfo, &hashlimit_net->htables, node) {
0413         if (!strcmp(name, hinfo->name) &&
0414             hinfo->family == family) {
0415             refcount_inc(&hinfo->use);
0416             return hinfo;
0417         }
0418     }
0419     return NULL;
0420 }
0421 
0422 static void htable_put(struct xt_hashlimit_htable *hinfo)
0423 {
0424     if (refcount_dec_and_mutex_lock(&hinfo->use, &hashlimit_mutex)) {
0425         hlist_del(&hinfo->node);
0426         htable_remove_proc_entry(hinfo);
0427         mutex_unlock(&hashlimit_mutex);
0428 
0429         cancel_delayed_work_sync(&hinfo->gc_work);
0430         htable_selective_cleanup(hinfo, true);
0431         kfree(hinfo->name);
0432         vfree(hinfo);
0433     }
0434 }
0435 
0436 /* The algorithm used is the Simple Token Bucket Filter (TBF)
0437  * see net/sched/sch_tbf.c in the linux source tree
0438  */
0439 
0440 /* Rusty: This is my (non-mathematically-inclined) understanding of
0441    this algorithm.  The `average rate' in jiffies becomes your initial
0442    amount of credit `credit' and the most credit you can ever have
0443    `credit_cap'.  The `peak rate' becomes the cost of passing the
0444    test, `cost'.
0445 
0446    `prev' tracks the last packet hit: you gain one credit per jiffy.
0447    If you get credit balance more than this, the extra credit is
0448    discarded.  Every time the match passes, you lose `cost' credits;
0449    if you don't have that many, the test fails.
0450 
0451    See Alexey's formal explanation in net/sched/sch_tbf.c.
0452 
0453    To get the maximum range, we multiply by this factor (ie. you get N
0454    credits per jiffy).  We want to allow a rate as low as 1 per day
0455    (slowest userspace tool allows), which means
0456    CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
0457 */
0458 #define MAX_CPJ_v1 (0xFFFFFFFF / (HZ*60*60*24))
0459 #define MAX_CPJ (0xFFFFFFFFFFFFFFFFULL / (HZ*60*60*24))
0460 
0461 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
0462  * us the power of 2 below the theoretical max, so GCC simply does a
0463  * shift. */
0464 #define _POW2_BELOW2(x) ((x)|((x)>>1))
0465 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
0466 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
0467 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
0468 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
0469 #define _POW2_BELOW64(x) (_POW2_BELOW32(x)|_POW2_BELOW32((x)>>32))
0470 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
0471 #define POW2_BELOW64(x) ((_POW2_BELOW64(x)>>1) + 1)
0472 
0473 #define CREDITS_PER_JIFFY POW2_BELOW64(MAX_CPJ)
0474 #define CREDITS_PER_JIFFY_v1 POW2_BELOW32(MAX_CPJ_v1)
0475 
0476 /* in byte mode, the lowest possible rate is one packet/second.
0477  * credit_cap is used as a counter that tells us how many times we can
0478  * refill the "credits available" counter when it becomes empty.
0479  */
0480 #define MAX_CPJ_BYTES (0xFFFFFFFF / HZ)
0481 #define CREDITS_PER_JIFFY_BYTES POW2_BELOW32(MAX_CPJ_BYTES)
0482 
0483 static u32 xt_hashlimit_len_to_chunks(u32 len)
0484 {
0485     return (len >> XT_HASHLIMIT_BYTE_SHIFT) + 1;
0486 }
0487 
0488 /* Precision saver. */
0489 static u64 user2credits(u64 user, int revision)
0490 {
0491     u64 scale = (revision == 1) ?
0492         XT_HASHLIMIT_SCALE : XT_HASHLIMIT_SCALE_v2;
0493     u64 cpj = (revision == 1) ?
0494         CREDITS_PER_JIFFY_v1 : CREDITS_PER_JIFFY;
0495 
0496     /* Avoid overflow: divide the constant operands first */
0497     if (scale >= HZ * cpj)
0498         return div64_u64(user, div64_u64(scale, HZ * cpj));
0499 
0500     return user * div64_u64(HZ * cpj, scale);
0501 }
0502 
0503 static u32 user2credits_byte(u32 user)
0504 {
0505     u64 us = user;
0506     us *= HZ * CREDITS_PER_JIFFY_BYTES;
0507     return (u32) (us >> 32);
0508 }
0509 
0510 static u64 user2rate(u64 user)
0511 {
0512     if (user != 0) {
0513         return div64_u64(XT_HASHLIMIT_SCALE_v2, user);
0514     } else {
0515         pr_info_ratelimited("invalid rate from userspace: %llu\n",
0516                     user);
0517         return 0;
0518     }
0519 }
0520 
0521 static u64 user2rate_bytes(u32 user)
0522 {
0523     u64 r;
0524 
0525     r = user ? U32_MAX / user : U32_MAX;
0526     return (r - 1) << XT_HASHLIMIT_BYTE_SHIFT;
0527 }
0528 
0529 static void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now,
0530                 u32 mode, int revision)
0531 {
0532     unsigned long delta = now - dh->rateinfo.prev;
0533     u64 cap, cpj;
0534 
0535     if (delta == 0)
0536         return;
0537 
0538     if (revision >= 3 && mode & XT_HASHLIMIT_RATE_MATCH) {
0539         u64 interval = dh->rateinfo.interval * HZ;
0540 
0541         if (delta < interval)
0542             return;
0543 
0544         dh->rateinfo.prev = now;
0545         dh->rateinfo.prev_window =
0546             ((dh->rateinfo.current_rate * interval) >
0547              (delta * dh->rateinfo.rate));
0548         dh->rateinfo.current_rate = 0;
0549 
0550         return;
0551     }
0552 
0553     dh->rateinfo.prev = now;
0554 
0555     if (mode & XT_HASHLIMIT_BYTES) {
0556         u64 tmp = dh->rateinfo.credit;
0557         dh->rateinfo.credit += CREDITS_PER_JIFFY_BYTES * delta;
0558         cap = CREDITS_PER_JIFFY_BYTES * HZ;
0559         if (tmp >= dh->rateinfo.credit) {/* overflow */
0560             dh->rateinfo.credit = cap;
0561             return;
0562         }
0563     } else {
0564         cpj = (revision == 1) ?
0565             CREDITS_PER_JIFFY_v1 : CREDITS_PER_JIFFY;
0566         dh->rateinfo.credit += delta * cpj;
0567         cap = dh->rateinfo.credit_cap;
0568     }
0569     if (dh->rateinfo.credit > cap)
0570         dh->rateinfo.credit = cap;
0571 }
0572 
0573 static void rateinfo_init(struct dsthash_ent *dh,
0574               struct xt_hashlimit_htable *hinfo, int revision)
0575 {
0576     dh->rateinfo.prev = jiffies;
0577     if (revision >= 3 && hinfo->cfg.mode & XT_HASHLIMIT_RATE_MATCH) {
0578         dh->rateinfo.prev_window = 0;
0579         dh->rateinfo.current_rate = 0;
0580         if (hinfo->cfg.mode & XT_HASHLIMIT_BYTES) {
0581             dh->rateinfo.rate =
0582                 user2rate_bytes((u32)hinfo->cfg.avg);
0583             if (hinfo->cfg.burst)
0584                 dh->rateinfo.burst =
0585                     hinfo->cfg.burst * dh->rateinfo.rate;
0586             else
0587                 dh->rateinfo.burst = dh->rateinfo.rate;
0588         } else {
0589             dh->rateinfo.rate = user2rate(hinfo->cfg.avg);
0590             dh->rateinfo.burst =
0591                 hinfo->cfg.burst + dh->rateinfo.rate;
0592         }
0593         dh->rateinfo.interval = hinfo->cfg.interval;
0594     } else if (hinfo->cfg.mode & XT_HASHLIMIT_BYTES) {
0595         dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
0596         dh->rateinfo.cost = user2credits_byte(hinfo->cfg.avg);
0597         dh->rateinfo.credit_cap = hinfo->cfg.burst;
0598     } else {
0599         dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
0600                            hinfo->cfg.burst, revision);
0601         dh->rateinfo.cost = user2credits(hinfo->cfg.avg, revision);
0602         dh->rateinfo.credit_cap = dh->rateinfo.credit;
0603     }
0604 }
0605 
0606 static inline __be32 maskl(__be32 a, unsigned int l)
0607 {
0608     return l ? htonl(ntohl(a) & ~0 << (32 - l)) : 0;
0609 }
0610 
0611 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
0612 static void hashlimit_ipv6_mask(__be32 *i, unsigned int p)
0613 {
0614     switch (p) {
0615     case 0 ... 31:
0616         i[0] = maskl(i[0], p);
0617         i[1] = i[2] = i[3] = 0;
0618         break;
0619     case 32 ... 63:
0620         i[1] = maskl(i[1], p - 32);
0621         i[2] = i[3] = 0;
0622         break;
0623     case 64 ... 95:
0624         i[2] = maskl(i[2], p - 64);
0625         i[3] = 0;
0626         break;
0627     case 96 ... 127:
0628         i[3] = maskl(i[3], p - 96);
0629         break;
0630     case 128:
0631         break;
0632     }
0633 }
0634 #endif
0635 
0636 static int
0637 hashlimit_init_dst(const struct xt_hashlimit_htable *hinfo,
0638            struct dsthash_dst *dst,
0639            const struct sk_buff *skb, unsigned int protoff)
0640 {
0641     __be16 _ports[2], *ports;
0642     u8 nexthdr;
0643     int poff;
0644 
0645     memset(dst, 0, sizeof(*dst));
0646 
0647     switch (hinfo->family) {
0648     case NFPROTO_IPV4:
0649         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
0650             dst->ip.dst = maskl(ip_hdr(skb)->daddr,
0651                           hinfo->cfg.dstmask);
0652         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
0653             dst->ip.src = maskl(ip_hdr(skb)->saddr,
0654                           hinfo->cfg.srcmask);
0655 
0656         if (!(hinfo->cfg.mode &
0657               (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
0658             return 0;
0659         nexthdr = ip_hdr(skb)->protocol;
0660         break;
0661 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
0662     case NFPROTO_IPV6:
0663     {
0664         __be16 frag_off;
0665 
0666         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP) {
0667             memcpy(&dst->ip6.dst, &ipv6_hdr(skb)->daddr,
0668                    sizeof(dst->ip6.dst));
0669             hashlimit_ipv6_mask(dst->ip6.dst, hinfo->cfg.dstmask);
0670         }
0671         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP) {
0672             memcpy(&dst->ip6.src, &ipv6_hdr(skb)->saddr,
0673                    sizeof(dst->ip6.src));
0674             hashlimit_ipv6_mask(dst->ip6.src, hinfo->cfg.srcmask);
0675         }
0676 
0677         if (!(hinfo->cfg.mode &
0678               (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
0679             return 0;
0680         nexthdr = ipv6_hdr(skb)->nexthdr;
0681         protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr, &frag_off);
0682         if ((int)protoff < 0)
0683             return -1;
0684         break;
0685     }
0686 #endif
0687     default:
0688         BUG();
0689         return 0;
0690     }
0691 
0692     poff = proto_ports_offset(nexthdr);
0693     if (poff >= 0) {
0694         ports = skb_header_pointer(skb, protoff + poff, sizeof(_ports),
0695                        &_ports);
0696     } else {
0697         _ports[0] = _ports[1] = 0;
0698         ports = _ports;
0699     }
0700     if (!ports)
0701         return -1;
0702     if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SPT)
0703         dst->src_port = ports[0];
0704     if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DPT)
0705         dst->dst_port = ports[1];
0706     return 0;
0707 }
0708 
0709 static u32 hashlimit_byte_cost(unsigned int len, struct dsthash_ent *dh)
0710 {
0711     u64 tmp = xt_hashlimit_len_to_chunks(len);
0712     tmp = tmp * dh->rateinfo.cost;
0713 
0714     if (unlikely(tmp > CREDITS_PER_JIFFY_BYTES * HZ))
0715         tmp = CREDITS_PER_JIFFY_BYTES * HZ;
0716 
0717     if (dh->rateinfo.credit < tmp && dh->rateinfo.credit_cap) {
0718         dh->rateinfo.credit_cap--;
0719         dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
0720     }
0721     return (u32) tmp;
0722 }
0723 
0724 static bool
0725 hashlimit_mt_common(const struct sk_buff *skb, struct xt_action_param *par,
0726             struct xt_hashlimit_htable *hinfo,
0727             const struct hashlimit_cfg3 *cfg, int revision)
0728 {
0729     unsigned long now = jiffies;
0730     struct dsthash_ent *dh;
0731     struct dsthash_dst dst;
0732     bool race = false;
0733     u64 cost;
0734 
0735     if (hashlimit_init_dst(hinfo, &dst, skb, par->thoff) < 0)
0736         goto hotdrop;
0737 
0738     local_bh_disable();
0739     dh = dsthash_find(hinfo, &dst);
0740     if (dh == NULL) {
0741         dh = dsthash_alloc_init(hinfo, &dst, &race);
0742         if (dh == NULL) {
0743             local_bh_enable();
0744             goto hotdrop;
0745         } else if (race) {
0746             /* Already got an entry, update expiration timeout */
0747             dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
0748             rateinfo_recalc(dh, now, hinfo->cfg.mode, revision);
0749         } else {
0750             dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
0751             rateinfo_init(dh, hinfo, revision);
0752         }
0753     } else {
0754         /* update expiration timeout */
0755         dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
0756         rateinfo_recalc(dh, now, hinfo->cfg.mode, revision);
0757     }
0758 
0759     if (cfg->mode & XT_HASHLIMIT_RATE_MATCH) {
0760         cost = (cfg->mode & XT_HASHLIMIT_BYTES) ? skb->len : 1;
0761         dh->rateinfo.current_rate += cost;
0762 
0763         if (!dh->rateinfo.prev_window &&
0764             (dh->rateinfo.current_rate <= dh->rateinfo.burst)) {
0765             spin_unlock(&dh->lock);
0766             local_bh_enable();
0767             return !(cfg->mode & XT_HASHLIMIT_INVERT);
0768         } else {
0769             goto overlimit;
0770         }
0771     }
0772 
0773     if (cfg->mode & XT_HASHLIMIT_BYTES)
0774         cost = hashlimit_byte_cost(skb->len, dh);
0775     else
0776         cost = dh->rateinfo.cost;
0777 
0778     if (dh->rateinfo.credit >= cost) {
0779         /* below the limit */
0780         dh->rateinfo.credit -= cost;
0781         spin_unlock(&dh->lock);
0782         local_bh_enable();
0783         return !(cfg->mode & XT_HASHLIMIT_INVERT);
0784     }
0785 
0786 overlimit:
0787     spin_unlock(&dh->lock);
0788     local_bh_enable();
0789     /* default match is underlimit - so over the limit, we need to invert */
0790     return cfg->mode & XT_HASHLIMIT_INVERT;
0791 
0792  hotdrop:
0793     par->hotdrop = true;
0794     return false;
0795 }
0796 
0797 static bool
0798 hashlimit_mt_v1(const struct sk_buff *skb, struct xt_action_param *par)
0799 {
0800     const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
0801     struct xt_hashlimit_htable *hinfo = info->hinfo;
0802     struct hashlimit_cfg3 cfg = {};
0803     int ret;
0804 
0805     ret = cfg_copy(&cfg, (void *)&info->cfg, 1);
0806     if (ret)
0807         return ret;
0808 
0809     return hashlimit_mt_common(skb, par, hinfo, &cfg, 1);
0810 }
0811 
0812 static bool
0813 hashlimit_mt_v2(const struct sk_buff *skb, struct xt_action_param *par)
0814 {
0815     const struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
0816     struct xt_hashlimit_htable *hinfo = info->hinfo;
0817     struct hashlimit_cfg3 cfg = {};
0818     int ret;
0819 
0820     ret = cfg_copy(&cfg, (void *)&info->cfg, 2);
0821     if (ret)
0822         return ret;
0823 
0824     return hashlimit_mt_common(skb, par, hinfo, &cfg, 2);
0825 }
0826 
0827 static bool
0828 hashlimit_mt(const struct sk_buff *skb, struct xt_action_param *par)
0829 {
0830     const struct xt_hashlimit_mtinfo3 *info = par->matchinfo;
0831     struct xt_hashlimit_htable *hinfo = info->hinfo;
0832 
0833     return hashlimit_mt_common(skb, par, hinfo, &info->cfg, 3);
0834 }
0835 
0836 #define HASHLIMIT_MAX_SIZE 1048576
0837 
0838 static int hashlimit_mt_check_common(const struct xt_mtchk_param *par,
0839                      struct xt_hashlimit_htable **hinfo,
0840                      struct hashlimit_cfg3 *cfg,
0841                      const char *name, int revision)
0842 {
0843     struct net *net = par->net;
0844     int ret;
0845 
0846     if (cfg->gc_interval == 0 || cfg->expire == 0)
0847         return -EINVAL;
0848     if (cfg->size > HASHLIMIT_MAX_SIZE) {
0849         cfg->size = HASHLIMIT_MAX_SIZE;
0850         pr_info_ratelimited("size too large, truncated to %u\n", cfg->size);
0851     }
0852     if (cfg->max > HASHLIMIT_MAX_SIZE) {
0853         cfg->max = HASHLIMIT_MAX_SIZE;
0854         pr_info_ratelimited("max too large, truncated to %u\n", cfg->max);
0855     }
0856     if (par->family == NFPROTO_IPV4) {
0857         if (cfg->srcmask > 32 || cfg->dstmask > 32)
0858             return -EINVAL;
0859     } else {
0860         if (cfg->srcmask > 128 || cfg->dstmask > 128)
0861             return -EINVAL;
0862     }
0863 
0864     if (cfg->mode & ~XT_HASHLIMIT_ALL) {
0865         pr_info_ratelimited("Unknown mode mask %X, kernel too old?\n",
0866                     cfg->mode);
0867         return -EINVAL;
0868     }
0869 
0870     /* Check for overflow. */
0871     if (revision >= 3 && cfg->mode & XT_HASHLIMIT_RATE_MATCH) {
0872         if (cfg->avg == 0 || cfg->avg > U32_MAX) {
0873             pr_info_ratelimited("invalid rate\n");
0874             return -ERANGE;
0875         }
0876 
0877         if (cfg->interval == 0) {
0878             pr_info_ratelimited("invalid interval\n");
0879             return -EINVAL;
0880         }
0881     } else if (cfg->mode & XT_HASHLIMIT_BYTES) {
0882         if (user2credits_byte(cfg->avg) == 0) {
0883             pr_info_ratelimited("overflow, rate too high: %llu\n",
0884                         cfg->avg);
0885             return -EINVAL;
0886         }
0887     } else if (cfg->burst == 0 ||
0888            user2credits(cfg->avg * cfg->burst, revision) <
0889            user2credits(cfg->avg, revision)) {
0890         pr_info_ratelimited("overflow, try lower: %llu/%llu\n",
0891                     cfg->avg, cfg->burst);
0892         return -ERANGE;
0893     }
0894 
0895     mutex_lock(&hashlimit_mutex);
0896     *hinfo = htable_find_get(net, name, par->family);
0897     if (*hinfo == NULL) {
0898         ret = htable_create(net, cfg, name, par->family,
0899                     hinfo, revision);
0900         if (ret < 0) {
0901             mutex_unlock(&hashlimit_mutex);
0902             return ret;
0903         }
0904     }
0905     mutex_unlock(&hashlimit_mutex);
0906 
0907     return 0;
0908 }
0909 
0910 static int hashlimit_mt_check_v1(const struct xt_mtchk_param *par)
0911 {
0912     struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
0913     struct hashlimit_cfg3 cfg = {};
0914     int ret;
0915 
0916     ret = xt_check_proc_name(info->name, sizeof(info->name));
0917     if (ret)
0918         return ret;
0919 
0920     ret = cfg_copy(&cfg, (void *)&info->cfg, 1);
0921     if (ret)
0922         return ret;
0923 
0924     return hashlimit_mt_check_common(par, &info->hinfo,
0925                      &cfg, info->name, 1);
0926 }
0927 
0928 static int hashlimit_mt_check_v2(const struct xt_mtchk_param *par)
0929 {
0930     struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
0931     struct hashlimit_cfg3 cfg = {};
0932     int ret;
0933 
0934     ret = xt_check_proc_name(info->name, sizeof(info->name));
0935     if (ret)
0936         return ret;
0937 
0938     ret = cfg_copy(&cfg, (void *)&info->cfg, 2);
0939     if (ret)
0940         return ret;
0941 
0942     return hashlimit_mt_check_common(par, &info->hinfo,
0943                      &cfg, info->name, 2);
0944 }
0945 
0946 static int hashlimit_mt_check(const struct xt_mtchk_param *par)
0947 {
0948     struct xt_hashlimit_mtinfo3 *info = par->matchinfo;
0949     int ret;
0950 
0951     ret = xt_check_proc_name(info->name, sizeof(info->name));
0952     if (ret)
0953         return ret;
0954 
0955     return hashlimit_mt_check_common(par, &info->hinfo, &info->cfg,
0956                      info->name, 3);
0957 }
0958 
0959 static void hashlimit_mt_destroy_v2(const struct xt_mtdtor_param *par)
0960 {
0961     const struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
0962 
0963     htable_put(info->hinfo);
0964 }
0965 
0966 static void hashlimit_mt_destroy_v1(const struct xt_mtdtor_param *par)
0967 {
0968     const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
0969 
0970     htable_put(info->hinfo);
0971 }
0972 
0973 static void hashlimit_mt_destroy(const struct xt_mtdtor_param *par)
0974 {
0975     const struct xt_hashlimit_mtinfo3 *info = par->matchinfo;
0976 
0977     htable_put(info->hinfo);
0978 }
0979 
0980 static struct xt_match hashlimit_mt_reg[] __read_mostly = {
0981     {
0982         .name           = "hashlimit",
0983         .revision       = 1,
0984         .family         = NFPROTO_IPV4,
0985         .match          = hashlimit_mt_v1,
0986         .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
0987         .usersize   = offsetof(struct xt_hashlimit_mtinfo1, hinfo),
0988         .checkentry     = hashlimit_mt_check_v1,
0989         .destroy        = hashlimit_mt_destroy_v1,
0990         .me             = THIS_MODULE,
0991     },
0992     {
0993         .name           = "hashlimit",
0994         .revision       = 2,
0995         .family         = NFPROTO_IPV4,
0996         .match          = hashlimit_mt_v2,
0997         .matchsize      = sizeof(struct xt_hashlimit_mtinfo2),
0998         .usersize   = offsetof(struct xt_hashlimit_mtinfo2, hinfo),
0999         .checkentry     = hashlimit_mt_check_v2,
1000         .destroy        = hashlimit_mt_destroy_v2,
1001         .me             = THIS_MODULE,
1002     },
1003     {
1004         .name           = "hashlimit",
1005         .revision       = 3,
1006         .family         = NFPROTO_IPV4,
1007         .match          = hashlimit_mt,
1008         .matchsize      = sizeof(struct xt_hashlimit_mtinfo3),
1009         .usersize   = offsetof(struct xt_hashlimit_mtinfo3, hinfo),
1010         .checkentry     = hashlimit_mt_check,
1011         .destroy        = hashlimit_mt_destroy,
1012         .me             = THIS_MODULE,
1013     },
1014 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1015     {
1016         .name           = "hashlimit",
1017         .revision       = 1,
1018         .family         = NFPROTO_IPV6,
1019         .match          = hashlimit_mt_v1,
1020         .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
1021         .usersize   = offsetof(struct xt_hashlimit_mtinfo1, hinfo),
1022         .checkentry     = hashlimit_mt_check_v1,
1023         .destroy        = hashlimit_mt_destroy_v1,
1024         .me             = THIS_MODULE,
1025     },
1026     {
1027         .name           = "hashlimit",
1028         .revision       = 2,
1029         .family         = NFPROTO_IPV6,
1030         .match          = hashlimit_mt_v2,
1031         .matchsize      = sizeof(struct xt_hashlimit_mtinfo2),
1032         .usersize   = offsetof(struct xt_hashlimit_mtinfo2, hinfo),
1033         .checkentry     = hashlimit_mt_check_v2,
1034         .destroy        = hashlimit_mt_destroy_v2,
1035         .me             = THIS_MODULE,
1036     },
1037     {
1038         .name           = "hashlimit",
1039         .revision       = 3,
1040         .family         = NFPROTO_IPV6,
1041         .match          = hashlimit_mt,
1042         .matchsize      = sizeof(struct xt_hashlimit_mtinfo3),
1043         .usersize   = offsetof(struct xt_hashlimit_mtinfo3, hinfo),
1044         .checkentry     = hashlimit_mt_check,
1045         .destroy        = hashlimit_mt_destroy,
1046         .me             = THIS_MODULE,
1047     },
1048 #endif
1049 };
1050 
1051 /* PROC stuff */
1052 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
1053     __acquires(htable->lock)
1054 {
1055     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1056     unsigned int *bucket;
1057 
1058     spin_lock_bh(&htable->lock);
1059     if (*pos >= htable->cfg.size)
1060         return NULL;
1061 
1062     bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
1063     if (!bucket)
1064         return ERR_PTR(-ENOMEM);
1065 
1066     *bucket = *pos;
1067     return bucket;
1068 }
1069 
1070 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
1071 {
1072     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1073     unsigned int *bucket = v;
1074 
1075     *pos = ++(*bucket);
1076     if (*pos >= htable->cfg.size) {
1077         kfree(v);
1078         return NULL;
1079     }
1080     return bucket;
1081 }
1082 
1083 static void dl_seq_stop(struct seq_file *s, void *v)
1084     __releases(htable->lock)
1085 {
1086     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1087     unsigned int *bucket = v;
1088 
1089     if (!IS_ERR(bucket))
1090         kfree(bucket);
1091     spin_unlock_bh(&htable->lock);
1092 }
1093 
1094 static void dl_seq_print(struct dsthash_ent *ent, u_int8_t family,
1095              struct seq_file *s)
1096 {
1097     switch (family) {
1098     case NFPROTO_IPV4:
1099         seq_printf(s, "%ld %pI4:%u->%pI4:%u %llu %llu %llu\n",
1100                (long)(ent->expires - jiffies)/HZ,
1101                &ent->dst.ip.src,
1102                ntohs(ent->dst.src_port),
1103                &ent->dst.ip.dst,
1104                ntohs(ent->dst.dst_port),
1105                ent->rateinfo.credit, ent->rateinfo.credit_cap,
1106                ent->rateinfo.cost);
1107         break;
1108 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1109     case NFPROTO_IPV6:
1110         seq_printf(s, "%ld %pI6:%u->%pI6:%u %llu %llu %llu\n",
1111                (long)(ent->expires - jiffies)/HZ,
1112                &ent->dst.ip6.src,
1113                ntohs(ent->dst.src_port),
1114                &ent->dst.ip6.dst,
1115                ntohs(ent->dst.dst_port),
1116                ent->rateinfo.credit, ent->rateinfo.credit_cap,
1117                ent->rateinfo.cost);
1118         break;
1119 #endif
1120     default:
1121         BUG();
1122     }
1123 }
1124 
1125 static int dl_seq_real_show_v2(struct dsthash_ent *ent, u_int8_t family,
1126                    struct seq_file *s)
1127 {
1128     struct xt_hashlimit_htable *ht = pde_data(file_inode(s->file));
1129 
1130     spin_lock(&ent->lock);
1131     /* recalculate to show accurate numbers */
1132     rateinfo_recalc(ent, jiffies, ht->cfg.mode, 2);
1133 
1134     dl_seq_print(ent, family, s);
1135 
1136     spin_unlock(&ent->lock);
1137     return seq_has_overflowed(s);
1138 }
1139 
1140 static int dl_seq_real_show_v1(struct dsthash_ent *ent, u_int8_t family,
1141                    struct seq_file *s)
1142 {
1143     struct xt_hashlimit_htable *ht = pde_data(file_inode(s->file));
1144 
1145     spin_lock(&ent->lock);
1146     /* recalculate to show accurate numbers */
1147     rateinfo_recalc(ent, jiffies, ht->cfg.mode, 1);
1148 
1149     dl_seq_print(ent, family, s);
1150 
1151     spin_unlock(&ent->lock);
1152     return seq_has_overflowed(s);
1153 }
1154 
1155 static int dl_seq_real_show(struct dsthash_ent *ent, u_int8_t family,
1156                 struct seq_file *s)
1157 {
1158     struct xt_hashlimit_htable *ht = pde_data(file_inode(s->file));
1159 
1160     spin_lock(&ent->lock);
1161     /* recalculate to show accurate numbers */
1162     rateinfo_recalc(ent, jiffies, ht->cfg.mode, 3);
1163 
1164     dl_seq_print(ent, family, s);
1165 
1166     spin_unlock(&ent->lock);
1167     return seq_has_overflowed(s);
1168 }
1169 
1170 static int dl_seq_show_v2(struct seq_file *s, void *v)
1171 {
1172     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1173     unsigned int *bucket = (unsigned int *)v;
1174     struct dsthash_ent *ent;
1175 
1176     if (!hlist_empty(&htable->hash[*bucket])) {
1177         hlist_for_each_entry(ent, &htable->hash[*bucket], node)
1178             if (dl_seq_real_show_v2(ent, htable->family, s))
1179                 return -1;
1180     }
1181     return 0;
1182 }
1183 
1184 static int dl_seq_show_v1(struct seq_file *s, void *v)
1185 {
1186     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1187     unsigned int *bucket = v;
1188     struct dsthash_ent *ent;
1189 
1190     if (!hlist_empty(&htable->hash[*bucket])) {
1191         hlist_for_each_entry(ent, &htable->hash[*bucket], node)
1192             if (dl_seq_real_show_v1(ent, htable->family, s))
1193                 return -1;
1194     }
1195     return 0;
1196 }
1197 
1198 static int dl_seq_show(struct seq_file *s, void *v)
1199 {
1200     struct xt_hashlimit_htable *htable = pde_data(file_inode(s->file));
1201     unsigned int *bucket = v;
1202     struct dsthash_ent *ent;
1203 
1204     if (!hlist_empty(&htable->hash[*bucket])) {
1205         hlist_for_each_entry(ent, &htable->hash[*bucket], node)
1206             if (dl_seq_real_show(ent, htable->family, s))
1207                 return -1;
1208     }
1209     return 0;
1210 }
1211 
1212 static const struct seq_operations dl_seq_ops_v1 = {
1213     .start = dl_seq_start,
1214     .next  = dl_seq_next,
1215     .stop  = dl_seq_stop,
1216     .show  = dl_seq_show_v1
1217 };
1218 
1219 static const struct seq_operations dl_seq_ops_v2 = {
1220     .start = dl_seq_start,
1221     .next  = dl_seq_next,
1222     .stop  = dl_seq_stop,
1223     .show  = dl_seq_show_v2
1224 };
1225 
1226 static const struct seq_operations dl_seq_ops = {
1227     .start = dl_seq_start,
1228     .next  = dl_seq_next,
1229     .stop  = dl_seq_stop,
1230     .show  = dl_seq_show
1231 };
1232 
1233 static int __net_init hashlimit_proc_net_init(struct net *net)
1234 {
1235     struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1236 
1237     hashlimit_net->ipt_hashlimit = proc_mkdir("ipt_hashlimit", net->proc_net);
1238     if (!hashlimit_net->ipt_hashlimit)
1239         return -ENOMEM;
1240 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1241     hashlimit_net->ip6t_hashlimit = proc_mkdir("ip6t_hashlimit", net->proc_net);
1242     if (!hashlimit_net->ip6t_hashlimit) {
1243         remove_proc_entry("ipt_hashlimit", net->proc_net);
1244         return -ENOMEM;
1245     }
1246 #endif
1247     return 0;
1248 }
1249 
1250 static void __net_exit hashlimit_proc_net_exit(struct net *net)
1251 {
1252     struct xt_hashlimit_htable *hinfo;
1253     struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1254 
1255     /* hashlimit_net_exit() is called before hashlimit_mt_destroy().
1256      * Make sure that the parent ipt_hashlimit and ip6t_hashlimit proc
1257      * entries is empty before trying to remove it.
1258      */
1259     mutex_lock(&hashlimit_mutex);
1260     hlist_for_each_entry(hinfo, &hashlimit_net->htables, node)
1261         htable_remove_proc_entry(hinfo);
1262     hashlimit_net->ipt_hashlimit = NULL;
1263     hashlimit_net->ip6t_hashlimit = NULL;
1264     mutex_unlock(&hashlimit_mutex);
1265 
1266     remove_proc_entry("ipt_hashlimit", net->proc_net);
1267 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1268     remove_proc_entry("ip6t_hashlimit", net->proc_net);
1269 #endif
1270 }
1271 
1272 static int __net_init hashlimit_net_init(struct net *net)
1273 {
1274     struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1275 
1276     INIT_HLIST_HEAD(&hashlimit_net->htables);
1277     return hashlimit_proc_net_init(net);
1278 }
1279 
1280 static void __net_exit hashlimit_net_exit(struct net *net)
1281 {
1282     hashlimit_proc_net_exit(net);
1283 }
1284 
1285 static struct pernet_operations hashlimit_net_ops = {
1286     .init   = hashlimit_net_init,
1287     .exit   = hashlimit_net_exit,
1288     .id = &hashlimit_net_id,
1289     .size   = sizeof(struct hashlimit_net),
1290 };
1291 
1292 static int __init hashlimit_mt_init(void)
1293 {
1294     int err;
1295 
1296     err = register_pernet_subsys(&hashlimit_net_ops);
1297     if (err < 0)
1298         return err;
1299     err = xt_register_matches(hashlimit_mt_reg,
1300           ARRAY_SIZE(hashlimit_mt_reg));
1301     if (err < 0)
1302         goto err1;
1303 
1304     err = -ENOMEM;
1305     hashlimit_cachep = kmem_cache_create("xt_hashlimit",
1306                         sizeof(struct dsthash_ent), 0, 0,
1307                         NULL);
1308     if (!hashlimit_cachep) {
1309         pr_warn("unable to create slab cache\n");
1310         goto err2;
1311     }
1312     return 0;
1313 
1314 err2:
1315     xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1316 err1:
1317     unregister_pernet_subsys(&hashlimit_net_ops);
1318     return err;
1319 
1320 }
1321 
1322 static void __exit hashlimit_mt_exit(void)
1323 {
1324     xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1325     unregister_pernet_subsys(&hashlimit_net_ops);
1326 
1327     rcu_barrier();
1328     kmem_cache_destroy(hashlimit_cachep);
1329 }
1330 
1331 module_init(hashlimit_mt_init);
1332 module_exit(hashlimit_mt_exit);