1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter. This is separated from,
3 but required by, the NAT layer; it can also be used by an iptables
6 /* (C) 1999-2001 Paul `Rusty' Russell
7 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9 * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/jhash.h>
25 #include <linux/siphash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
37 #include <net/netfilter/nf_conntrack.h>
38 #include <net/netfilter/nf_conntrack_l4proto.h>
39 #include <net/netfilter/nf_conntrack_expect.h>
40 #include <net/netfilter/nf_conntrack_helper.h>
41 #include <net/netfilter/nf_conntrack_seqadj.h>
42 #include <net/netfilter/nf_conntrack_core.h>
43 #include <net/netfilter/nf_conntrack_extend.h>
44 #include <net/netfilter/nf_conntrack_acct.h>
45 #include <net/netfilter/nf_conntrack_ecache.h>
46 #include <net/netfilter/nf_conntrack_zones.h>
47 #include <net/netfilter/nf_conntrack_timestamp.h>
48 #include <net/netfilter/nf_conntrack_timeout.h>
49 #include <net/netfilter/nf_conntrack_labels.h>
50 #include <net/netfilter/nf_conntrack_synproxy.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_helper.h>
53 #include <net/netns/hash.h>
56 #include "nf_internals.h"
58 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
59 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
61 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
62 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
64 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
65 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
67 struct conntrack_gc_work {
68 struct delayed_work dwork;
75 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
76 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
77 static __read_mostly bool nf_conntrack_locks_all;
79 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
80 #define GC_MAX_BUCKETS_DIV 128u
81 /* upper bound of full table scan */
82 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
83 /* desired ratio of entries found to be expired */
84 #define GC_EVICT_RATIO 50u
86 static struct conntrack_gc_work conntrack_gc_work;
88 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
90 /* 1) Acquire the lock */
93 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
94 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
96 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
99 /* fast path failed, unlock */
102 /* Slow path 1) get global lock */
103 spin_lock(&nf_conntrack_locks_all_lock);
105 /* Slow path 2) get the lock we want */
108 /* Slow path 3) release the global lock */
109 spin_unlock(&nf_conntrack_locks_all_lock);
111 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
113 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
115 h1 %= CONNTRACK_LOCKS;
116 h2 %= CONNTRACK_LOCKS;
117 spin_unlock(&nf_conntrack_locks[h1]);
119 spin_unlock(&nf_conntrack_locks[h2]);
122 /* return true if we need to recompute hashes (in case hash table was resized) */
123 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
124 unsigned int h2, unsigned int sequence)
126 h1 %= CONNTRACK_LOCKS;
127 h2 %= CONNTRACK_LOCKS;
129 nf_conntrack_lock(&nf_conntrack_locks[h1]);
131 spin_lock_nested(&nf_conntrack_locks[h2],
132 SINGLE_DEPTH_NESTING);
134 nf_conntrack_lock(&nf_conntrack_locks[h2]);
135 spin_lock_nested(&nf_conntrack_locks[h1],
136 SINGLE_DEPTH_NESTING);
138 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
139 nf_conntrack_double_unlock(h1, h2);
145 static void nf_conntrack_all_lock(void)
149 spin_lock(&nf_conntrack_locks_all_lock);
151 nf_conntrack_locks_all = true;
153 for (i = 0; i < CONNTRACK_LOCKS; i++) {
154 spin_lock(&nf_conntrack_locks[i]);
156 /* This spin_unlock provides the "release" to ensure that
157 * nf_conntrack_locks_all==true is visible to everyone that
158 * acquired spin_lock(&nf_conntrack_locks[]).
160 spin_unlock(&nf_conntrack_locks[i]);
164 static void nf_conntrack_all_unlock(void)
166 /* All prior stores must be complete before we clear
167 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
168 * might observe the false value but not the entire
170 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
172 smp_store_release(&nf_conntrack_locks_all, false);
173 spin_unlock(&nf_conntrack_locks_all_lock);
176 unsigned int nf_conntrack_htable_size __read_mostly;
177 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
179 unsigned int nf_conntrack_max __read_mostly;
180 EXPORT_SYMBOL_GPL(nf_conntrack_max);
181 seqcount_t nf_conntrack_generation __read_mostly;
182 static unsigned int nf_conntrack_hash_rnd __read_mostly;
184 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
185 const struct net *net)
190 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
192 /* The direction must be ignored, so we hash everything up to the
193 * destination ports (which is a multiple of 4) and treat the last
194 * three bytes manually.
196 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
197 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
198 return jhash2((u32 *)tuple, n, seed ^
199 (((__force __u16)tuple->dst.u.all << 16) |
200 tuple->dst.protonum));
203 static u32 scale_hash(u32 hash)
205 return reciprocal_scale(hash, nf_conntrack_htable_size);
208 static u32 __hash_conntrack(const struct net *net,
209 const struct nf_conntrack_tuple *tuple,
212 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
215 static u32 hash_conntrack(const struct net *net,
216 const struct nf_conntrack_tuple *tuple)
218 return scale_hash(hash_conntrack_raw(tuple, net));
221 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
222 unsigned int dataoff,
223 struct nf_conntrack_tuple *tuple)
227 } _inet_hdr, *inet_hdr;
229 /* Actually only need first 4 bytes to get ports. */
230 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
234 tuple->src.u.udp.port = inet_hdr->sport;
235 tuple->dst.u.udp.port = inet_hdr->dport;
240 nf_ct_get_tuple(const struct sk_buff *skb,
242 unsigned int dataoff,
246 struct nf_conntrack_tuple *tuple)
252 memset(tuple, 0, sizeof(*tuple));
254 tuple->src.l3num = l3num;
257 nhoff += offsetof(struct iphdr, saddr);
258 size = 2 * sizeof(__be32);
261 nhoff += offsetof(struct ipv6hdr, saddr);
262 size = sizeof(_addrs);
268 ap = skb_header_pointer(skb, nhoff, size, _addrs);
274 tuple->src.u3.ip = ap[0];
275 tuple->dst.u3.ip = ap[1];
278 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
279 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
283 tuple->dst.protonum = protonum;
284 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
287 #if IS_ENABLED(CONFIG_IPV6)
289 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
292 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
293 #ifdef CONFIG_NF_CT_PROTO_GRE
295 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
298 case IPPROTO_UDP: /* fallthrough */
299 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
300 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
301 case IPPROTO_UDPLITE:
302 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
304 #ifdef CONFIG_NF_CT_PROTO_SCTP
306 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
308 #ifdef CONFIG_NF_CT_PROTO_DCCP
310 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
319 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
323 const struct iphdr *iph;
326 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
330 /* Conntrack defragments packets, we might still see fragments
331 * inside ICMP packets though.
333 if (iph->frag_off & htons(IP_OFFSET))
336 dataoff = nhoff + (iph->ihl << 2);
337 *protonum = iph->protocol;
339 /* Check bogus IP headers */
340 if (dataoff > skb->len) {
341 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
342 nhoff, iph->ihl << 2, skb->len);
348 #if IS_ENABLED(CONFIG_IPV6)
349 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
353 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
357 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
358 &nexthdr, sizeof(nexthdr)) != 0) {
359 pr_debug("can't get nexthdr\n");
362 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
364 * (protoff == skb->len) means the packet has not data, just
365 * IPv6 and possibly extensions headers, but it is tracked anyway
367 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
368 pr_debug("can't find proto in pkt\n");
377 static int get_l4proto(const struct sk_buff *skb,
378 unsigned int nhoff, u8 pf, u8 *l4num)
382 return ipv4_get_l4proto(skb, nhoff, l4num);
383 #if IS_ENABLED(CONFIG_IPV6)
385 return ipv6_get_l4proto(skb, nhoff, l4num);
394 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
396 struct net *net, struct nf_conntrack_tuple *tuple)
401 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
405 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
407 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
410 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
411 const struct nf_conntrack_tuple *orig)
413 memset(inverse, 0, sizeof(*inverse));
415 inverse->src.l3num = orig->src.l3num;
417 switch (orig->src.l3num) {
419 inverse->src.u3.ip = orig->dst.u3.ip;
420 inverse->dst.u3.ip = orig->src.u3.ip;
423 inverse->src.u3.in6 = orig->dst.u3.in6;
424 inverse->dst.u3.in6 = orig->src.u3.in6;
430 inverse->dst.dir = !orig->dst.dir;
432 inverse->dst.protonum = orig->dst.protonum;
434 switch (orig->dst.protonum) {
436 return nf_conntrack_invert_icmp_tuple(inverse, orig);
437 #if IS_ENABLED(CONFIG_IPV6)
439 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
443 inverse->src.u.all = orig->dst.u.all;
444 inverse->dst.u.all = orig->src.u.all;
447 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
449 /* Generate a almost-unique pseudo-id for a given conntrack.
451 * intentionally doesn't re-use any of the seeds used for hash
452 * table location, we assume id gets exposed to userspace.
454 * Following nf_conn items do not change throughout lifetime
458 * 2. nf_conn->master address (normally NULL)
459 * 3. the associated net namespace
460 * 4. the original direction tuple
462 u32 nf_ct_get_id(const struct nf_conn *ct)
464 static __read_mostly siphash_key_t ct_id_seed;
465 unsigned long a, b, c, d;
467 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
469 a = (unsigned long)ct;
470 b = (unsigned long)ct->master;
471 c = (unsigned long)nf_ct_net(ct);
472 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
473 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
476 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
478 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
481 EXPORT_SYMBOL_GPL(nf_ct_get_id);
484 clean_from_lists(struct nf_conn *ct)
486 pr_debug("clean_from_lists(%p)\n", ct);
487 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
488 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
490 /* Destroy all pending expectations */
491 nf_ct_remove_expectations(ct);
494 /* must be called with local_bh_disable */
495 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
497 struct ct_pcpu *pcpu;
499 /* add this conntrack to the (per cpu) dying list */
500 ct->cpu = smp_processor_id();
501 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
503 spin_lock(&pcpu->lock);
504 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
506 spin_unlock(&pcpu->lock);
509 /* must be called with local_bh_disable */
510 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
512 struct ct_pcpu *pcpu;
514 /* add this conntrack to the (per cpu) unconfirmed list */
515 ct->cpu = smp_processor_id();
516 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
518 spin_lock(&pcpu->lock);
519 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
521 spin_unlock(&pcpu->lock);
524 /* must be called with local_bh_disable */
525 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
527 struct ct_pcpu *pcpu;
529 /* We overload first tuple to link into unconfirmed or dying list.*/
530 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
532 spin_lock(&pcpu->lock);
533 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
534 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
535 spin_unlock(&pcpu->lock);
538 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
540 /* Released via destroy_conntrack() */
541 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
542 const struct nf_conntrack_zone *zone,
545 struct nf_conn *tmpl, *p;
547 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
548 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
553 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
555 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
556 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
559 tmpl = kzalloc(sizeof(*tmpl), flags);
564 tmpl->status = IPS_TEMPLATE;
565 write_pnet(&tmpl->ct_net, net);
566 nf_ct_zone_add(tmpl, zone);
567 atomic_set(&tmpl->ct_general.use, 0);
571 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
573 void nf_ct_tmpl_free(struct nf_conn *tmpl)
575 nf_ct_ext_destroy(tmpl);
576 nf_ct_ext_free(tmpl);
578 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
579 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
583 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
585 static void destroy_gre_conntrack(struct nf_conn *ct)
587 #ifdef CONFIG_NF_CT_PROTO_GRE
588 struct nf_conn *master = ct->master;
591 nf_ct_gre_keymap_destroy(master);
596 destroy_conntrack(struct nf_conntrack *nfct)
598 struct nf_conn *ct = (struct nf_conn *)nfct;
600 pr_debug("destroy_conntrack(%p)\n", ct);
601 WARN_ON(atomic_read(&nfct->use) != 0);
603 if (unlikely(nf_ct_is_template(ct))) {
608 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
609 destroy_gre_conntrack(ct);
612 /* Expectations will have been removed in clean_from_lists,
613 * except TFTP can create an expectation on the first packet,
614 * before connection is in the list, so we need to clean here,
617 nf_ct_remove_expectations(ct);
619 nf_ct_del_from_dying_or_unconfirmed_list(ct);
624 nf_ct_put(ct->master);
626 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
627 nf_conntrack_free(ct);
630 static void nf_ct_delete_from_lists(struct nf_conn *ct)
632 struct net *net = nf_ct_net(ct);
633 unsigned int hash, reply_hash;
634 unsigned int sequence;
636 nf_ct_helper_destroy(ct);
640 sequence = read_seqcount_begin(&nf_conntrack_generation);
641 hash = hash_conntrack(net,
642 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
643 reply_hash = hash_conntrack(net,
644 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
645 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
647 clean_from_lists(ct);
648 nf_conntrack_double_unlock(hash, reply_hash);
650 nf_ct_add_to_dying_list(ct);
655 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
657 struct nf_conn_tstamp *tstamp;
659 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
662 tstamp = nf_conn_tstamp_find(ct);
663 if (tstamp && tstamp->stop == 0)
664 tstamp->stop = ktime_get_real_ns();
666 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
667 portid, report) < 0) {
668 /* destroy event was not delivered. nf_ct_put will
669 * be done by event cache worker on redelivery.
671 nf_ct_delete_from_lists(ct);
672 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
676 nf_conntrack_ecache_work(nf_ct_net(ct));
677 nf_ct_delete_from_lists(ct);
681 EXPORT_SYMBOL_GPL(nf_ct_delete);
684 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
685 const struct nf_conntrack_tuple *tuple,
686 const struct nf_conntrack_zone *zone,
687 const struct net *net)
689 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
691 /* A conntrack can be recreated with the equal tuple,
692 * so we need to check that the conntrack is confirmed
694 return nf_ct_tuple_equal(tuple, &h->tuple) &&
695 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
696 nf_ct_is_confirmed(ct) &&
697 net_eq(net, nf_ct_net(ct));
701 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
703 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
704 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
705 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
706 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
707 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
708 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
709 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
712 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
713 static void nf_ct_gc_expired(struct nf_conn *ct)
715 if (!atomic_inc_not_zero(&ct->ct_general.use))
718 if (nf_ct_should_gc(ct))
726 * - Caller must take a reference on returned object
727 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
729 static struct nf_conntrack_tuple_hash *
730 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
731 const struct nf_conntrack_tuple *tuple, u32 hash)
733 struct nf_conntrack_tuple_hash *h;
734 struct hlist_nulls_head *ct_hash;
735 struct hlist_nulls_node *n;
736 unsigned int bucket, hsize;
739 nf_conntrack_get_ht(&ct_hash, &hsize);
740 bucket = reciprocal_scale(hash, hsize);
742 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
745 ct = nf_ct_tuplehash_to_ctrack(h);
746 if (nf_ct_is_expired(ct)) {
747 nf_ct_gc_expired(ct);
751 if (nf_ct_key_equal(h, tuple, zone, net))
755 * if the nulls value we got at the end of this lookup is
756 * not the expected one, we must restart lookup.
757 * We probably met an item that was moved to another chain.
759 if (get_nulls_value(n) != bucket) {
760 NF_CT_STAT_INC_ATOMIC(net, search_restart);
767 /* Find a connection corresponding to a tuple. */
768 static struct nf_conntrack_tuple_hash *
769 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
770 const struct nf_conntrack_tuple *tuple, u32 hash)
772 struct nf_conntrack_tuple_hash *h;
777 h = ____nf_conntrack_find(net, zone, tuple, hash);
779 /* We have a candidate that matches the tuple we're interested
780 * in, try to obtain a reference and re-check tuple
782 ct = nf_ct_tuplehash_to_ctrack(h);
783 if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
784 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
787 /* TYPESAFE_BY_RCU recycled the candidate */
799 struct nf_conntrack_tuple_hash *
800 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
801 const struct nf_conntrack_tuple *tuple)
803 return __nf_conntrack_find_get(net, zone, tuple,
804 hash_conntrack_raw(tuple, net));
806 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
808 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
810 unsigned int reply_hash)
812 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
813 &nf_conntrack_hash[hash]);
814 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
815 &nf_conntrack_hash[reply_hash]);
819 nf_conntrack_hash_check_insert(struct nf_conn *ct)
821 const struct nf_conntrack_zone *zone;
822 struct net *net = nf_ct_net(ct);
823 unsigned int hash, reply_hash;
824 struct nf_conntrack_tuple_hash *h;
825 struct hlist_nulls_node *n;
826 unsigned int sequence;
828 zone = nf_ct_zone(ct);
832 sequence = read_seqcount_begin(&nf_conntrack_generation);
833 hash = hash_conntrack(net,
834 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
835 reply_hash = hash_conntrack(net,
836 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
837 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
839 /* See if there's one in the list already, including reverse */
840 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
841 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
845 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
846 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
851 /* The caller holds a reference to this object */
852 atomic_set(&ct->ct_general.use, 2);
853 __nf_conntrack_hash_insert(ct, hash, reply_hash);
854 nf_conntrack_double_unlock(hash, reply_hash);
855 NF_CT_STAT_INC(net, insert);
860 nf_conntrack_double_unlock(hash, reply_hash);
861 NF_CT_STAT_INC(net, insert_failed);
865 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
867 static inline void nf_ct_acct_update(struct nf_conn *ct,
868 enum ip_conntrack_info ctinfo,
871 struct nf_conn_acct *acct;
873 acct = nf_conn_acct_find(ct);
875 struct nf_conn_counter *counter = acct->counter;
877 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
878 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
882 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
883 const struct nf_conn *loser_ct)
885 struct nf_conn_acct *acct;
887 acct = nf_conn_acct_find(loser_ct);
889 struct nf_conn_counter *counter = acct->counter;
892 /* u32 should be fine since we must have seen one packet. */
893 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
894 nf_ct_acct_update(ct, ctinfo, bytes);
898 /* Resolve race on insertion if this protocol allows this. */
899 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
900 enum ip_conntrack_info ctinfo,
901 struct nf_conntrack_tuple_hash *h)
903 /* This is the conntrack entry already in hashes that won race. */
904 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
905 const struct nf_conntrack_l4proto *l4proto;
906 enum ip_conntrack_info oldinfo;
907 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
909 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
910 if (l4proto->allow_clash &&
911 !nf_ct_is_dying(ct) &&
912 atomic_inc_not_zero(&ct->ct_general.use)) {
913 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
914 nf_ct_match(ct, loser_ct)) {
915 nf_ct_acct_merge(ct, ctinfo, loser_ct);
916 nf_conntrack_put(&loser_ct->ct_general);
917 nf_ct_set(skb, ct, oldinfo);
922 NF_CT_STAT_INC(net, drop);
926 /* Confirm a connection given skb; places it in hash table */
928 __nf_conntrack_confirm(struct sk_buff *skb)
930 const struct nf_conntrack_zone *zone;
931 unsigned int hash, reply_hash;
932 struct nf_conntrack_tuple_hash *h;
934 struct nf_conn_help *help;
935 struct nf_conn_tstamp *tstamp;
936 struct hlist_nulls_node *n;
937 enum ip_conntrack_info ctinfo;
939 unsigned int sequence;
942 ct = nf_ct_get(skb, &ctinfo);
945 /* ipt_REJECT uses nf_conntrack_attach to attach related
946 ICMP/TCP RST packets in other direction. Actual packet
947 which created connection will be IP_CT_NEW or for an
948 expected connection, IP_CT_RELATED. */
949 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
952 zone = nf_ct_zone(ct);
956 sequence = read_seqcount_begin(&nf_conntrack_generation);
957 /* reuse the hash saved before */
958 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
959 hash = scale_hash(hash);
960 reply_hash = hash_conntrack(net,
961 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
963 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
965 /* We're not in hash table, and we refuse to set up related
966 * connections for unconfirmed conns. But packet copies and
967 * REJECT will give spurious warnings here.
970 /* Another skb with the same unconfirmed conntrack may
971 * win the race. This may happen for bridge(br_flood)
972 * or broadcast/multicast packets do skb_clone with
973 * unconfirmed conntrack.
975 if (unlikely(nf_ct_is_confirmed(ct))) {
977 nf_conntrack_double_unlock(hash, reply_hash);
982 pr_debug("Confirming conntrack %p\n", ct);
983 /* We have to check the DYING flag after unlink to prevent
984 * a race against nf_ct_get_next_corpse() possibly called from
985 * user context, else we insert an already 'dead' hash, blocking
986 * further use of that particular connection -JM.
988 nf_ct_del_from_dying_or_unconfirmed_list(ct);
990 if (unlikely(nf_ct_is_dying(ct))) {
991 nf_ct_add_to_dying_list(ct);
995 /* See if there's one in the list already, including reverse:
996 NAT could have grabbed it without realizing, since we're
997 not in the hash. If there is, we lost race. */
998 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
999 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1003 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
1004 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1008 /* Timer relative to confirmation time, not original
1009 setting time, otherwise we'd get timer wrap in
1010 weird delay cases. */
1011 ct->timeout += nfct_time_stamp;
1012 atomic_inc(&ct->ct_general.use);
1013 ct->status |= IPS_CONFIRMED;
1015 /* set conntrack timestamp, if enabled. */
1016 tstamp = nf_conn_tstamp_find(ct);
1018 tstamp->start = ktime_get_real_ns();
1020 /* Since the lookup is lockless, hash insertion must be done after
1021 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1022 * guarantee that no other CPU can find the conntrack before the above
1023 * stores are visible.
1025 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1026 nf_conntrack_double_unlock(hash, reply_hash);
1029 help = nfct_help(ct);
1030 if (help && help->helper)
1031 nf_conntrack_event_cache(IPCT_HELPER, ct);
1033 nf_conntrack_event_cache(master_ct(ct) ?
1034 IPCT_RELATED : IPCT_NEW, ct);
1038 nf_ct_add_to_dying_list(ct);
1039 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
1041 nf_conntrack_double_unlock(hash, reply_hash);
1042 NF_CT_STAT_INC(net, insert_failed);
1046 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1048 /* Returns true if a connection correspondings to the tuple (required
1051 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1052 const struct nf_conn *ignored_conntrack)
1054 struct net *net = nf_ct_net(ignored_conntrack);
1055 const struct nf_conntrack_zone *zone;
1056 struct nf_conntrack_tuple_hash *h;
1057 struct hlist_nulls_head *ct_hash;
1058 unsigned int hash, hsize;
1059 struct hlist_nulls_node *n;
1062 zone = nf_ct_zone(ignored_conntrack);
1066 nf_conntrack_get_ht(&ct_hash, &hsize);
1067 hash = __hash_conntrack(net, tuple, hsize);
1069 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1070 ct = nf_ct_tuplehash_to_ctrack(h);
1072 if (ct == ignored_conntrack)
1075 if (nf_ct_is_expired(ct)) {
1076 nf_ct_gc_expired(ct);
1080 if (nf_ct_key_equal(h, tuple, zone, net)) {
1081 /* Tuple is taken already, so caller will need to find
1082 * a new source port to use.
1085 * If the *original tuples* are identical, then both
1086 * conntracks refer to the same flow.
1087 * This is a rare situation, it can occur e.g. when
1088 * more than one UDP packet is sent from same socket
1089 * in different threads.
1091 * Let nf_ct_resolve_clash() deal with this later.
1093 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1094 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple))
1097 NF_CT_STAT_INC_ATOMIC(net, found);
1103 if (get_nulls_value(n) != hash) {
1104 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1112 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1114 #define NF_CT_EVICTION_RANGE 8
1116 /* There's a small race here where we may free a just-assured
1117 connection. Too bad: we're in trouble anyway. */
1118 static unsigned int early_drop_list(struct net *net,
1119 struct hlist_nulls_head *head)
1121 struct nf_conntrack_tuple_hash *h;
1122 struct hlist_nulls_node *n;
1123 unsigned int drops = 0;
1124 struct nf_conn *tmp;
1126 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1127 tmp = nf_ct_tuplehash_to_ctrack(h);
1129 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1132 if (nf_ct_is_expired(tmp)) {
1133 nf_ct_gc_expired(tmp);
1137 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1138 !net_eq(nf_ct_net(tmp), net) ||
1139 nf_ct_is_dying(tmp))
1142 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1145 /* kill only if still in same netns -- might have moved due to
1146 * SLAB_TYPESAFE_BY_RCU rules.
1148 * We steal the timer reference. If that fails timer has
1149 * already fired or someone else deleted it. Just drop ref
1150 * and move to next entry.
1152 if (net_eq(nf_ct_net(tmp), net) &&
1153 nf_ct_is_confirmed(tmp) &&
1154 nf_ct_delete(tmp, 0, 0))
1163 static noinline int early_drop(struct net *net, unsigned int hash)
1165 unsigned int i, bucket;
1167 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1168 struct hlist_nulls_head *ct_hash;
1169 unsigned int hsize, drops;
1172 nf_conntrack_get_ht(&ct_hash, &hsize);
1174 bucket = reciprocal_scale(hash, hsize);
1176 bucket = (bucket + 1) % hsize;
1178 drops = early_drop_list(net, &ct_hash[bucket]);
1182 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1190 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1192 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1195 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1197 const struct nf_conntrack_l4proto *l4proto;
1199 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1202 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1203 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1209 #define DAY (86400 * HZ)
1211 /* Set an arbitrary timeout large enough not to ever expire, this save
1212 * us a check for the IPS_OFFLOAD_BIT from the packet path via
1213 * nf_ct_is_expired().
1215 static void nf_ct_offload_timeout(struct nf_conn *ct)
1217 if (nf_ct_expires(ct) < DAY / 2)
1218 ct->timeout = nfct_time_stamp + DAY;
1221 static void gc_worker(struct work_struct *work)
1223 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
1224 unsigned int i, goal, buckets = 0, expired_count = 0;
1225 unsigned int nf_conntrack_max95 = 0;
1226 struct conntrack_gc_work *gc_work;
1227 unsigned int ratio, scanned = 0;
1228 unsigned long next_run;
1230 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1232 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
1233 i = gc_work->last_bucket;
1234 if (gc_work->early_drop)
1235 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1238 struct nf_conntrack_tuple_hash *h;
1239 struct hlist_nulls_head *ct_hash;
1240 struct hlist_nulls_node *n;
1241 unsigned int hashsz;
1242 struct nf_conn *tmp;
1247 nf_conntrack_get_ht(&ct_hash, &hashsz);
1251 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1254 tmp = nf_ct_tuplehash_to_ctrack(h);
1257 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1258 nf_ct_offload_timeout(tmp);
1262 if (nf_ct_is_expired(tmp)) {
1263 nf_ct_gc_expired(tmp);
1268 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1271 net = nf_ct_net(tmp);
1272 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1275 /* need to take reference to avoid possible races */
1276 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1279 if (gc_worker_skip_ct(tmp)) {
1284 if (gc_worker_can_early_drop(tmp))
1290 /* could check get_nulls_value() here and restart if ct
1291 * was moved to another chain. But given gc is best-effort
1292 * we will just continue with next hash slot.
1296 } while (++buckets < goal);
1298 if (gc_work->exiting)
1302 * Eviction will normally happen from the packet path, and not
1303 * from this gc worker.
1305 * This worker is only here to reap expired entries when system went
1306 * idle after a busy period.
1308 * The heuristics below are supposed to balance conflicting goals:
1310 * 1. Minimize time until we notice a stale entry
1311 * 2. Maximize scan intervals to not waste cycles
1313 * Normally, expire ratio will be close to 0.
1315 * As soon as a sizeable fraction of the entries have expired
1316 * increase scan frequency.
1318 ratio = scanned ? expired_count * 100 / scanned : 0;
1319 if (ratio > GC_EVICT_RATIO) {
1320 gc_work->next_gc_run = min_interval;
1322 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1324 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1326 gc_work->next_gc_run += min_interval;
1327 if (gc_work->next_gc_run > max)
1328 gc_work->next_gc_run = max;
1331 next_run = gc_work->next_gc_run;
1332 gc_work->last_bucket = i;
1333 gc_work->early_drop = false;
1334 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1337 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1339 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1340 gc_work->next_gc_run = HZ;
1341 gc_work->exiting = false;
1344 static struct nf_conn *
1345 __nf_conntrack_alloc(struct net *net,
1346 const struct nf_conntrack_zone *zone,
1347 const struct nf_conntrack_tuple *orig,
1348 const struct nf_conntrack_tuple *repl,
1349 gfp_t gfp, u32 hash)
1353 /* We don't want any race condition at early drop stage */
1354 atomic_inc(&net->ct.count);
1356 if (nf_conntrack_max &&
1357 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1358 if (!early_drop(net, hash)) {
1359 if (!conntrack_gc_work.early_drop)
1360 conntrack_gc_work.early_drop = true;
1361 atomic_dec(&net->ct.count);
1362 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1363 return ERR_PTR(-ENOMEM);
1368 * Do not use kmem_cache_zalloc(), as this cache uses
1369 * SLAB_TYPESAFE_BY_RCU.
1371 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1375 spin_lock_init(&ct->lock);
1376 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1377 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1378 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1379 /* save hash for reusing when confirming */
1380 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1383 write_pnet(&ct->ct_net, net);
1384 memset(&ct->__nfct_init_offset[0], 0,
1385 offsetof(struct nf_conn, proto) -
1386 offsetof(struct nf_conn, __nfct_init_offset[0]));
1388 nf_ct_zone_add(ct, zone);
1390 /* Because we use RCU lookups, we set ct_general.use to zero before
1391 * this is inserted in any list.
1393 atomic_set(&ct->ct_general.use, 0);
1396 atomic_dec(&net->ct.count);
1397 return ERR_PTR(-ENOMEM);
1400 struct nf_conn *nf_conntrack_alloc(struct net *net,
1401 const struct nf_conntrack_zone *zone,
1402 const struct nf_conntrack_tuple *orig,
1403 const struct nf_conntrack_tuple *repl,
1406 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1408 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1410 void nf_conntrack_free(struct nf_conn *ct)
1412 struct net *net = nf_ct_net(ct);
1414 /* A freed object has refcnt == 0, that's
1415 * the golden rule for SLAB_TYPESAFE_BY_RCU
1417 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1419 nf_ct_ext_destroy(ct);
1421 kmem_cache_free(nf_conntrack_cachep, ct);
1422 smp_mb__before_atomic();
1423 atomic_dec(&net->ct.count);
1425 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1428 /* Allocate a new conntrack: we return -ENOMEM if classification
1429 failed due to stress. Otherwise it really is unclassifiable. */
1430 static noinline struct nf_conntrack_tuple_hash *
1431 init_conntrack(struct net *net, struct nf_conn *tmpl,
1432 const struct nf_conntrack_tuple *tuple,
1433 struct sk_buff *skb,
1434 unsigned int dataoff, u32 hash)
1437 struct nf_conn_help *help;
1438 struct nf_conntrack_tuple repl_tuple;
1439 struct nf_conntrack_ecache *ecache;
1440 struct nf_conntrack_expect *exp = NULL;
1441 const struct nf_conntrack_zone *zone;
1442 struct nf_conn_timeout *timeout_ext;
1443 struct nf_conntrack_zone tmp;
1445 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1446 pr_debug("Can't invert tuple.\n");
1450 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1451 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1454 return (struct nf_conntrack_tuple_hash *)ct;
1456 if (!nf_ct_add_synproxy(ct, tmpl)) {
1457 nf_conntrack_free(ct);
1458 return ERR_PTR(-ENOMEM);
1461 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1464 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1467 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1468 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1469 nf_ct_labels_ext_add(ct);
1471 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1472 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1473 ecache ? ecache->expmask : 0,
1477 if (net->ct.expect_count) {
1478 spin_lock(&nf_conntrack_expect_lock);
1479 exp = nf_ct_find_expectation(net, zone, tuple);
1481 pr_debug("expectation arrives ct=%p exp=%p\n",
1483 /* Welcome, Mr. Bond. We've been expecting you... */
1484 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1485 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1486 ct->master = exp->master;
1488 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1490 rcu_assign_pointer(help->helper, exp->helper);
1493 #ifdef CONFIG_NF_CONNTRACK_MARK
1494 ct->mark = exp->master->mark;
1496 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1497 ct->secmark = exp->master->secmark;
1499 NF_CT_STAT_INC(net, expect_new);
1501 spin_unlock(&nf_conntrack_expect_lock);
1504 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1506 /* Now it is inserted into the unconfirmed list, bump refcount */
1507 nf_conntrack_get(&ct->ct_general);
1508 nf_ct_add_to_unconfirmed_list(ct);
1514 exp->expectfn(ct, exp);
1515 nf_ct_expect_put(exp);
1518 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1521 /* On success, returns 0, sets skb->_nfct | ctinfo */
1523 resolve_normal_ct(struct nf_conn *tmpl,
1524 struct sk_buff *skb,
1525 unsigned int dataoff,
1527 const struct nf_hook_state *state)
1529 const struct nf_conntrack_zone *zone;
1530 struct nf_conntrack_tuple tuple;
1531 struct nf_conntrack_tuple_hash *h;
1532 enum ip_conntrack_info ctinfo;
1533 struct nf_conntrack_zone tmp;
1537 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1538 dataoff, state->pf, protonum, state->net,
1540 pr_debug("Can't get tuple\n");
1544 /* look for tuple match */
1545 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1546 hash = hash_conntrack_raw(&tuple, state->net);
1547 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1549 h = init_conntrack(state->net, tmpl, &tuple,
1550 skb, dataoff, hash);
1556 ct = nf_ct_tuplehash_to_ctrack(h);
1558 /* It exists; we have (non-exclusive) reference. */
1559 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1560 ctinfo = IP_CT_ESTABLISHED_REPLY;
1562 /* Once we've had two way comms, always ESTABLISHED. */
1563 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1564 pr_debug("normal packet for %p\n", ct);
1565 ctinfo = IP_CT_ESTABLISHED;
1566 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1567 pr_debug("related packet for %p\n", ct);
1568 ctinfo = IP_CT_RELATED;
1570 pr_debug("new packet for %p\n", ct);
1574 nf_ct_set(skb, ct, ctinfo);
1579 * icmp packets need special treatment to handle error messages that are
1580 * related to a connection.
1582 * Callers need to check if skb has a conntrack assigned when this
1583 * helper returns; in such case skb belongs to an already known connection.
1585 static unsigned int __cold
1586 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1587 struct sk_buff *skb,
1588 unsigned int dataoff,
1590 const struct nf_hook_state *state)
1594 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1595 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1596 #if IS_ENABLED(CONFIG_IPV6)
1597 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1598 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1604 NF_CT_STAT_INC_ATOMIC(state->net, error);
1605 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1611 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1612 enum ip_conntrack_info ctinfo)
1614 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1617 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1619 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1623 /* Returns verdict for packet, or -1 for invalid. */
1624 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1625 struct sk_buff *skb,
1626 unsigned int dataoff,
1627 enum ip_conntrack_info ctinfo,
1628 const struct nf_hook_state *state)
1630 switch (nf_ct_protonum(ct)) {
1632 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1635 return nf_conntrack_udp_packet(ct, skb, dataoff,
1638 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1639 #if IS_ENABLED(CONFIG_IPV6)
1640 case IPPROTO_ICMPV6:
1641 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1643 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1644 case IPPROTO_UDPLITE:
1645 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1648 #ifdef CONFIG_NF_CT_PROTO_SCTP
1650 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1653 #ifdef CONFIG_NF_CT_PROTO_DCCP
1655 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1658 #ifdef CONFIG_NF_CT_PROTO_GRE
1660 return nf_conntrack_gre_packet(ct, skb, dataoff,
1665 return generic_packet(ct, skb, ctinfo);
1669 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1671 enum ip_conntrack_info ctinfo;
1672 struct nf_conn *ct, *tmpl;
1676 tmpl = nf_ct_get(skb, &ctinfo);
1677 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1678 /* Previously seen (loopback or untracked)? Ignore. */
1679 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1680 ctinfo == IP_CT_UNTRACKED) {
1681 NF_CT_STAT_INC_ATOMIC(state->net, ignore);
1687 /* rcu_read_lock()ed by nf_hook_thresh */
1688 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1690 pr_debug("not prepared to track yet or error occurred\n");
1691 NF_CT_STAT_INC_ATOMIC(state->net, error);
1692 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1697 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1698 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1704 /* ICMP[v6] protocol trackers may assign one conntrack. */
1709 ret = resolve_normal_ct(tmpl, skb, dataoff,
1712 /* Too stressed to deal. */
1713 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1718 ct = nf_ct_get(skb, &ctinfo);
1720 /* Not valid part of a connection */
1721 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1726 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1728 /* Invalid: inverse of the return code tells
1729 * the netfilter core what to do */
1730 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1731 nf_conntrack_put(&ct->ct_general);
1733 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1734 if (ret == -NF_DROP)
1735 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1736 /* Special case: TCP tracker reports an attempt to reopen a
1737 * closed/aborted connection. We have to go back and create a
1740 if (ret == -NF_REPEAT)
1746 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1747 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1748 nf_conntrack_event_cache(IPCT_REPLY, ct);
1755 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1757 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1758 implicitly racy: see __nf_conntrack_confirm */
1759 void nf_conntrack_alter_reply(struct nf_conn *ct,
1760 const struct nf_conntrack_tuple *newreply)
1762 struct nf_conn_help *help = nfct_help(ct);
1764 /* Should be unconfirmed, so not in hash table yet */
1765 WARN_ON(nf_ct_is_confirmed(ct));
1767 pr_debug("Altering reply tuple of %p to ", ct);
1768 nf_ct_dump_tuple(newreply);
1770 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1771 if (ct->master || (help && !hlist_empty(&help->expectations)))
1775 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1778 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1780 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1781 void __nf_ct_refresh_acct(struct nf_conn *ct,
1782 enum ip_conntrack_info ctinfo,
1783 const struct sk_buff *skb,
1787 /* Only update if this is not a fixed timeout */
1788 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1791 /* If not in hash table, timer will not be active yet */
1792 if (nf_ct_is_confirmed(ct))
1793 extra_jiffies += nfct_time_stamp;
1795 if (READ_ONCE(ct->timeout) != extra_jiffies)
1796 WRITE_ONCE(ct->timeout, extra_jiffies);
1799 nf_ct_acct_update(ct, ctinfo, skb->len);
1801 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1803 bool nf_ct_kill_acct(struct nf_conn *ct,
1804 enum ip_conntrack_info ctinfo,
1805 const struct sk_buff *skb)
1807 nf_ct_acct_update(ct, ctinfo, skb->len);
1809 return nf_ct_delete(ct, 0, 0);
1811 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1813 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1815 #include <linux/netfilter/nfnetlink.h>
1816 #include <linux/netfilter/nfnetlink_conntrack.h>
1817 #include <linux/mutex.h>
1819 /* Generic function for tcp/udp/sctp/dccp and alike. */
1820 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1821 const struct nf_conntrack_tuple *tuple)
1823 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1824 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1825 goto nla_put_failure;
1831 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1833 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1834 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1835 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1837 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1839 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1840 struct nf_conntrack_tuple *t)
1842 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1845 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1846 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1850 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1852 unsigned int nf_ct_port_nlattr_tuple_size(void)
1854 static unsigned int size __read_mostly;
1857 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1861 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1864 /* Used by ipt_REJECT and ip6t_REJECT. */
1865 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1868 enum ip_conntrack_info ctinfo;
1870 /* This ICMP is in reverse direction to the packet which caused it */
1871 ct = nf_ct_get(skb, &ctinfo);
1872 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1873 ctinfo = IP_CT_RELATED_REPLY;
1875 ctinfo = IP_CT_RELATED;
1877 /* Attach to new skbuff, and increment count */
1878 nf_ct_set(nskb, ct, ctinfo);
1879 nf_conntrack_get(skb_nfct(nskb));
1882 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1884 struct nf_conntrack_tuple_hash *h;
1885 struct nf_conntrack_tuple tuple;
1886 enum ip_conntrack_info ctinfo;
1887 struct nf_nat_hook *nat_hook;
1888 unsigned int status;
1894 ct = nf_ct_get(skb, &ctinfo);
1895 if (!ct || nf_ct_is_confirmed(ct))
1898 l3num = nf_ct_l3num(ct);
1900 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
1904 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1905 l4num, net, &tuple))
1908 if (ct->status & IPS_SRC_NAT) {
1909 memcpy(tuple.src.u3.all,
1910 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1911 sizeof(tuple.src.u3.all));
1913 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1916 if (ct->status & IPS_DST_NAT) {
1917 memcpy(tuple.dst.u3.all,
1918 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1919 sizeof(tuple.dst.u3.all));
1921 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1924 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1928 /* Store status bits of the conntrack that is clashing to re-do NAT
1929 * mangling according to what it has been done already to this packet.
1931 status = ct->status;
1934 ct = nf_ct_tuplehash_to_ctrack(h);
1935 nf_ct_set(skb, ct, ctinfo);
1937 nat_hook = rcu_dereference(nf_nat_hook);
1941 if (status & IPS_SRC_NAT &&
1942 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1943 IP_CT_DIR_ORIGINAL) == NF_DROP)
1946 if (status & IPS_DST_NAT &&
1947 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1948 IP_CT_DIR_ORIGINAL) == NF_DROP)
1954 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
1955 const struct sk_buff *skb)
1957 const struct nf_conntrack_tuple *src_tuple;
1958 const struct nf_conntrack_tuple_hash *hash;
1959 struct nf_conntrack_tuple srctuple;
1960 enum ip_conntrack_info ctinfo;
1963 ct = nf_ct_get(skb, &ctinfo);
1965 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
1966 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1970 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
1971 NFPROTO_IPV4, dev_net(skb->dev),
1975 hash = nf_conntrack_find_get(dev_net(skb->dev),
1981 ct = nf_ct_tuplehash_to_ctrack(hash);
1982 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
1983 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1989 /* Bring out ya dead! */
1990 static struct nf_conn *
1991 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1992 void *data, unsigned int *bucket)
1994 struct nf_conntrack_tuple_hash *h;
1996 struct hlist_nulls_node *n;
1999 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2000 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2002 nf_conntrack_lock(lockp);
2003 if (*bucket < nf_conntrack_htable_size) {
2004 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
2005 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
2007 ct = nf_ct_tuplehash_to_ctrack(h);
2019 atomic_inc(&ct->ct_general.use);
2025 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2026 void *data, u32 portid, int report)
2028 unsigned int bucket = 0, sequence;
2034 sequence = read_seqcount_begin(&nf_conntrack_generation);
2036 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2037 /* Time to push up daises... */
2039 nf_ct_delete(ct, portid, report);
2044 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2051 int (*iter)(struct nf_conn *i, void *data);
2056 static int iter_net_only(struct nf_conn *i, void *data)
2058 struct iter_data *d = data;
2060 if (!net_eq(d->net, nf_ct_net(i)))
2063 return d->iter(i, d->data);
2067 __nf_ct_unconfirmed_destroy(struct net *net)
2071 for_each_possible_cpu(cpu) {
2072 struct nf_conntrack_tuple_hash *h;
2073 struct hlist_nulls_node *n;
2074 struct ct_pcpu *pcpu;
2076 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2078 spin_lock_bh(&pcpu->lock);
2079 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2082 ct = nf_ct_tuplehash_to_ctrack(h);
2084 /* we cannot call iter() on unconfirmed list, the
2085 * owning cpu can reallocate ct->ext at any time.
2087 set_bit(IPS_DYING_BIT, &ct->status);
2089 spin_unlock_bh(&pcpu->lock);
2094 void nf_ct_unconfirmed_destroy(struct net *net)
2098 if (atomic_read(&net->ct.count) > 0) {
2099 __nf_ct_unconfirmed_destroy(net);
2100 nf_queue_nf_hook_drop(net);
2104 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2106 void nf_ct_iterate_cleanup_net(struct net *net,
2107 int (*iter)(struct nf_conn *i, void *data),
2108 void *data, u32 portid, int report)
2114 if (atomic_read(&net->ct.count) == 0)
2121 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2123 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2126 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2127 * @iter: callback to invoke for each conntrack
2128 * @data: data to pass to @iter
2130 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2131 * unconfirmed list as dying (so they will not be inserted into
2134 * Can only be called in module exit path.
2137 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2141 down_read(&net_rwsem);
2143 if (atomic_read(&net->ct.count) == 0)
2145 __nf_ct_unconfirmed_destroy(net);
2146 nf_queue_nf_hook_drop(net);
2148 up_read(&net_rwsem);
2150 /* Need to wait for netns cleanup worker to finish, if its
2151 * running -- it might have deleted a net namespace from
2152 * the global list, so our __nf_ct_unconfirmed_destroy() might
2153 * not have affected all namespaces.
2157 /* a conntrack could have been unlinked from unconfirmed list
2158 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2159 * This makes sure its inserted into conntrack table.
2163 nf_ct_iterate_cleanup(iter, data, 0, 0);
2165 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2167 static int kill_all(struct nf_conn *i, void *data)
2169 return net_eq(nf_ct_net(i), data);
2172 void nf_conntrack_cleanup_start(void)
2174 conntrack_gc_work.exiting = true;
2175 RCU_INIT_POINTER(ip_ct_attach, NULL);
2178 void nf_conntrack_cleanup_end(void)
2180 RCU_INIT_POINTER(nf_ct_hook, NULL);
2181 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2182 kvfree(nf_conntrack_hash);
2184 nf_conntrack_proto_fini();
2185 nf_conntrack_seqadj_fini();
2186 nf_conntrack_labels_fini();
2187 nf_conntrack_helper_fini();
2188 nf_conntrack_timeout_fini();
2189 nf_conntrack_ecache_fini();
2190 nf_conntrack_tstamp_fini();
2191 nf_conntrack_acct_fini();
2192 nf_conntrack_expect_fini();
2194 kmem_cache_destroy(nf_conntrack_cachep);
2198 * Mishearing the voices in his head, our hero wonders how he's
2199 * supposed to kill the mall.
2201 void nf_conntrack_cleanup_net(struct net *net)
2205 list_add(&net->exit_list, &single);
2206 nf_conntrack_cleanup_net_list(&single);
2209 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2215 * This makes sure all current packets have passed through
2216 * netfilter framework. Roll on, two-stage module
2222 list_for_each_entry(net, net_exit_list, exit_list) {
2223 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2224 if (atomic_read(&net->ct.count) != 0)
2229 goto i_see_dead_people;
2232 list_for_each_entry(net, net_exit_list, exit_list) {
2233 nf_conntrack_proto_pernet_fini(net);
2234 nf_conntrack_ecache_pernet_fini(net);
2235 nf_conntrack_expect_pernet_fini(net);
2236 free_percpu(net->ct.stat);
2237 free_percpu(net->ct.pcpu_lists);
2241 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2243 struct hlist_nulls_head *hash;
2244 unsigned int nr_slots, i;
2246 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2249 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2250 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2252 hash = kvmalloc_array(nr_slots, sizeof(struct hlist_nulls_head),
2253 GFP_KERNEL | __GFP_ZERO);
2256 for (i = 0; i < nr_slots; i++)
2257 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2261 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2263 int nf_conntrack_hash_resize(unsigned int hashsize)
2266 unsigned int old_size;
2267 struct hlist_nulls_head *hash, *old_hash;
2268 struct nf_conntrack_tuple_hash *h;
2274 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2278 old_size = nf_conntrack_htable_size;
2279 if (old_size == hashsize) {
2285 nf_conntrack_all_lock();
2286 write_seqcount_begin(&nf_conntrack_generation);
2288 /* Lookups in the old hash might happen in parallel, which means we
2289 * might get false negatives during connection lookup. New connections
2290 * created because of a false negative won't make it into the hash
2291 * though since that required taking the locks.
2294 for (i = 0; i < nf_conntrack_htable_size; i++) {
2295 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2296 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2297 struct nf_conntrack_tuple_hash, hnnode);
2298 ct = nf_ct_tuplehash_to_ctrack(h);
2299 hlist_nulls_del_rcu(&h->hnnode);
2300 bucket = __hash_conntrack(nf_ct_net(ct),
2301 &h->tuple, hashsize);
2302 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2305 old_size = nf_conntrack_htable_size;
2306 old_hash = nf_conntrack_hash;
2308 nf_conntrack_hash = hash;
2309 nf_conntrack_htable_size = hashsize;
2311 write_seqcount_end(&nf_conntrack_generation);
2312 nf_conntrack_all_unlock();
2320 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2322 unsigned int hashsize;
2325 if (current->nsproxy->net_ns != &init_net)
2328 /* On boot, we can set this without any fancy locking. */
2329 if (!nf_conntrack_hash)
2330 return param_set_uint(val, kp);
2332 rc = kstrtouint(val, 0, &hashsize);
2336 return nf_conntrack_hash_resize(hashsize);
2338 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2340 static __always_inline unsigned int total_extension_size(void)
2342 /* remember to add new extensions below */
2343 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2345 return sizeof(struct nf_ct_ext) +
2346 sizeof(struct nf_conn_help)
2347 #if IS_ENABLED(CONFIG_NF_NAT)
2348 + sizeof(struct nf_conn_nat)
2350 + sizeof(struct nf_conn_seqadj)
2351 + sizeof(struct nf_conn_acct)
2352 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2353 + sizeof(struct nf_conntrack_ecache)
2355 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2356 + sizeof(struct nf_conn_tstamp)
2358 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2359 + sizeof(struct nf_conn_timeout)
2361 #ifdef CONFIG_NF_CONNTRACK_LABELS
2362 + sizeof(struct nf_conn_labels)
2364 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2365 + sizeof(struct nf_conn_synproxy)
2370 int nf_conntrack_init_start(void)
2372 unsigned long nr_pages = totalram_pages();
2377 /* struct nf_ct_ext uses u8 to store offsets/size */
2378 BUILD_BUG_ON(total_extension_size() > 255u);
2380 seqcount_init(&nf_conntrack_generation);
2382 for (i = 0; i < CONNTRACK_LOCKS; i++)
2383 spin_lock_init(&nf_conntrack_locks[i]);
2385 if (!nf_conntrack_htable_size) {
2386 /* Idea from tcp.c: use 1/16384 of memory.
2387 * On i386: 32MB machine has 512 buckets.
2388 * >= 1GB machines have 16384 buckets.
2389 * >= 4GB machines have 65536 buckets.
2391 nf_conntrack_htable_size
2392 = (((nr_pages << PAGE_SHIFT) / 16384)
2393 / sizeof(struct hlist_head));
2394 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2395 nf_conntrack_htable_size = 65536;
2396 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2397 nf_conntrack_htable_size = 16384;
2398 if (nf_conntrack_htable_size < 32)
2399 nf_conntrack_htable_size = 32;
2401 /* Use a max. factor of four by default to get the same max as
2402 * with the old struct list_heads. When a table size is given
2403 * we use the old value of 8 to avoid reducing the max.
2408 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2409 if (!nf_conntrack_hash)
2412 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2414 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2415 sizeof(struct nf_conn),
2417 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2418 if (!nf_conntrack_cachep)
2421 ret = nf_conntrack_expect_init();
2425 ret = nf_conntrack_acct_init();
2429 ret = nf_conntrack_tstamp_init();
2433 ret = nf_conntrack_ecache_init();
2437 ret = nf_conntrack_timeout_init();
2441 ret = nf_conntrack_helper_init();
2445 ret = nf_conntrack_labels_init();
2449 ret = nf_conntrack_seqadj_init();
2453 ret = nf_conntrack_proto_init();
2457 conntrack_gc_work_init(&conntrack_gc_work);
2458 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2463 nf_conntrack_seqadj_fini();
2465 nf_conntrack_labels_fini();
2467 nf_conntrack_helper_fini();
2469 nf_conntrack_timeout_fini();
2471 nf_conntrack_ecache_fini();
2473 nf_conntrack_tstamp_fini();
2475 nf_conntrack_acct_fini();
2477 nf_conntrack_expect_fini();
2479 kmem_cache_destroy(nf_conntrack_cachep);
2481 kvfree(nf_conntrack_hash);
2485 static struct nf_ct_hook nf_conntrack_hook = {
2486 .update = nf_conntrack_update,
2487 .destroy = destroy_conntrack,
2488 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2491 void nf_conntrack_init_end(void)
2493 /* For use by REJECT target */
2494 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2495 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2499 * We need to use special "null" values, not used in hash table
2501 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2502 #define DYING_NULLS_VAL ((1<<30)+1)
2503 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2505 int nf_conntrack_init_net(struct net *net)
2510 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2511 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2512 atomic_set(&net->ct.count, 0);
2514 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2515 if (!net->ct.pcpu_lists)
2518 for_each_possible_cpu(cpu) {
2519 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2521 spin_lock_init(&pcpu->lock);
2522 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2523 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2526 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2528 goto err_pcpu_lists;
2530 ret = nf_conntrack_expect_pernet_init(net);
2534 nf_conntrack_acct_pernet_init(net);
2535 nf_conntrack_tstamp_pernet_init(net);
2536 nf_conntrack_ecache_pernet_init(net);
2537 nf_conntrack_helper_pernet_init(net);
2538 nf_conntrack_proto_pernet_init(net);
2543 free_percpu(net->ct.stat);
2545 free_percpu(net->ct.pcpu_lists);