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/siphash.h>
25 #include <linux/err.h>
26 #include <linux/percpu.h>
27 #include <linux/moduleparam.h>
28 #include <linux/notifier.h>
29 #include <linux/kernel.h>
30 #include <linux/netdevice.h>
31 #include <linux/socket.h>
33 #include <linux/nsproxy.h>
34 #include <linux/rculist_nulls.h>
36 #include <net/netfilter/nf_conntrack.h>
37 #include <net/netfilter/nf_conntrack_l4proto.h>
38 #include <net/netfilter/nf_conntrack_expect.h>
39 #include <net/netfilter/nf_conntrack_helper.h>
40 #include <net/netfilter/nf_conntrack_seqadj.h>
41 #include <net/netfilter/nf_conntrack_core.h>
42 #include <net/netfilter/nf_conntrack_extend.h>
43 #include <net/netfilter/nf_conntrack_acct.h>
44 #include <net/netfilter/nf_conntrack_ecache.h>
45 #include <net/netfilter/nf_conntrack_zones.h>
46 #include <net/netfilter/nf_conntrack_timestamp.h>
47 #include <net/netfilter/nf_conntrack_timeout.h>
48 #include <net/netfilter/nf_conntrack_labels.h>
49 #include <net/netfilter/nf_conntrack_synproxy.h>
50 #include <net/netfilter/nf_nat.h>
51 #include <net/netfilter/nf_nat_helper.h>
52 #include <net/netns/hash.h>
55 #include "nf_internals.h"
57 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
58 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
60 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
61 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
63 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
64 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
66 struct conntrack_gc_work {
67 struct delayed_work dwork;
73 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
74 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
75 static __read_mostly bool nf_conntrack_locks_all;
77 #define GC_SCAN_INTERVAL (120u * HZ)
78 #define GC_SCAN_MAX_DURATION msecs_to_jiffies(10)
80 #define MAX_CHAINLEN 64u
82 static struct conntrack_gc_work conntrack_gc_work;
84 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
86 /* 1) Acquire the lock */
89 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
90 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
92 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
95 /* fast path failed, unlock */
98 /* Slow path 1) get global lock */
99 spin_lock(&nf_conntrack_locks_all_lock);
101 /* Slow path 2) get the lock we want */
104 /* Slow path 3) release the global lock */
105 spin_unlock(&nf_conntrack_locks_all_lock);
107 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
109 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
111 h1 %= CONNTRACK_LOCKS;
112 h2 %= CONNTRACK_LOCKS;
113 spin_unlock(&nf_conntrack_locks[h1]);
115 spin_unlock(&nf_conntrack_locks[h2]);
118 /* return true if we need to recompute hashes (in case hash table was resized) */
119 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
120 unsigned int h2, unsigned int sequence)
122 h1 %= CONNTRACK_LOCKS;
123 h2 %= CONNTRACK_LOCKS;
125 nf_conntrack_lock(&nf_conntrack_locks[h1]);
127 spin_lock_nested(&nf_conntrack_locks[h2],
128 SINGLE_DEPTH_NESTING);
130 nf_conntrack_lock(&nf_conntrack_locks[h2]);
131 spin_lock_nested(&nf_conntrack_locks[h1],
132 SINGLE_DEPTH_NESTING);
134 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
135 nf_conntrack_double_unlock(h1, h2);
141 static void nf_conntrack_all_lock(void)
142 __acquires(&nf_conntrack_locks_all_lock)
146 spin_lock(&nf_conntrack_locks_all_lock);
148 /* For nf_contrack_locks_all, only the latest time when another
149 * CPU will see an update is controlled, by the "release" of the
151 * The earliest time is not controlled, an thus KCSAN could detect
152 * a race when nf_conntract_lock() reads the variable.
153 * WRITE_ONCE() is used to ensure the compiler will not
154 * optimize the write.
156 WRITE_ONCE(nf_conntrack_locks_all, true);
158 for (i = 0; i < CONNTRACK_LOCKS; i++) {
159 spin_lock(&nf_conntrack_locks[i]);
161 /* This spin_unlock provides the "release" to ensure that
162 * nf_conntrack_locks_all==true is visible to everyone that
163 * acquired spin_lock(&nf_conntrack_locks[]).
165 spin_unlock(&nf_conntrack_locks[i]);
169 static void nf_conntrack_all_unlock(void)
170 __releases(&nf_conntrack_locks_all_lock)
172 /* All prior stores must be complete before we clear
173 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
174 * might observe the false value but not the entire
176 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
178 smp_store_release(&nf_conntrack_locks_all, false);
179 spin_unlock(&nf_conntrack_locks_all_lock);
182 unsigned int nf_conntrack_htable_size __read_mostly;
183 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
185 unsigned int nf_conntrack_max __read_mostly;
186 EXPORT_SYMBOL_GPL(nf_conntrack_max);
187 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
188 static siphash_key_t nf_conntrack_hash_rnd __read_mostly;
190 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
191 const struct net *net)
194 struct nf_conntrack_man src;
195 union nf_inet_addr dst_addr;
199 } __aligned(SIPHASH_ALIGNMENT) combined;
201 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
203 memset(&combined, 0, sizeof(combined));
205 /* The direction must be ignored, so handle usable members manually. */
206 combined.src = tuple->src;
207 combined.dst_addr = tuple->dst.u3;
208 combined.net_mix = net_hash_mix(net);
209 combined.dport = (__force __u16)tuple->dst.u.all;
210 combined.proto = tuple->dst.protonum;
212 return (u32)siphash(&combined, sizeof(combined), &nf_conntrack_hash_rnd);
215 static u32 scale_hash(u32 hash)
217 return reciprocal_scale(hash, nf_conntrack_htable_size);
220 static u32 __hash_conntrack(const struct net *net,
221 const struct nf_conntrack_tuple *tuple,
224 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
227 static u32 hash_conntrack(const struct net *net,
228 const struct nf_conntrack_tuple *tuple)
230 return scale_hash(hash_conntrack_raw(tuple, net));
233 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
234 unsigned int dataoff,
235 struct nf_conntrack_tuple *tuple)
239 } _inet_hdr, *inet_hdr;
241 /* Actually only need first 4 bytes to get ports. */
242 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
246 tuple->src.u.udp.port = inet_hdr->sport;
247 tuple->dst.u.udp.port = inet_hdr->dport;
252 nf_ct_get_tuple(const struct sk_buff *skb,
254 unsigned int dataoff,
258 struct nf_conntrack_tuple *tuple)
264 memset(tuple, 0, sizeof(*tuple));
266 tuple->src.l3num = l3num;
269 nhoff += offsetof(struct iphdr, saddr);
270 size = 2 * sizeof(__be32);
273 nhoff += offsetof(struct ipv6hdr, saddr);
274 size = sizeof(_addrs);
280 ap = skb_header_pointer(skb, nhoff, size, _addrs);
286 tuple->src.u3.ip = ap[0];
287 tuple->dst.u3.ip = ap[1];
290 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
291 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
295 tuple->dst.protonum = protonum;
296 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
299 #if IS_ENABLED(CONFIG_IPV6)
301 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
304 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
305 #ifdef CONFIG_NF_CT_PROTO_GRE
307 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
310 case IPPROTO_UDP: /* fallthrough */
311 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
312 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
313 case IPPROTO_UDPLITE:
314 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
316 #ifdef CONFIG_NF_CT_PROTO_SCTP
318 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
320 #ifdef CONFIG_NF_CT_PROTO_DCCP
322 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
331 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
335 const struct iphdr *iph;
338 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
342 /* Conntrack defragments packets, we might still see fragments
343 * inside ICMP packets though.
345 if (iph->frag_off & htons(IP_OFFSET))
348 dataoff = nhoff + (iph->ihl << 2);
349 *protonum = iph->protocol;
351 /* Check bogus IP headers */
352 if (dataoff > skb->len) {
353 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
354 nhoff, iph->ihl << 2, skb->len);
360 #if IS_ENABLED(CONFIG_IPV6)
361 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
365 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
369 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
370 &nexthdr, sizeof(nexthdr)) != 0) {
371 pr_debug("can't get nexthdr\n");
374 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
376 * (protoff == skb->len) means the packet has not data, just
377 * IPv6 and possibly extensions headers, but it is tracked anyway
379 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
380 pr_debug("can't find proto in pkt\n");
389 static int get_l4proto(const struct sk_buff *skb,
390 unsigned int nhoff, u8 pf, u8 *l4num)
394 return ipv4_get_l4proto(skb, nhoff, l4num);
395 #if IS_ENABLED(CONFIG_IPV6)
397 return ipv6_get_l4proto(skb, nhoff, l4num);
406 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
408 struct net *net, struct nf_conntrack_tuple *tuple)
413 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
417 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
419 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
422 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
423 const struct nf_conntrack_tuple *orig)
425 memset(inverse, 0, sizeof(*inverse));
427 inverse->src.l3num = orig->src.l3num;
429 switch (orig->src.l3num) {
431 inverse->src.u3.ip = orig->dst.u3.ip;
432 inverse->dst.u3.ip = orig->src.u3.ip;
435 inverse->src.u3.in6 = orig->dst.u3.in6;
436 inverse->dst.u3.in6 = orig->src.u3.in6;
442 inverse->dst.dir = !orig->dst.dir;
444 inverse->dst.protonum = orig->dst.protonum;
446 switch (orig->dst.protonum) {
448 return nf_conntrack_invert_icmp_tuple(inverse, orig);
449 #if IS_ENABLED(CONFIG_IPV6)
451 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
455 inverse->src.u.all = orig->dst.u.all;
456 inverse->dst.u.all = orig->src.u.all;
459 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
461 /* Generate a almost-unique pseudo-id for a given conntrack.
463 * intentionally doesn't re-use any of the seeds used for hash
464 * table location, we assume id gets exposed to userspace.
466 * Following nf_conn items do not change throughout lifetime
470 * 2. nf_conn->master address (normally NULL)
471 * 3. the associated net namespace
472 * 4. the original direction tuple
474 u32 nf_ct_get_id(const struct nf_conn *ct)
476 static __read_mostly siphash_key_t ct_id_seed;
477 unsigned long a, b, c, d;
479 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
481 a = (unsigned long)ct;
482 b = (unsigned long)ct->master;
483 c = (unsigned long)nf_ct_net(ct);
484 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
485 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
488 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
490 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
493 EXPORT_SYMBOL_GPL(nf_ct_get_id);
496 clean_from_lists(struct nf_conn *ct)
498 pr_debug("clean_from_lists(%p)\n", ct);
499 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
500 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
502 /* Destroy all pending expectations */
503 nf_ct_remove_expectations(ct);
506 /* must be called with local_bh_disable */
507 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
509 struct ct_pcpu *pcpu;
511 /* add this conntrack to the (per cpu) dying list */
512 ct->cpu = smp_processor_id();
513 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
515 spin_lock(&pcpu->lock);
516 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
518 spin_unlock(&pcpu->lock);
521 /* must be called with local_bh_disable */
522 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
524 struct ct_pcpu *pcpu;
526 /* add this conntrack to the (per cpu) unconfirmed list */
527 ct->cpu = smp_processor_id();
528 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
530 spin_lock(&pcpu->lock);
531 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
533 spin_unlock(&pcpu->lock);
536 /* must be called with local_bh_disable */
537 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
539 struct ct_pcpu *pcpu;
541 /* We overload first tuple to link into unconfirmed or dying list.*/
542 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
544 spin_lock(&pcpu->lock);
545 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
546 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
547 spin_unlock(&pcpu->lock);
550 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
552 /* Released via destroy_conntrack() */
553 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
554 const struct nf_conntrack_zone *zone,
557 struct nf_conn *tmpl, *p;
559 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
560 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
565 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
567 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
568 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
571 tmpl = kzalloc(sizeof(*tmpl), flags);
576 tmpl->status = IPS_TEMPLATE;
577 write_pnet(&tmpl->ct_net, net);
578 nf_ct_zone_add(tmpl, zone);
579 atomic_set(&tmpl->ct_general.use, 0);
583 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
585 void nf_ct_tmpl_free(struct nf_conn *tmpl)
587 nf_ct_ext_destroy(tmpl);
589 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
590 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
594 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
596 static void destroy_gre_conntrack(struct nf_conn *ct)
598 #ifdef CONFIG_NF_CT_PROTO_GRE
599 struct nf_conn *master = ct->master;
602 nf_ct_gre_keymap_destroy(master);
607 destroy_conntrack(struct nf_conntrack *nfct)
609 struct nf_conn *ct = (struct nf_conn *)nfct;
611 pr_debug("destroy_conntrack(%p)\n", ct);
612 WARN_ON(atomic_read(&nfct->use) != 0);
614 if (unlikely(nf_ct_is_template(ct))) {
619 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
620 destroy_gre_conntrack(ct);
623 /* Expectations will have been removed in clean_from_lists,
624 * except TFTP can create an expectation on the first packet,
625 * before connection is in the list, so we need to clean here,
628 nf_ct_remove_expectations(ct);
630 nf_ct_del_from_dying_or_unconfirmed_list(ct);
635 nf_ct_put(ct->master);
637 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
638 nf_conntrack_free(ct);
641 static void nf_ct_delete_from_lists(struct nf_conn *ct)
643 struct net *net = nf_ct_net(ct);
644 unsigned int hash, reply_hash;
645 unsigned int sequence;
647 nf_ct_helper_destroy(ct);
651 sequence = read_seqcount_begin(&nf_conntrack_generation);
652 hash = hash_conntrack(net,
653 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
654 reply_hash = hash_conntrack(net,
655 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
656 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
658 clean_from_lists(ct);
659 nf_conntrack_double_unlock(hash, reply_hash);
661 nf_ct_add_to_dying_list(ct);
666 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
668 struct nf_conn_tstamp *tstamp;
671 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
674 tstamp = nf_conn_tstamp_find(ct);
676 s32 timeout = ct->timeout - nfct_time_stamp;
678 tstamp->stop = ktime_get_real_ns();
680 tstamp->stop -= jiffies_to_nsecs(-timeout);
683 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
684 portid, report) < 0) {
685 /* destroy event was not delivered. nf_ct_put will
686 * be done by event cache worker on redelivery.
688 nf_ct_delete_from_lists(ct);
689 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
694 if (nf_conntrack_ecache_dwork_pending(net))
695 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
696 nf_ct_delete_from_lists(ct);
700 EXPORT_SYMBOL_GPL(nf_ct_delete);
703 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
704 const struct nf_conntrack_tuple *tuple,
705 const struct nf_conntrack_zone *zone,
706 const struct net *net)
708 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
710 /* A conntrack can be recreated with the equal tuple,
711 * so we need to check that the conntrack is confirmed
713 return nf_ct_tuple_equal(tuple, &h->tuple) &&
714 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
715 nf_ct_is_confirmed(ct) &&
716 net_eq(net, nf_ct_net(ct));
720 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
722 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
723 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
724 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
725 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
726 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
727 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
728 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
731 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
732 static void nf_ct_gc_expired(struct nf_conn *ct)
734 if (!atomic_inc_not_zero(&ct->ct_general.use))
737 if (nf_ct_should_gc(ct))
745 * - Caller must take a reference on returned object
746 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
748 static struct nf_conntrack_tuple_hash *
749 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
750 const struct nf_conntrack_tuple *tuple, u32 hash)
752 struct nf_conntrack_tuple_hash *h;
753 struct hlist_nulls_head *ct_hash;
754 struct hlist_nulls_node *n;
755 unsigned int bucket, hsize;
758 nf_conntrack_get_ht(&ct_hash, &hsize);
759 bucket = reciprocal_scale(hash, hsize);
761 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
764 ct = nf_ct_tuplehash_to_ctrack(h);
765 if (nf_ct_is_expired(ct)) {
766 nf_ct_gc_expired(ct);
770 if (nf_ct_key_equal(h, tuple, zone, net))
774 * if the nulls value we got at the end of this lookup is
775 * not the expected one, we must restart lookup.
776 * We probably met an item that was moved to another chain.
778 if (get_nulls_value(n) != bucket) {
779 NF_CT_STAT_INC_ATOMIC(net, search_restart);
786 /* Find a connection corresponding to a tuple. */
787 static struct nf_conntrack_tuple_hash *
788 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
789 const struct nf_conntrack_tuple *tuple, u32 hash)
791 struct nf_conntrack_tuple_hash *h;
796 h = ____nf_conntrack_find(net, zone, tuple, hash);
798 /* We have a candidate that matches the tuple we're interested
799 * in, try to obtain a reference and re-check tuple
801 ct = nf_ct_tuplehash_to_ctrack(h);
802 if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
803 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
806 /* TYPESAFE_BY_RCU recycled the candidate */
818 struct nf_conntrack_tuple_hash *
819 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
820 const struct nf_conntrack_tuple *tuple)
822 return __nf_conntrack_find_get(net, zone, tuple,
823 hash_conntrack_raw(tuple, net));
825 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
827 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
829 unsigned int reply_hash)
831 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
832 &nf_conntrack_hash[hash]);
833 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
834 &nf_conntrack_hash[reply_hash]);
838 nf_conntrack_hash_check_insert(struct nf_conn *ct)
840 const struct nf_conntrack_zone *zone;
841 struct net *net = nf_ct_net(ct);
842 unsigned int hash, reply_hash;
843 struct nf_conntrack_tuple_hash *h;
844 struct hlist_nulls_node *n;
845 unsigned int chainlen = 0;
846 unsigned int sequence;
849 zone = nf_ct_zone(ct);
853 sequence = read_seqcount_begin(&nf_conntrack_generation);
854 hash = hash_conntrack(net,
855 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
856 reply_hash = hash_conntrack(net,
857 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
858 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
860 /* See if there's one in the list already, including reverse */
861 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
862 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
866 if (chainlen++ > MAX_CHAINLEN)
872 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
873 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
876 if (chainlen++ > MAX_CHAINLEN)
881 /* The caller holds a reference to this object */
882 atomic_set(&ct->ct_general.use, 2);
883 __nf_conntrack_hash_insert(ct, hash, reply_hash);
884 nf_conntrack_double_unlock(hash, reply_hash);
885 NF_CT_STAT_INC(net, insert);
889 NF_CT_STAT_INC(net, chaintoolong);
892 nf_conntrack_double_unlock(hash, reply_hash);
896 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
898 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
901 struct nf_conn_acct *acct;
903 acct = nf_conn_acct_find(ct);
905 struct nf_conn_counter *counter = acct->counter;
907 atomic64_add(packets, &counter[dir].packets);
908 atomic64_add(bytes, &counter[dir].bytes);
911 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
913 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
914 const struct nf_conn *loser_ct)
916 struct nf_conn_acct *acct;
918 acct = nf_conn_acct_find(loser_ct);
920 struct nf_conn_counter *counter = acct->counter;
923 /* u32 should be fine since we must have seen one packet. */
924 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
925 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
929 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
931 struct nf_conn_tstamp *tstamp;
933 atomic_inc(&ct->ct_general.use);
934 ct->status |= IPS_CONFIRMED;
936 /* set conntrack timestamp, if enabled. */
937 tstamp = nf_conn_tstamp_find(ct);
939 tstamp->start = ktime_get_real_ns();
942 /* caller must hold locks to prevent concurrent changes */
943 static int __nf_ct_resolve_clash(struct sk_buff *skb,
944 struct nf_conntrack_tuple_hash *h)
946 /* This is the conntrack entry already in hashes that won race. */
947 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
948 enum ip_conntrack_info ctinfo;
949 struct nf_conn *loser_ct;
951 loser_ct = nf_ct_get(skb, &ctinfo);
953 if (nf_ct_is_dying(ct))
956 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
957 nf_ct_match(ct, loser_ct)) {
958 struct net *net = nf_ct_net(ct);
960 nf_conntrack_get(&ct->ct_general);
962 nf_ct_acct_merge(ct, ctinfo, loser_ct);
963 nf_ct_add_to_dying_list(loser_ct);
964 nf_conntrack_put(&loser_ct->ct_general);
965 nf_ct_set(skb, ct, ctinfo);
967 NF_CT_STAT_INC(net, clash_resolve);
975 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
977 * @skb: skb that causes the collision
978 * @repl_idx: hash slot for reply direction
980 * Called when origin or reply direction had a clash.
981 * The skb can be handled without packet drop provided the reply direction
982 * is unique or there the existing entry has the identical tuple in both
985 * Caller must hold conntrack table locks to prevent concurrent updates.
987 * Returns NF_DROP if the clash could not be handled.
989 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
991 struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
992 const struct nf_conntrack_zone *zone;
993 struct nf_conntrack_tuple_hash *h;
994 struct hlist_nulls_node *n;
997 zone = nf_ct_zone(loser_ct);
998 net = nf_ct_net(loser_ct);
1000 /* Reply direction must never result in a clash, unless both origin
1001 * and reply tuples are identical.
1003 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
1004 if (nf_ct_key_equal(h,
1005 &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1007 return __nf_ct_resolve_clash(skb, h);
1010 /* We want the clashing entry to go away real soon: 1 second timeout. */
1011 loser_ct->timeout = nfct_time_stamp + HZ;
1013 /* IPS_NAT_CLASH removes the entry automatically on the first
1014 * reply. Also prevents UDP tracker from moving the entry to
1015 * ASSURED state, i.e. the entry can always be evicted under
1018 loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
1020 __nf_conntrack_insert_prepare(loser_ct);
1022 /* fake add for ORIGINAL dir: we want lookups to only find the entry
1023 * already in the table. This also hides the clashing entry from
1024 * ctnetlink iteration, i.e. conntrack -L won't show them.
1026 hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1028 hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1029 &nf_conntrack_hash[repl_idx]);
1031 NF_CT_STAT_INC(net, clash_resolve);
1036 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1038 * @skb: skb that causes the clash
1039 * @h: tuplehash of the clashing entry already in table
1040 * @reply_hash: hash slot for reply direction
1042 * A conntrack entry can be inserted to the connection tracking table
1043 * if there is no existing entry with an identical tuple.
1045 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1046 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1047 * will find the already-existing entry.
1049 * The major problem with such packet drop is the extra delay added by
1050 * the packet loss -- it will take some time for a retransmit to occur
1051 * (or the sender to time out when waiting for a reply).
1053 * This function attempts to handle the situation without packet drop.
1055 * If @skb has no NAT transformation or if the colliding entries are
1056 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1057 * and @skb is associated with the conntrack entry already in the table.
1059 * Failing that, the new, unconfirmed conntrack is still added to the table
1060 * provided that the collision only occurs in the ORIGINAL direction.
1061 * The new entry will be added only in the non-clashing REPLY direction,
1062 * so packets in the ORIGINAL direction will continue to match the existing
1063 * entry. The new entry will also have a fixed timeout so it expires --
1064 * due to the collision, it will only see reply traffic.
1066 * Returns NF_DROP if the clash could not be resolved.
1068 static __cold noinline int
1069 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1072 /* This is the conntrack entry already in hashes that won race. */
1073 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1074 const struct nf_conntrack_l4proto *l4proto;
1075 enum ip_conntrack_info ctinfo;
1076 struct nf_conn *loser_ct;
1080 loser_ct = nf_ct_get(skb, &ctinfo);
1081 net = nf_ct_net(loser_ct);
1083 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1084 if (!l4proto->allow_clash)
1087 ret = __nf_ct_resolve_clash(skb, h);
1088 if (ret == NF_ACCEPT)
1091 ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1092 if (ret == NF_ACCEPT)
1096 nf_ct_add_to_dying_list(loser_ct);
1097 NF_CT_STAT_INC(net, drop);
1098 NF_CT_STAT_INC(net, insert_failed);
1102 /* Confirm a connection given skb; places it in hash table */
1104 __nf_conntrack_confirm(struct sk_buff *skb)
1106 const struct nf_conntrack_zone *zone;
1107 unsigned int chainlen = 0, sequence;
1108 unsigned int hash, reply_hash;
1109 struct nf_conntrack_tuple_hash *h;
1111 struct nf_conn_help *help;
1112 struct hlist_nulls_node *n;
1113 enum ip_conntrack_info ctinfo;
1117 ct = nf_ct_get(skb, &ctinfo);
1118 net = nf_ct_net(ct);
1120 /* ipt_REJECT uses nf_conntrack_attach to attach related
1121 ICMP/TCP RST packets in other direction. Actual packet
1122 which created connection will be IP_CT_NEW or for an
1123 expected connection, IP_CT_RELATED. */
1124 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1127 zone = nf_ct_zone(ct);
1131 sequence = read_seqcount_begin(&nf_conntrack_generation);
1132 /* reuse the hash saved before */
1133 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1134 hash = scale_hash(hash);
1135 reply_hash = hash_conntrack(net,
1136 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
1138 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1140 /* We're not in hash table, and we refuse to set up related
1141 * connections for unconfirmed conns. But packet copies and
1142 * REJECT will give spurious warnings here.
1145 /* Another skb with the same unconfirmed conntrack may
1146 * win the race. This may happen for bridge(br_flood)
1147 * or broadcast/multicast packets do skb_clone with
1148 * unconfirmed conntrack.
1150 if (unlikely(nf_ct_is_confirmed(ct))) {
1152 nf_conntrack_double_unlock(hash, reply_hash);
1157 pr_debug("Confirming conntrack %p\n", ct);
1158 /* We have to check the DYING flag after unlink to prevent
1159 * a race against nf_ct_get_next_corpse() possibly called from
1160 * user context, else we insert an already 'dead' hash, blocking
1161 * further use of that particular connection -JM.
1163 nf_ct_del_from_dying_or_unconfirmed_list(ct);
1165 if (unlikely(nf_ct_is_dying(ct))) {
1166 nf_ct_add_to_dying_list(ct);
1167 NF_CT_STAT_INC(net, insert_failed);
1171 /* See if there's one in the list already, including reverse:
1172 NAT could have grabbed it without realizing, since we're
1173 not in the hash. If there is, we lost race. */
1174 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
1175 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1178 if (chainlen++ > MAX_CHAINLEN)
1183 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
1184 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1187 if (chainlen++ > MAX_CHAINLEN) {
1189 nf_ct_add_to_dying_list(ct);
1190 NF_CT_STAT_INC(net, chaintoolong);
1191 NF_CT_STAT_INC(net, insert_failed);
1197 /* Timer relative to confirmation time, not original
1198 setting time, otherwise we'd get timer wrap in
1199 weird delay cases. */
1200 ct->timeout += nfct_time_stamp;
1202 __nf_conntrack_insert_prepare(ct);
1204 /* Since the lookup is lockless, hash insertion must be done after
1205 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1206 * guarantee that no other CPU can find the conntrack before the above
1207 * stores are visible.
1209 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1210 nf_conntrack_double_unlock(hash, reply_hash);
1213 help = nfct_help(ct);
1214 if (help && help->helper)
1215 nf_conntrack_event_cache(IPCT_HELPER, ct);
1217 nf_conntrack_event_cache(master_ct(ct) ?
1218 IPCT_RELATED : IPCT_NEW, ct);
1222 ret = nf_ct_resolve_clash(skb, h, reply_hash);
1224 nf_conntrack_double_unlock(hash, reply_hash);
1228 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1230 /* Returns true if a connection correspondings to the tuple (required
1233 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1234 const struct nf_conn *ignored_conntrack)
1236 struct net *net = nf_ct_net(ignored_conntrack);
1237 const struct nf_conntrack_zone *zone;
1238 struct nf_conntrack_tuple_hash *h;
1239 struct hlist_nulls_head *ct_hash;
1240 unsigned int hash, hsize;
1241 struct hlist_nulls_node *n;
1244 zone = nf_ct_zone(ignored_conntrack);
1248 nf_conntrack_get_ht(&ct_hash, &hsize);
1249 hash = __hash_conntrack(net, tuple, hsize);
1251 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1252 ct = nf_ct_tuplehash_to_ctrack(h);
1254 if (ct == ignored_conntrack)
1257 if (nf_ct_is_expired(ct)) {
1258 nf_ct_gc_expired(ct);
1262 if (nf_ct_key_equal(h, tuple, zone, net)) {
1263 /* Tuple is taken already, so caller will need to find
1264 * a new source port to use.
1267 * If the *original tuples* are identical, then both
1268 * conntracks refer to the same flow.
1269 * This is a rare situation, it can occur e.g. when
1270 * more than one UDP packet is sent from same socket
1271 * in different threads.
1273 * Let nf_ct_resolve_clash() deal with this later.
1275 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1276 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1277 nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1280 NF_CT_STAT_INC_ATOMIC(net, found);
1286 if (get_nulls_value(n) != hash) {
1287 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1295 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1297 #define NF_CT_EVICTION_RANGE 8
1299 /* There's a small race here where we may free a just-assured
1300 connection. Too bad: we're in trouble anyway. */
1301 static unsigned int early_drop_list(struct net *net,
1302 struct hlist_nulls_head *head)
1304 struct nf_conntrack_tuple_hash *h;
1305 struct hlist_nulls_node *n;
1306 unsigned int drops = 0;
1307 struct nf_conn *tmp;
1309 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1310 tmp = nf_ct_tuplehash_to_ctrack(h);
1312 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1315 if (nf_ct_is_expired(tmp)) {
1316 nf_ct_gc_expired(tmp);
1320 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1321 !net_eq(nf_ct_net(tmp), net) ||
1322 nf_ct_is_dying(tmp))
1325 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1328 /* kill only if still in same netns -- might have moved due to
1329 * SLAB_TYPESAFE_BY_RCU rules.
1331 * We steal the timer reference. If that fails timer has
1332 * already fired or someone else deleted it. Just drop ref
1333 * and move to next entry.
1335 if (net_eq(nf_ct_net(tmp), net) &&
1336 nf_ct_is_confirmed(tmp) &&
1337 nf_ct_delete(tmp, 0, 0))
1346 static noinline int early_drop(struct net *net, unsigned int hash)
1348 unsigned int i, bucket;
1350 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1351 struct hlist_nulls_head *ct_hash;
1352 unsigned int hsize, drops;
1355 nf_conntrack_get_ht(&ct_hash, &hsize);
1357 bucket = reciprocal_scale(hash, hsize);
1359 bucket = (bucket + 1) % hsize;
1361 drops = early_drop_list(net, &ct_hash[bucket]);
1365 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1373 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1375 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1378 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1380 const struct nf_conntrack_l4proto *l4proto;
1382 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1385 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1386 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1392 static void gc_worker(struct work_struct *work)
1394 unsigned long end_time = jiffies + GC_SCAN_MAX_DURATION;
1395 unsigned int i, hashsz, nf_conntrack_max95 = 0;
1396 unsigned long next_run = GC_SCAN_INTERVAL;
1397 struct conntrack_gc_work *gc_work;
1398 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1400 i = gc_work->next_bucket;
1401 if (gc_work->early_drop)
1402 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1405 struct nf_conntrack_tuple_hash *h;
1406 struct hlist_nulls_head *ct_hash;
1407 struct hlist_nulls_node *n;
1408 struct nf_conn *tmp;
1412 nf_conntrack_get_ht(&ct_hash, &hashsz);
1418 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1419 struct nf_conntrack_net *cnet;
1422 tmp = nf_ct_tuplehash_to_ctrack(h);
1424 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1425 nf_ct_offload_timeout(tmp);
1429 if (nf_ct_is_expired(tmp)) {
1430 nf_ct_gc_expired(tmp);
1434 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1437 net = nf_ct_net(tmp);
1438 cnet = nf_ct_pernet(net);
1439 if (atomic_read(&cnet->count) < nf_conntrack_max95)
1442 /* need to take reference to avoid possible races */
1443 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1446 if (gc_worker_skip_ct(tmp)) {
1451 if (gc_worker_can_early_drop(tmp))
1457 /* could check get_nulls_value() here and restart if ct
1458 * was moved to another chain. But given gc is best-effort
1459 * we will just continue with next hash slot.
1465 if (time_after(jiffies, end_time) && i < hashsz) {
1466 gc_work->next_bucket = i;
1470 } while (i < hashsz);
1472 if (gc_work->exiting)
1476 * Eviction will normally happen from the packet path, and not
1477 * from this gc worker.
1479 * This worker is only here to reap expired entries when system went
1480 * idle after a busy period.
1483 gc_work->early_drop = false;
1484 gc_work->next_bucket = 0;
1486 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1489 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1491 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1492 gc_work->exiting = false;
1495 static struct nf_conn *
1496 __nf_conntrack_alloc(struct net *net,
1497 const struct nf_conntrack_zone *zone,
1498 const struct nf_conntrack_tuple *orig,
1499 const struct nf_conntrack_tuple *repl,
1500 gfp_t gfp, u32 hash)
1502 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
1503 unsigned int ct_count;
1506 /* We don't want any race condition at early drop stage */
1507 ct_count = atomic_inc_return(&cnet->count);
1509 if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1510 if (!early_drop(net, hash)) {
1511 if (!conntrack_gc_work.early_drop)
1512 conntrack_gc_work.early_drop = true;
1513 atomic_dec(&cnet->count);
1514 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1515 return ERR_PTR(-ENOMEM);
1520 * Do not use kmem_cache_zalloc(), as this cache uses
1521 * SLAB_TYPESAFE_BY_RCU.
1523 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1527 spin_lock_init(&ct->lock);
1528 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1529 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1530 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1531 /* save hash for reusing when confirming */
1532 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1535 write_pnet(&ct->ct_net, net);
1536 memset(&ct->__nfct_init_offset, 0,
1537 offsetof(struct nf_conn, proto) -
1538 offsetof(struct nf_conn, __nfct_init_offset));
1540 nf_ct_zone_add(ct, zone);
1542 /* Because we use RCU lookups, we set ct_general.use to zero before
1543 * this is inserted in any list.
1545 atomic_set(&ct->ct_general.use, 0);
1548 atomic_dec(&cnet->count);
1549 return ERR_PTR(-ENOMEM);
1552 struct nf_conn *nf_conntrack_alloc(struct net *net,
1553 const struct nf_conntrack_zone *zone,
1554 const struct nf_conntrack_tuple *orig,
1555 const struct nf_conntrack_tuple *repl,
1558 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1560 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1562 void nf_conntrack_free(struct nf_conn *ct)
1564 struct net *net = nf_ct_net(ct);
1565 struct nf_conntrack_net *cnet;
1567 /* A freed object has refcnt == 0, that's
1568 * the golden rule for SLAB_TYPESAFE_BY_RCU
1570 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1572 nf_ct_ext_destroy(ct);
1573 kmem_cache_free(nf_conntrack_cachep, ct);
1574 cnet = nf_ct_pernet(net);
1576 smp_mb__before_atomic();
1577 atomic_dec(&cnet->count);
1579 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1582 /* Allocate a new conntrack: we return -ENOMEM if classification
1583 failed due to stress. Otherwise it really is unclassifiable. */
1584 static noinline struct nf_conntrack_tuple_hash *
1585 init_conntrack(struct net *net, struct nf_conn *tmpl,
1586 const struct nf_conntrack_tuple *tuple,
1587 struct sk_buff *skb,
1588 unsigned int dataoff, u32 hash)
1591 struct nf_conn_help *help;
1592 struct nf_conntrack_tuple repl_tuple;
1593 struct nf_conntrack_ecache *ecache;
1594 struct nf_conntrack_expect *exp = NULL;
1595 const struct nf_conntrack_zone *zone;
1596 struct nf_conn_timeout *timeout_ext;
1597 struct nf_conntrack_zone tmp;
1598 struct nf_conntrack_net *cnet;
1600 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1601 pr_debug("Can't invert tuple.\n");
1605 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1606 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1609 return (struct nf_conntrack_tuple_hash *)ct;
1611 if (!nf_ct_add_synproxy(ct, tmpl)) {
1612 nf_conntrack_free(ct);
1613 return ERR_PTR(-ENOMEM);
1616 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1619 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1622 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1623 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1624 nf_ct_labels_ext_add(ct);
1626 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1627 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1628 ecache ? ecache->expmask : 0,
1632 cnet = nf_ct_pernet(net);
1633 if (cnet->expect_count) {
1634 spin_lock(&nf_conntrack_expect_lock);
1635 exp = nf_ct_find_expectation(net, zone, tuple);
1637 pr_debug("expectation arrives ct=%p exp=%p\n",
1639 /* Welcome, Mr. Bond. We've been expecting you... */
1640 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1641 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1642 ct->master = exp->master;
1644 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1646 rcu_assign_pointer(help->helper, exp->helper);
1649 #ifdef CONFIG_NF_CONNTRACK_MARK
1650 ct->mark = exp->master->mark;
1652 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1653 ct->secmark = exp->master->secmark;
1655 NF_CT_STAT_INC(net, expect_new);
1657 spin_unlock(&nf_conntrack_expect_lock);
1660 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1662 /* Now it is inserted into the unconfirmed list, bump refcount */
1663 nf_conntrack_get(&ct->ct_general);
1664 nf_ct_add_to_unconfirmed_list(ct);
1670 exp->expectfn(ct, exp);
1671 nf_ct_expect_put(exp);
1674 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1677 /* On success, returns 0, sets skb->_nfct | ctinfo */
1679 resolve_normal_ct(struct nf_conn *tmpl,
1680 struct sk_buff *skb,
1681 unsigned int dataoff,
1683 const struct nf_hook_state *state)
1685 const struct nf_conntrack_zone *zone;
1686 struct nf_conntrack_tuple tuple;
1687 struct nf_conntrack_tuple_hash *h;
1688 enum ip_conntrack_info ctinfo;
1689 struct nf_conntrack_zone tmp;
1693 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1694 dataoff, state->pf, protonum, state->net,
1696 pr_debug("Can't get tuple\n");
1700 /* look for tuple match */
1701 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1702 hash = hash_conntrack_raw(&tuple, state->net);
1703 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1705 h = init_conntrack(state->net, tmpl, &tuple,
1706 skb, dataoff, hash);
1712 ct = nf_ct_tuplehash_to_ctrack(h);
1714 /* It exists; we have (non-exclusive) reference. */
1715 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1716 ctinfo = IP_CT_ESTABLISHED_REPLY;
1718 /* Once we've had two way comms, always ESTABLISHED. */
1719 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1720 pr_debug("normal packet for %p\n", ct);
1721 ctinfo = IP_CT_ESTABLISHED;
1722 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1723 pr_debug("related packet for %p\n", ct);
1724 ctinfo = IP_CT_RELATED;
1726 pr_debug("new packet for %p\n", ct);
1730 nf_ct_set(skb, ct, ctinfo);
1735 * icmp packets need special treatment to handle error messages that are
1736 * related to a connection.
1738 * Callers need to check if skb has a conntrack assigned when this
1739 * helper returns; in such case skb belongs to an already known connection.
1741 static unsigned int __cold
1742 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1743 struct sk_buff *skb,
1744 unsigned int dataoff,
1746 const struct nf_hook_state *state)
1750 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1751 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1752 #if IS_ENABLED(CONFIG_IPV6)
1753 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1754 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1760 NF_CT_STAT_INC_ATOMIC(state->net, error);
1765 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1766 enum ip_conntrack_info ctinfo)
1768 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1771 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1773 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1777 /* Returns verdict for packet, or -1 for invalid. */
1778 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1779 struct sk_buff *skb,
1780 unsigned int dataoff,
1781 enum ip_conntrack_info ctinfo,
1782 const struct nf_hook_state *state)
1784 switch (nf_ct_protonum(ct)) {
1786 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1789 return nf_conntrack_udp_packet(ct, skb, dataoff,
1792 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1793 #if IS_ENABLED(CONFIG_IPV6)
1794 case IPPROTO_ICMPV6:
1795 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1797 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1798 case IPPROTO_UDPLITE:
1799 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1802 #ifdef CONFIG_NF_CT_PROTO_SCTP
1804 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1807 #ifdef CONFIG_NF_CT_PROTO_DCCP
1809 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1812 #ifdef CONFIG_NF_CT_PROTO_GRE
1814 return nf_conntrack_gre_packet(ct, skb, dataoff,
1819 return generic_packet(ct, skb, ctinfo);
1823 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1825 enum ip_conntrack_info ctinfo;
1826 struct nf_conn *ct, *tmpl;
1830 tmpl = nf_ct_get(skb, &ctinfo);
1831 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1832 /* Previously seen (loopback or untracked)? Ignore. */
1833 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1834 ctinfo == IP_CT_UNTRACKED)
1839 /* rcu_read_lock()ed by nf_hook_thresh */
1840 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1842 pr_debug("not prepared to track yet or error occurred\n");
1843 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1848 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1849 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1855 /* ICMP[v6] protocol trackers may assign one conntrack. */
1860 ret = resolve_normal_ct(tmpl, skb, dataoff,
1863 /* Too stressed to deal. */
1864 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1869 ct = nf_ct_get(skb, &ctinfo);
1871 /* Not valid part of a connection */
1872 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1877 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1879 /* Invalid: inverse of the return code tells
1880 * the netfilter core what to do */
1881 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1882 nf_conntrack_put(&ct->ct_general);
1884 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1885 if (ret == -NF_DROP)
1886 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1887 /* Special case: TCP tracker reports an attempt to reopen a
1888 * closed/aborted connection. We have to go back and create a
1891 if (ret == -NF_REPEAT)
1897 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1898 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1899 nf_conntrack_event_cache(IPCT_REPLY, ct);
1906 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1908 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1909 implicitly racy: see __nf_conntrack_confirm */
1910 void nf_conntrack_alter_reply(struct nf_conn *ct,
1911 const struct nf_conntrack_tuple *newreply)
1913 struct nf_conn_help *help = nfct_help(ct);
1915 /* Should be unconfirmed, so not in hash table yet */
1916 WARN_ON(nf_ct_is_confirmed(ct));
1918 pr_debug("Altering reply tuple of %p to ", ct);
1919 nf_ct_dump_tuple(newreply);
1921 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1922 if (ct->master || (help && !hlist_empty(&help->expectations)))
1926 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1929 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1931 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1932 void __nf_ct_refresh_acct(struct nf_conn *ct,
1933 enum ip_conntrack_info ctinfo,
1934 const struct sk_buff *skb,
1938 /* Only update if this is not a fixed timeout */
1939 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1942 /* If not in hash table, timer will not be active yet */
1943 if (nf_ct_is_confirmed(ct))
1944 extra_jiffies += nfct_time_stamp;
1946 if (READ_ONCE(ct->timeout) != extra_jiffies)
1947 WRITE_ONCE(ct->timeout, extra_jiffies);
1950 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1952 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1954 bool nf_ct_kill_acct(struct nf_conn *ct,
1955 enum ip_conntrack_info ctinfo,
1956 const struct sk_buff *skb)
1958 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1960 return nf_ct_delete(ct, 0, 0);
1962 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1964 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1966 #include <linux/netfilter/nfnetlink.h>
1967 #include <linux/netfilter/nfnetlink_conntrack.h>
1968 #include <linux/mutex.h>
1970 /* Generic function for tcp/udp/sctp/dccp and alike. */
1971 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1972 const struct nf_conntrack_tuple *tuple)
1974 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1975 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1976 goto nla_put_failure;
1982 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1984 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1985 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1986 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1988 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1990 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1991 struct nf_conntrack_tuple *t,
1994 if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
1995 if (!tb[CTA_PROTO_SRC_PORT])
1998 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
2001 if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
2002 if (!tb[CTA_PROTO_DST_PORT])
2005 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
2010 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
2012 unsigned int nf_ct_port_nlattr_tuple_size(void)
2014 static unsigned int size __read_mostly;
2017 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2021 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2024 /* Used by ipt_REJECT and ip6t_REJECT. */
2025 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2028 enum ip_conntrack_info ctinfo;
2030 /* This ICMP is in reverse direction to the packet which caused it */
2031 ct = nf_ct_get(skb, &ctinfo);
2032 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2033 ctinfo = IP_CT_RELATED_REPLY;
2035 ctinfo = IP_CT_RELATED;
2037 /* Attach to new skbuff, and increment count */
2038 nf_ct_set(nskb, ct, ctinfo);
2039 nf_conntrack_get(skb_nfct(nskb));
2042 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2044 enum ip_conntrack_info ctinfo)
2046 struct nf_conntrack_tuple_hash *h;
2047 struct nf_conntrack_tuple tuple;
2048 struct nf_nat_hook *nat_hook;
2049 unsigned int status;
2054 l3num = nf_ct_l3num(ct);
2056 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2060 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2061 l4num, net, &tuple))
2064 if (ct->status & IPS_SRC_NAT) {
2065 memcpy(tuple.src.u3.all,
2066 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2067 sizeof(tuple.src.u3.all));
2069 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2072 if (ct->status & IPS_DST_NAT) {
2073 memcpy(tuple.dst.u3.all,
2074 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2075 sizeof(tuple.dst.u3.all));
2077 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2080 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2084 /* Store status bits of the conntrack that is clashing to re-do NAT
2085 * mangling according to what it has been done already to this packet.
2087 status = ct->status;
2090 ct = nf_ct_tuplehash_to_ctrack(h);
2091 nf_ct_set(skb, ct, ctinfo);
2093 nat_hook = rcu_dereference(nf_nat_hook);
2097 if (status & IPS_SRC_NAT &&
2098 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2099 IP_CT_DIR_ORIGINAL) == NF_DROP)
2102 if (status & IPS_DST_NAT &&
2103 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2104 IP_CT_DIR_ORIGINAL) == NF_DROP)
2110 /* This packet is coming from userspace via nf_queue, complete the packet
2111 * processing after the helper invocation in nf_confirm().
2113 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2114 enum ip_conntrack_info ctinfo)
2116 const struct nf_conntrack_helper *helper;
2117 const struct nf_conn_help *help;
2120 help = nfct_help(ct);
2124 helper = rcu_dereference(help->helper);
2125 if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2128 switch (nf_ct_l3num(ct)) {
2130 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2132 #if IS_ENABLED(CONFIG_IPV6)
2133 case NFPROTO_IPV6: {
2137 pnum = ipv6_hdr(skb)->nexthdr;
2138 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2140 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2149 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2150 !nf_is_loopback_packet(skb)) {
2151 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2152 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2157 /* We've seen it coming out the other side: confirm it */
2158 return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2161 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2163 enum ip_conntrack_info ctinfo;
2167 ct = nf_ct_get(skb, &ctinfo);
2171 if (!nf_ct_is_confirmed(ct)) {
2172 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2176 ct = nf_ct_get(skb, &ctinfo);
2179 return nf_confirm_cthelper(skb, ct, ctinfo);
2182 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2183 const struct sk_buff *skb)
2185 const struct nf_conntrack_tuple *src_tuple;
2186 const struct nf_conntrack_tuple_hash *hash;
2187 struct nf_conntrack_tuple srctuple;
2188 enum ip_conntrack_info ctinfo;
2191 ct = nf_ct_get(skb, &ctinfo);
2193 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2194 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2198 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2199 NFPROTO_IPV4, dev_net(skb->dev),
2203 hash = nf_conntrack_find_get(dev_net(skb->dev),
2209 ct = nf_ct_tuplehash_to_ctrack(hash);
2210 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2211 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2217 /* Bring out ya dead! */
2218 static struct nf_conn *
2219 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2220 void *data, unsigned int *bucket)
2222 struct nf_conntrack_tuple_hash *h;
2224 struct hlist_nulls_node *n;
2227 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2228 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2230 nf_conntrack_lock(lockp);
2231 if (*bucket < nf_conntrack_htable_size) {
2232 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
2233 if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2235 /* All nf_conn objects are added to hash table twice, one
2236 * for original direction tuple, once for the reply tuple.
2238 * Exception: In the IPS_NAT_CLASH case, only the reply
2239 * tuple is added (the original tuple already existed for
2240 * a different object).
2242 * We only need to call the iterator once for each
2243 * conntrack, so we just use the 'reply' direction
2244 * tuple while iterating.
2246 ct = nf_ct_tuplehash_to_ctrack(h);
2258 atomic_inc(&ct->ct_general.use);
2264 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2265 void *data, u32 portid, int report)
2267 unsigned int bucket = 0, sequence;
2273 sequence = read_seqcount_begin(&nf_conntrack_generation);
2275 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2276 /* Time to push up daises... */
2278 nf_ct_delete(ct, portid, report);
2283 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2290 int (*iter)(struct nf_conn *i, void *data);
2295 static int iter_net_only(struct nf_conn *i, void *data)
2297 struct iter_data *d = data;
2299 if (!net_eq(d->net, nf_ct_net(i)))
2302 return d->iter(i, d->data);
2306 __nf_ct_unconfirmed_destroy(struct net *net)
2310 for_each_possible_cpu(cpu) {
2311 struct nf_conntrack_tuple_hash *h;
2312 struct hlist_nulls_node *n;
2313 struct ct_pcpu *pcpu;
2315 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2317 spin_lock_bh(&pcpu->lock);
2318 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2321 ct = nf_ct_tuplehash_to_ctrack(h);
2323 /* we cannot call iter() on unconfirmed list, the
2324 * owning cpu can reallocate ct->ext at any time.
2326 set_bit(IPS_DYING_BIT, &ct->status);
2328 spin_unlock_bh(&pcpu->lock);
2333 void nf_ct_unconfirmed_destroy(struct net *net)
2335 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2339 if (atomic_read(&cnet->count) > 0) {
2340 __nf_ct_unconfirmed_destroy(net);
2341 nf_queue_nf_hook_drop(net);
2345 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2347 void nf_ct_iterate_cleanup_net(struct net *net,
2348 int (*iter)(struct nf_conn *i, void *data),
2349 void *data, u32 portid, int report)
2351 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2356 if (atomic_read(&cnet->count) == 0)
2363 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2365 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2368 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2369 * @iter: callback to invoke for each conntrack
2370 * @data: data to pass to @iter
2372 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2373 * unconfirmed list as dying (so they will not be inserted into
2376 * Can only be called in module exit path.
2379 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2383 down_read(&net_rwsem);
2385 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2387 if (atomic_read(&cnet->count) == 0)
2389 __nf_ct_unconfirmed_destroy(net);
2390 nf_queue_nf_hook_drop(net);
2392 up_read(&net_rwsem);
2394 /* Need to wait for netns cleanup worker to finish, if its
2395 * running -- it might have deleted a net namespace from
2396 * the global list, so our __nf_ct_unconfirmed_destroy() might
2397 * not have affected all namespaces.
2401 /* a conntrack could have been unlinked from unconfirmed list
2402 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2403 * This makes sure its inserted into conntrack table.
2407 nf_ct_iterate_cleanup(iter, data, 0, 0);
2409 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2411 static int kill_all(struct nf_conn *i, void *data)
2413 return net_eq(nf_ct_net(i), data);
2416 void nf_conntrack_cleanup_start(void)
2418 conntrack_gc_work.exiting = true;
2419 RCU_INIT_POINTER(ip_ct_attach, NULL);
2422 void nf_conntrack_cleanup_end(void)
2424 RCU_INIT_POINTER(nf_ct_hook, NULL);
2425 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2426 kvfree(nf_conntrack_hash);
2428 nf_conntrack_proto_fini();
2429 nf_conntrack_seqadj_fini();
2430 nf_conntrack_labels_fini();
2431 nf_conntrack_helper_fini();
2432 nf_conntrack_timeout_fini();
2433 nf_conntrack_ecache_fini();
2434 nf_conntrack_tstamp_fini();
2435 nf_conntrack_acct_fini();
2436 nf_conntrack_expect_fini();
2438 kmem_cache_destroy(nf_conntrack_cachep);
2442 * Mishearing the voices in his head, our hero wonders how he's
2443 * supposed to kill the mall.
2445 void nf_conntrack_cleanup_net(struct net *net)
2449 list_add(&net->exit_list, &single);
2450 nf_conntrack_cleanup_net_list(&single);
2453 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2459 * This makes sure all current packets have passed through
2460 * netfilter framework. Roll on, two-stage module
2466 list_for_each_entry(net, net_exit_list, exit_list) {
2467 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2469 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2470 if (atomic_read(&cnet->count) != 0)
2475 goto i_see_dead_people;
2478 list_for_each_entry(net, net_exit_list, exit_list) {
2479 nf_conntrack_ecache_pernet_fini(net);
2480 nf_conntrack_expect_pernet_fini(net);
2481 free_percpu(net->ct.stat);
2482 free_percpu(net->ct.pcpu_lists);
2486 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2488 struct hlist_nulls_head *hash;
2489 unsigned int nr_slots, i;
2491 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2494 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2495 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2497 hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2500 for (i = 0; i < nr_slots; i++)
2501 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2505 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2507 int nf_conntrack_hash_resize(unsigned int hashsize)
2510 unsigned int old_size;
2511 struct hlist_nulls_head *hash, *old_hash;
2512 struct nf_conntrack_tuple_hash *h;
2518 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2522 old_size = nf_conntrack_htable_size;
2523 if (old_size == hashsize) {
2529 nf_conntrack_all_lock();
2530 write_seqcount_begin(&nf_conntrack_generation);
2532 /* Lookups in the old hash might happen in parallel, which means we
2533 * might get false negatives during connection lookup. New connections
2534 * created because of a false negative won't make it into the hash
2535 * though since that required taking the locks.
2538 for (i = 0; i < nf_conntrack_htable_size; i++) {
2539 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2540 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2541 struct nf_conntrack_tuple_hash, hnnode);
2542 ct = nf_ct_tuplehash_to_ctrack(h);
2543 hlist_nulls_del_rcu(&h->hnnode);
2544 bucket = __hash_conntrack(nf_ct_net(ct),
2545 &h->tuple, hashsize);
2546 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2549 old_size = nf_conntrack_htable_size;
2550 old_hash = nf_conntrack_hash;
2552 nf_conntrack_hash = hash;
2553 nf_conntrack_htable_size = hashsize;
2555 write_seqcount_end(&nf_conntrack_generation);
2556 nf_conntrack_all_unlock();
2564 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2566 unsigned int hashsize;
2569 if (current->nsproxy->net_ns != &init_net)
2572 /* On boot, we can set this without any fancy locking. */
2573 if (!nf_conntrack_hash)
2574 return param_set_uint(val, kp);
2576 rc = kstrtouint(val, 0, &hashsize);
2580 return nf_conntrack_hash_resize(hashsize);
2583 static __always_inline unsigned int total_extension_size(void)
2585 /* remember to add new extensions below */
2586 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2588 return sizeof(struct nf_ct_ext) +
2589 sizeof(struct nf_conn_help)
2590 #if IS_ENABLED(CONFIG_NF_NAT)
2591 + sizeof(struct nf_conn_nat)
2593 + sizeof(struct nf_conn_seqadj)
2594 + sizeof(struct nf_conn_acct)
2595 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2596 + sizeof(struct nf_conntrack_ecache)
2598 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2599 + sizeof(struct nf_conn_tstamp)
2601 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2602 + sizeof(struct nf_conn_timeout)
2604 #ifdef CONFIG_NF_CONNTRACK_LABELS
2605 + sizeof(struct nf_conn_labels)
2607 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2608 + sizeof(struct nf_conn_synproxy)
2613 int nf_conntrack_init_start(void)
2615 unsigned long nr_pages = totalram_pages();
2620 /* struct nf_ct_ext uses u8 to store offsets/size */
2621 BUILD_BUG_ON(total_extension_size() > 255u);
2623 seqcount_spinlock_init(&nf_conntrack_generation,
2624 &nf_conntrack_locks_all_lock);
2626 for (i = 0; i < CONNTRACK_LOCKS; i++)
2627 spin_lock_init(&nf_conntrack_locks[i]);
2629 if (!nf_conntrack_htable_size) {
2630 nf_conntrack_htable_size
2631 = (((nr_pages << PAGE_SHIFT) / 16384)
2632 / sizeof(struct hlist_head));
2633 if (BITS_PER_LONG >= 64 &&
2634 nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2635 nf_conntrack_htable_size = 262144;
2636 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2637 nf_conntrack_htable_size = 65536;
2639 if (nf_conntrack_htable_size < 1024)
2640 nf_conntrack_htable_size = 1024;
2641 /* Use a max. factor of one by default to keep the average
2642 * hash chain length at 2 entries. Each entry has to be added
2643 * twice (once for original direction, once for reply).
2644 * When a table size is given we use the old value of 8 to
2645 * avoid implicit reduction of the max entries setting.
2650 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2651 if (!nf_conntrack_hash)
2654 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2656 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2657 sizeof(struct nf_conn),
2659 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2660 if (!nf_conntrack_cachep)
2663 ret = nf_conntrack_expect_init();
2667 ret = nf_conntrack_acct_init();
2671 ret = nf_conntrack_tstamp_init();
2675 ret = nf_conntrack_ecache_init();
2679 ret = nf_conntrack_timeout_init();
2683 ret = nf_conntrack_helper_init();
2687 ret = nf_conntrack_labels_init();
2691 ret = nf_conntrack_seqadj_init();
2695 ret = nf_conntrack_proto_init();
2699 conntrack_gc_work_init(&conntrack_gc_work);
2700 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2705 nf_conntrack_seqadj_fini();
2707 nf_conntrack_labels_fini();
2709 nf_conntrack_helper_fini();
2711 nf_conntrack_timeout_fini();
2713 nf_conntrack_ecache_fini();
2715 nf_conntrack_tstamp_fini();
2717 nf_conntrack_acct_fini();
2719 nf_conntrack_expect_fini();
2721 kmem_cache_destroy(nf_conntrack_cachep);
2723 kvfree(nf_conntrack_hash);
2727 static struct nf_ct_hook nf_conntrack_hook = {
2728 .update = nf_conntrack_update,
2729 .destroy = destroy_conntrack,
2730 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2733 void nf_conntrack_init_end(void)
2735 /* For use by REJECT target */
2736 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2737 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2741 * We need to use special "null" values, not used in hash table
2743 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2744 #define DYING_NULLS_VAL ((1<<30)+1)
2746 int nf_conntrack_init_net(struct net *net)
2748 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2752 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2753 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2754 atomic_set(&cnet->count, 0);
2756 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2757 if (!net->ct.pcpu_lists)
2760 for_each_possible_cpu(cpu) {
2761 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2763 spin_lock_init(&pcpu->lock);
2764 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2765 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2768 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2770 goto err_pcpu_lists;
2772 ret = nf_conntrack_expect_pernet_init(net);
2776 nf_conntrack_acct_pernet_init(net);
2777 nf_conntrack_tstamp_pernet_init(net);
2778 nf_conntrack_ecache_pernet_init(net);
2779 nf_conntrack_helper_pernet_init(net);
2780 nf_conntrack_proto_pernet_init(net);
2785 free_percpu(net->ct.stat);
2787 free_percpu(net->ct.pcpu_lists);