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_conntrack_act_ct.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;
74 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
75 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
76 static __read_mostly bool nf_conntrack_locks_all;
78 /* serialize hash resizes and nf_ct_iterate_cleanup */
79 static DEFINE_MUTEX(nf_conntrack_mutex);
81 #define GC_SCAN_INTERVAL (120u * HZ)
82 #define GC_SCAN_MAX_DURATION msecs_to_jiffies(10)
84 #define MIN_CHAINLEN 8u
85 #define MAX_CHAINLEN (32u - MIN_CHAINLEN)
87 static struct conntrack_gc_work conntrack_gc_work;
89 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
91 /* 1) Acquire the lock */
94 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
95 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
97 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
100 /* fast path failed, unlock */
103 /* Slow path 1) get global lock */
104 spin_lock(&nf_conntrack_locks_all_lock);
106 /* Slow path 2) get the lock we want */
109 /* Slow path 3) release the global lock */
110 spin_unlock(&nf_conntrack_locks_all_lock);
112 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
114 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
116 h1 %= CONNTRACK_LOCKS;
117 h2 %= CONNTRACK_LOCKS;
118 spin_unlock(&nf_conntrack_locks[h1]);
120 spin_unlock(&nf_conntrack_locks[h2]);
123 /* return true if we need to recompute hashes (in case hash table was resized) */
124 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
125 unsigned int h2, unsigned int sequence)
127 h1 %= CONNTRACK_LOCKS;
128 h2 %= CONNTRACK_LOCKS;
130 nf_conntrack_lock(&nf_conntrack_locks[h1]);
132 spin_lock_nested(&nf_conntrack_locks[h2],
133 SINGLE_DEPTH_NESTING);
135 nf_conntrack_lock(&nf_conntrack_locks[h2]);
136 spin_lock_nested(&nf_conntrack_locks[h1],
137 SINGLE_DEPTH_NESTING);
139 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
140 nf_conntrack_double_unlock(h1, h2);
146 static void nf_conntrack_all_lock(void)
147 __acquires(&nf_conntrack_locks_all_lock)
151 spin_lock(&nf_conntrack_locks_all_lock);
153 /* For nf_contrack_locks_all, only the latest time when another
154 * CPU will see an update is controlled, by the "release" of the
156 * The earliest time is not controlled, an thus KCSAN could detect
157 * a race when nf_conntract_lock() reads the variable.
158 * WRITE_ONCE() is used to ensure the compiler will not
159 * optimize the write.
161 WRITE_ONCE(nf_conntrack_locks_all, true);
163 for (i = 0; i < CONNTRACK_LOCKS; i++) {
164 spin_lock(&nf_conntrack_locks[i]);
166 /* This spin_unlock provides the "release" to ensure that
167 * nf_conntrack_locks_all==true is visible to everyone that
168 * acquired spin_lock(&nf_conntrack_locks[]).
170 spin_unlock(&nf_conntrack_locks[i]);
174 static void nf_conntrack_all_unlock(void)
175 __releases(&nf_conntrack_locks_all_lock)
177 /* All prior stores must be complete before we clear
178 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
179 * might observe the false value but not the entire
181 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
183 smp_store_release(&nf_conntrack_locks_all, false);
184 spin_unlock(&nf_conntrack_locks_all_lock);
187 unsigned int nf_conntrack_htable_size __read_mostly;
188 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
190 unsigned int nf_conntrack_max __read_mostly;
191 EXPORT_SYMBOL_GPL(nf_conntrack_max);
192 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
193 static siphash_aligned_key_t nf_conntrack_hash_rnd;
195 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
197 const struct net *net)
200 struct nf_conntrack_man src;
201 union nf_inet_addr dst_addr;
206 } __aligned(SIPHASH_ALIGNMENT) combined;
208 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
210 memset(&combined, 0, sizeof(combined));
212 /* The direction must be ignored, so handle usable members manually. */
213 combined.src = tuple->src;
214 combined.dst_addr = tuple->dst.u3;
215 combined.zone = zoneid;
216 combined.net_mix = net_hash_mix(net);
217 combined.dport = (__force __u16)tuple->dst.u.all;
218 combined.proto = tuple->dst.protonum;
220 return (u32)siphash(&combined, sizeof(combined), &nf_conntrack_hash_rnd);
223 static u32 scale_hash(u32 hash)
225 return reciprocal_scale(hash, nf_conntrack_htable_size);
228 static u32 __hash_conntrack(const struct net *net,
229 const struct nf_conntrack_tuple *tuple,
233 return reciprocal_scale(hash_conntrack_raw(tuple, zoneid, net), size);
236 static u32 hash_conntrack(const struct net *net,
237 const struct nf_conntrack_tuple *tuple,
240 return scale_hash(hash_conntrack_raw(tuple, zoneid, net));
243 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
244 unsigned int dataoff,
245 struct nf_conntrack_tuple *tuple)
249 } _inet_hdr, *inet_hdr;
251 /* Actually only need first 4 bytes to get ports. */
252 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
256 tuple->src.u.udp.port = inet_hdr->sport;
257 tuple->dst.u.udp.port = inet_hdr->dport;
262 nf_ct_get_tuple(const struct sk_buff *skb,
264 unsigned int dataoff,
268 struct nf_conntrack_tuple *tuple)
274 memset(tuple, 0, sizeof(*tuple));
276 tuple->src.l3num = l3num;
279 nhoff += offsetof(struct iphdr, saddr);
280 size = 2 * sizeof(__be32);
283 nhoff += offsetof(struct ipv6hdr, saddr);
284 size = sizeof(_addrs);
290 ap = skb_header_pointer(skb, nhoff, size, _addrs);
296 tuple->src.u3.ip = ap[0];
297 tuple->dst.u3.ip = ap[1];
300 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
301 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
305 tuple->dst.protonum = protonum;
306 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
309 #if IS_ENABLED(CONFIG_IPV6)
311 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
314 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
315 #ifdef CONFIG_NF_CT_PROTO_GRE
317 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
320 case IPPROTO_UDP: /* fallthrough */
321 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
322 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
323 case IPPROTO_UDPLITE:
324 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
326 #ifdef CONFIG_NF_CT_PROTO_SCTP
328 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
330 #ifdef CONFIG_NF_CT_PROTO_DCCP
332 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
341 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
345 const struct iphdr *iph;
348 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
352 /* Conntrack defragments packets, we might still see fragments
353 * inside ICMP packets though.
355 if (iph->frag_off & htons(IP_OFFSET))
358 dataoff = nhoff + (iph->ihl << 2);
359 *protonum = iph->protocol;
361 /* Check bogus IP headers */
362 if (dataoff > skb->len) {
363 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
364 nhoff, iph->ihl << 2, skb->len);
370 #if IS_ENABLED(CONFIG_IPV6)
371 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
375 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
379 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
380 &nexthdr, sizeof(nexthdr)) != 0) {
381 pr_debug("can't get nexthdr\n");
384 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
386 * (protoff == skb->len) means the packet has not data, just
387 * IPv6 and possibly extensions headers, but it is tracked anyway
389 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
390 pr_debug("can't find proto in pkt\n");
399 static int get_l4proto(const struct sk_buff *skb,
400 unsigned int nhoff, u8 pf, u8 *l4num)
404 return ipv4_get_l4proto(skb, nhoff, l4num);
405 #if IS_ENABLED(CONFIG_IPV6)
407 return ipv6_get_l4proto(skb, nhoff, l4num);
416 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
418 struct net *net, struct nf_conntrack_tuple *tuple)
423 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
427 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
429 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
432 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
433 const struct nf_conntrack_tuple *orig)
435 memset(inverse, 0, sizeof(*inverse));
437 inverse->src.l3num = orig->src.l3num;
439 switch (orig->src.l3num) {
441 inverse->src.u3.ip = orig->dst.u3.ip;
442 inverse->dst.u3.ip = orig->src.u3.ip;
445 inverse->src.u3.in6 = orig->dst.u3.in6;
446 inverse->dst.u3.in6 = orig->src.u3.in6;
452 inverse->dst.dir = !orig->dst.dir;
454 inverse->dst.protonum = orig->dst.protonum;
456 switch (orig->dst.protonum) {
458 return nf_conntrack_invert_icmp_tuple(inverse, orig);
459 #if IS_ENABLED(CONFIG_IPV6)
461 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
465 inverse->src.u.all = orig->dst.u.all;
466 inverse->dst.u.all = orig->src.u.all;
469 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
471 /* Generate a almost-unique pseudo-id for a given conntrack.
473 * intentionally doesn't re-use any of the seeds used for hash
474 * table location, we assume id gets exposed to userspace.
476 * Following nf_conn items do not change throughout lifetime
480 * 2. nf_conn->master address (normally NULL)
481 * 3. the associated net namespace
482 * 4. the original direction tuple
484 u32 nf_ct_get_id(const struct nf_conn *ct)
486 static siphash_aligned_key_t ct_id_seed;
487 unsigned long a, b, c, d;
489 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
491 a = (unsigned long)ct;
492 b = (unsigned long)ct->master;
493 c = (unsigned long)nf_ct_net(ct);
494 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
495 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
498 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
500 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
503 EXPORT_SYMBOL_GPL(nf_ct_get_id);
506 clean_from_lists(struct nf_conn *ct)
508 pr_debug("clean_from_lists(%p)\n", ct);
509 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
510 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
512 /* Destroy all pending expectations */
513 nf_ct_remove_expectations(ct);
516 /* must be called with local_bh_disable */
517 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
519 struct ct_pcpu *pcpu;
521 /* add this conntrack to the (per cpu) dying list */
522 ct->cpu = smp_processor_id();
523 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
525 spin_lock(&pcpu->lock);
526 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
528 spin_unlock(&pcpu->lock);
531 /* must be called with local_bh_disable */
532 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
534 struct ct_pcpu *pcpu;
536 /* add this conntrack to the (per cpu) unconfirmed list */
537 ct->cpu = smp_processor_id();
538 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
540 spin_lock(&pcpu->lock);
541 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
543 spin_unlock(&pcpu->lock);
546 /* must be called with local_bh_disable */
547 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
549 struct ct_pcpu *pcpu;
551 /* We overload first tuple to link into unconfirmed or dying list.*/
552 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
554 spin_lock(&pcpu->lock);
555 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
556 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
557 spin_unlock(&pcpu->lock);
560 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
562 /* Released via nf_ct_destroy() */
563 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
564 const struct nf_conntrack_zone *zone,
567 struct nf_conn *tmpl, *p;
569 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
570 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
575 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
577 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
578 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
581 tmpl = kzalloc(sizeof(*tmpl), flags);
586 tmpl->status = IPS_TEMPLATE;
587 write_pnet(&tmpl->ct_net, net);
588 nf_ct_zone_add(tmpl, zone);
589 refcount_set(&tmpl->ct_general.use, 1);
593 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
595 void nf_ct_tmpl_free(struct nf_conn *tmpl)
597 nf_ct_ext_destroy(tmpl);
599 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
600 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
604 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
606 static void destroy_gre_conntrack(struct nf_conn *ct)
608 #ifdef CONFIG_NF_CT_PROTO_GRE
609 struct nf_conn *master = ct->master;
612 nf_ct_gre_keymap_destroy(master);
616 void nf_ct_destroy(struct nf_conntrack *nfct)
618 struct nf_conn *ct = (struct nf_conn *)nfct;
620 pr_debug("%s(%p)\n", __func__, ct);
621 WARN_ON(refcount_read(&nfct->use) != 0);
623 if (unlikely(nf_ct_is_template(ct))) {
628 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
629 destroy_gre_conntrack(ct);
632 /* Expectations will have been removed in clean_from_lists,
633 * except TFTP can create an expectation on the first packet,
634 * before connection is in the list, so we need to clean here,
637 nf_ct_remove_expectations(ct);
639 nf_ct_del_from_dying_or_unconfirmed_list(ct);
644 nf_ct_put(ct->master);
646 pr_debug("%s: returning ct=%p to slab\n", __func__, ct);
647 nf_conntrack_free(ct);
649 EXPORT_SYMBOL(nf_ct_destroy);
651 static void nf_ct_delete_from_lists(struct nf_conn *ct)
653 struct net *net = nf_ct_net(ct);
654 unsigned int hash, reply_hash;
655 unsigned int sequence;
657 nf_ct_helper_destroy(ct);
661 sequence = read_seqcount_begin(&nf_conntrack_generation);
662 hash = hash_conntrack(net,
663 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
664 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
665 reply_hash = hash_conntrack(net,
666 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
667 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
668 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
670 clean_from_lists(ct);
671 nf_conntrack_double_unlock(hash, reply_hash);
673 nf_ct_add_to_dying_list(ct);
678 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
680 struct nf_conn_tstamp *tstamp;
683 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
686 tstamp = nf_conn_tstamp_find(ct);
688 s32 timeout = READ_ONCE(ct->timeout) - nfct_time_stamp;
690 tstamp->stop = ktime_get_real_ns();
692 tstamp->stop -= jiffies_to_nsecs(-timeout);
695 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
696 portid, report) < 0) {
697 /* destroy event was not delivered. nf_ct_put will
698 * be done by event cache worker on redelivery.
700 nf_ct_delete_from_lists(ct);
701 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
706 if (nf_conntrack_ecache_dwork_pending(net))
707 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
708 nf_ct_delete_from_lists(ct);
712 EXPORT_SYMBOL_GPL(nf_ct_delete);
715 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
716 const struct nf_conntrack_tuple *tuple,
717 const struct nf_conntrack_zone *zone,
718 const struct net *net)
720 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
722 /* A conntrack can be recreated with the equal tuple,
723 * so we need to check that the conntrack is confirmed
725 return nf_ct_tuple_equal(tuple, &h->tuple) &&
726 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
727 nf_ct_is_confirmed(ct) &&
728 net_eq(net, nf_ct_net(ct));
732 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
734 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
735 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
736 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
737 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
738 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
739 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
740 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
743 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
744 static void nf_ct_gc_expired(struct nf_conn *ct)
746 if (!refcount_inc_not_zero(&ct->ct_general.use))
749 if (nf_ct_should_gc(ct))
757 * - Caller must take a reference on returned object
758 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
760 static struct nf_conntrack_tuple_hash *
761 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
762 const struct nf_conntrack_tuple *tuple, u32 hash)
764 struct nf_conntrack_tuple_hash *h;
765 struct hlist_nulls_head *ct_hash;
766 struct hlist_nulls_node *n;
767 unsigned int bucket, hsize;
770 nf_conntrack_get_ht(&ct_hash, &hsize);
771 bucket = reciprocal_scale(hash, hsize);
773 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
776 ct = nf_ct_tuplehash_to_ctrack(h);
777 if (nf_ct_is_expired(ct)) {
778 nf_ct_gc_expired(ct);
782 if (nf_ct_key_equal(h, tuple, zone, net))
786 * if the nulls value we got at the end of this lookup is
787 * not the expected one, we must restart lookup.
788 * We probably met an item that was moved to another chain.
790 if (get_nulls_value(n) != bucket) {
791 NF_CT_STAT_INC_ATOMIC(net, search_restart);
798 /* Find a connection corresponding to a tuple. */
799 static 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, u32 hash)
803 struct nf_conntrack_tuple_hash *h;
808 h = ____nf_conntrack_find(net, zone, tuple, hash);
810 /* We have a candidate that matches the tuple we're interested
811 * in, try to obtain a reference and re-check tuple
813 ct = nf_ct_tuplehash_to_ctrack(h);
814 if (likely(refcount_inc_not_zero(&ct->ct_general.use))) {
815 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
818 /* TYPESAFE_BY_RCU recycled the candidate */
830 struct nf_conntrack_tuple_hash *
831 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
832 const struct nf_conntrack_tuple *tuple)
834 unsigned int rid, zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
835 struct nf_conntrack_tuple_hash *thash;
837 thash = __nf_conntrack_find_get(net, zone, tuple,
838 hash_conntrack_raw(tuple, zone_id, net));
843 rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
845 return __nf_conntrack_find_get(net, zone, tuple,
846 hash_conntrack_raw(tuple, rid, net));
849 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
851 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
853 unsigned int reply_hash)
855 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
856 &nf_conntrack_hash[hash]);
857 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
858 &nf_conntrack_hash[reply_hash]);
862 nf_conntrack_hash_check_insert(struct nf_conn *ct)
864 const struct nf_conntrack_zone *zone;
865 struct net *net = nf_ct_net(ct);
866 unsigned int hash, reply_hash;
867 struct nf_conntrack_tuple_hash *h;
868 struct hlist_nulls_node *n;
869 unsigned int max_chainlen;
870 unsigned int chainlen = 0;
871 unsigned int sequence;
874 zone = nf_ct_zone(ct);
878 sequence = read_seqcount_begin(&nf_conntrack_generation);
879 hash = hash_conntrack(net,
880 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
881 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
882 reply_hash = hash_conntrack(net,
883 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
884 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
885 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
887 max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
889 /* See if there's one in the list already, including reverse */
890 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
891 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
895 if (chainlen++ > max_chainlen)
901 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
902 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
905 if (chainlen++ > max_chainlen)
910 /* The caller holds a reference to this object */
911 refcount_set(&ct->ct_general.use, 2);
912 __nf_conntrack_hash_insert(ct, hash, reply_hash);
913 nf_conntrack_double_unlock(hash, reply_hash);
914 NF_CT_STAT_INC(net, insert);
918 NF_CT_STAT_INC(net, chaintoolong);
921 nf_conntrack_double_unlock(hash, reply_hash);
925 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
927 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
930 struct nf_conn_acct *acct;
932 acct = nf_conn_acct_find(ct);
934 struct nf_conn_counter *counter = acct->counter;
936 atomic64_add(packets, &counter[dir].packets);
937 atomic64_add(bytes, &counter[dir].bytes);
940 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
942 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
943 const struct nf_conn *loser_ct)
945 struct nf_conn_acct *acct;
947 acct = nf_conn_acct_find(loser_ct);
949 struct nf_conn_counter *counter = acct->counter;
952 /* u32 should be fine since we must have seen one packet. */
953 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
954 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
958 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
960 struct nf_conn_tstamp *tstamp;
962 refcount_inc(&ct->ct_general.use);
963 ct->status |= IPS_CONFIRMED;
965 /* set conntrack timestamp, if enabled. */
966 tstamp = nf_conn_tstamp_find(ct);
968 tstamp->start = ktime_get_real_ns();
971 /* caller must hold locks to prevent concurrent changes */
972 static int __nf_ct_resolve_clash(struct sk_buff *skb,
973 struct nf_conntrack_tuple_hash *h)
975 /* This is the conntrack entry already in hashes that won race. */
976 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
977 enum ip_conntrack_info ctinfo;
978 struct nf_conn *loser_ct;
980 loser_ct = nf_ct_get(skb, &ctinfo);
982 if (nf_ct_is_dying(ct))
985 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
986 nf_ct_match(ct, loser_ct)) {
987 struct net *net = nf_ct_net(ct);
989 nf_conntrack_get(&ct->ct_general);
991 nf_ct_acct_merge(ct, ctinfo, loser_ct);
992 nf_ct_add_to_dying_list(loser_ct);
994 nf_ct_set(skb, ct, ctinfo);
996 NF_CT_STAT_INC(net, clash_resolve);
1004 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
1006 * @skb: skb that causes the collision
1007 * @repl_idx: hash slot for reply direction
1009 * Called when origin or reply direction had a clash.
1010 * The skb can be handled without packet drop provided the reply direction
1011 * is unique or there the existing entry has the identical tuple in both
1014 * Caller must hold conntrack table locks to prevent concurrent updates.
1016 * Returns NF_DROP if the clash could not be handled.
1018 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
1020 struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
1021 const struct nf_conntrack_zone *zone;
1022 struct nf_conntrack_tuple_hash *h;
1023 struct hlist_nulls_node *n;
1026 zone = nf_ct_zone(loser_ct);
1027 net = nf_ct_net(loser_ct);
1029 /* Reply direction must never result in a clash, unless both origin
1030 * and reply tuples are identical.
1032 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
1033 if (nf_ct_key_equal(h,
1034 &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1036 return __nf_ct_resolve_clash(skb, h);
1039 /* We want the clashing entry to go away real soon: 1 second timeout. */
1040 WRITE_ONCE(loser_ct->timeout, nfct_time_stamp + HZ);
1042 /* IPS_NAT_CLASH removes the entry automatically on the first
1043 * reply. Also prevents UDP tracker from moving the entry to
1044 * ASSURED state, i.e. the entry can always be evicted under
1047 loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
1049 __nf_conntrack_insert_prepare(loser_ct);
1051 /* fake add for ORIGINAL dir: we want lookups to only find the entry
1052 * already in the table. This also hides the clashing entry from
1053 * ctnetlink iteration, i.e. conntrack -L won't show them.
1055 hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1057 hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1058 &nf_conntrack_hash[repl_idx]);
1060 NF_CT_STAT_INC(net, clash_resolve);
1065 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1067 * @skb: skb that causes the clash
1068 * @h: tuplehash of the clashing entry already in table
1069 * @reply_hash: hash slot for reply direction
1071 * A conntrack entry can be inserted to the connection tracking table
1072 * if there is no existing entry with an identical tuple.
1074 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1075 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1076 * will find the already-existing entry.
1078 * The major problem with such packet drop is the extra delay added by
1079 * the packet loss -- it will take some time for a retransmit to occur
1080 * (or the sender to time out when waiting for a reply).
1082 * This function attempts to handle the situation without packet drop.
1084 * If @skb has no NAT transformation or if the colliding entries are
1085 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1086 * and @skb is associated with the conntrack entry already in the table.
1088 * Failing that, the new, unconfirmed conntrack is still added to the table
1089 * provided that the collision only occurs in the ORIGINAL direction.
1090 * The new entry will be added only in the non-clashing REPLY direction,
1091 * so packets in the ORIGINAL direction will continue to match the existing
1092 * entry. The new entry will also have a fixed timeout so it expires --
1093 * due to the collision, it will only see reply traffic.
1095 * Returns NF_DROP if the clash could not be resolved.
1097 static __cold noinline int
1098 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1101 /* This is the conntrack entry already in hashes that won race. */
1102 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1103 const struct nf_conntrack_l4proto *l4proto;
1104 enum ip_conntrack_info ctinfo;
1105 struct nf_conn *loser_ct;
1109 loser_ct = nf_ct_get(skb, &ctinfo);
1110 net = nf_ct_net(loser_ct);
1112 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1113 if (!l4proto->allow_clash)
1116 ret = __nf_ct_resolve_clash(skb, h);
1117 if (ret == NF_ACCEPT)
1120 ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1121 if (ret == NF_ACCEPT)
1125 nf_ct_add_to_dying_list(loser_ct);
1126 NF_CT_STAT_INC(net, drop);
1127 NF_CT_STAT_INC(net, insert_failed);
1131 /* Confirm a connection given skb; places it in hash table */
1133 __nf_conntrack_confirm(struct sk_buff *skb)
1135 unsigned int chainlen = 0, sequence, max_chainlen;
1136 const struct nf_conntrack_zone *zone;
1137 unsigned int hash, reply_hash;
1138 struct nf_conntrack_tuple_hash *h;
1140 struct nf_conn_help *help;
1141 struct hlist_nulls_node *n;
1142 enum ip_conntrack_info ctinfo;
1146 ct = nf_ct_get(skb, &ctinfo);
1147 net = nf_ct_net(ct);
1149 /* ipt_REJECT uses nf_conntrack_attach to attach related
1150 ICMP/TCP RST packets in other direction. Actual packet
1151 which created connection will be IP_CT_NEW or for an
1152 expected connection, IP_CT_RELATED. */
1153 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1156 zone = nf_ct_zone(ct);
1160 sequence = read_seqcount_begin(&nf_conntrack_generation);
1161 /* reuse the hash saved before */
1162 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1163 hash = scale_hash(hash);
1164 reply_hash = hash_conntrack(net,
1165 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1166 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
1167 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1169 /* We're not in hash table, and we refuse to set up related
1170 * connections for unconfirmed conns. But packet copies and
1171 * REJECT will give spurious warnings here.
1174 /* Another skb with the same unconfirmed conntrack may
1175 * win the race. This may happen for bridge(br_flood)
1176 * or broadcast/multicast packets do skb_clone with
1177 * unconfirmed conntrack.
1179 if (unlikely(nf_ct_is_confirmed(ct))) {
1181 nf_conntrack_double_unlock(hash, reply_hash);
1186 pr_debug("Confirming conntrack %p\n", ct);
1187 /* We have to check the DYING flag after unlink to prevent
1188 * a race against nf_ct_get_next_corpse() possibly called from
1189 * user context, else we insert an already 'dead' hash, blocking
1190 * further use of that particular connection -JM.
1192 nf_ct_del_from_dying_or_unconfirmed_list(ct);
1194 if (unlikely(nf_ct_is_dying(ct))) {
1195 nf_ct_add_to_dying_list(ct);
1196 NF_CT_STAT_INC(net, insert_failed);
1200 max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
1201 /* See if there's one in the list already, including reverse:
1202 NAT could have grabbed it without realizing, since we're
1203 not in the hash. If there is, we lost race. */
1204 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
1205 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1208 if (chainlen++ > max_chainlen)
1213 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
1214 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1217 if (chainlen++ > max_chainlen) {
1219 nf_ct_add_to_dying_list(ct);
1220 NF_CT_STAT_INC(net, chaintoolong);
1221 NF_CT_STAT_INC(net, insert_failed);
1227 /* Timer relative to confirmation time, not original
1228 setting time, otherwise we'd get timer wrap in
1229 weird delay cases. */
1230 ct->timeout += nfct_time_stamp;
1232 __nf_conntrack_insert_prepare(ct);
1234 /* Since the lookup is lockless, hash insertion must be done after
1235 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1236 * guarantee that no other CPU can find the conntrack before the above
1237 * stores are visible.
1239 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1240 nf_conntrack_double_unlock(hash, reply_hash);
1243 help = nfct_help(ct);
1244 if (help && help->helper)
1245 nf_conntrack_event_cache(IPCT_HELPER, ct);
1247 nf_conntrack_event_cache(master_ct(ct) ?
1248 IPCT_RELATED : IPCT_NEW, ct);
1252 ret = nf_ct_resolve_clash(skb, h, reply_hash);
1254 nf_conntrack_double_unlock(hash, reply_hash);
1258 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1260 /* Returns true if a connection correspondings to the tuple (required
1263 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1264 const struct nf_conn *ignored_conntrack)
1266 struct net *net = nf_ct_net(ignored_conntrack);
1267 const struct nf_conntrack_zone *zone;
1268 struct nf_conntrack_tuple_hash *h;
1269 struct hlist_nulls_head *ct_hash;
1270 unsigned int hash, hsize;
1271 struct hlist_nulls_node *n;
1274 zone = nf_ct_zone(ignored_conntrack);
1278 nf_conntrack_get_ht(&ct_hash, &hsize);
1279 hash = __hash_conntrack(net, tuple, nf_ct_zone_id(zone, IP_CT_DIR_REPLY), hsize);
1281 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1282 ct = nf_ct_tuplehash_to_ctrack(h);
1284 if (ct == ignored_conntrack)
1287 if (nf_ct_is_expired(ct)) {
1288 nf_ct_gc_expired(ct);
1292 if (nf_ct_key_equal(h, tuple, zone, net)) {
1293 /* Tuple is taken already, so caller will need to find
1294 * a new source port to use.
1297 * If the *original tuples* are identical, then both
1298 * conntracks refer to the same flow.
1299 * This is a rare situation, it can occur e.g. when
1300 * more than one UDP packet is sent from same socket
1301 * in different threads.
1303 * Let nf_ct_resolve_clash() deal with this later.
1305 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1306 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1307 nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1310 NF_CT_STAT_INC_ATOMIC(net, found);
1316 if (get_nulls_value(n) != hash) {
1317 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1325 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1327 #define NF_CT_EVICTION_RANGE 8
1329 /* There's a small race here where we may free a just-assured
1330 connection. Too bad: we're in trouble anyway. */
1331 static unsigned int early_drop_list(struct net *net,
1332 struct hlist_nulls_head *head)
1334 struct nf_conntrack_tuple_hash *h;
1335 struct hlist_nulls_node *n;
1336 unsigned int drops = 0;
1337 struct nf_conn *tmp;
1339 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1340 tmp = nf_ct_tuplehash_to_ctrack(h);
1342 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1345 if (nf_ct_is_expired(tmp)) {
1346 nf_ct_gc_expired(tmp);
1350 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1351 !net_eq(nf_ct_net(tmp), net) ||
1352 nf_ct_is_dying(tmp))
1355 if (!refcount_inc_not_zero(&tmp->ct_general.use))
1358 /* kill only if still in same netns -- might have moved due to
1359 * SLAB_TYPESAFE_BY_RCU rules.
1361 * We steal the timer reference. If that fails timer has
1362 * already fired or someone else deleted it. Just drop ref
1363 * and move to next entry.
1365 if (net_eq(nf_ct_net(tmp), net) &&
1366 nf_ct_is_confirmed(tmp) &&
1367 nf_ct_delete(tmp, 0, 0))
1376 static noinline int early_drop(struct net *net, unsigned int hash)
1378 unsigned int i, bucket;
1380 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1381 struct hlist_nulls_head *ct_hash;
1382 unsigned int hsize, drops;
1385 nf_conntrack_get_ht(&ct_hash, &hsize);
1387 bucket = reciprocal_scale(hash, hsize);
1389 bucket = (bucket + 1) % hsize;
1391 drops = early_drop_list(net, &ct_hash[bucket]);
1395 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1403 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1405 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1408 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1410 const struct nf_conntrack_l4proto *l4proto;
1412 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1415 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1416 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1422 static void gc_worker(struct work_struct *work)
1424 unsigned long end_time = jiffies + GC_SCAN_MAX_DURATION;
1425 unsigned int i, hashsz, nf_conntrack_max95 = 0;
1426 unsigned long next_run = GC_SCAN_INTERVAL;
1427 struct conntrack_gc_work *gc_work;
1428 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1430 i = gc_work->next_bucket;
1431 if (gc_work->early_drop)
1432 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1435 struct nf_conntrack_tuple_hash *h;
1436 struct hlist_nulls_head *ct_hash;
1437 struct hlist_nulls_node *n;
1438 struct nf_conn *tmp;
1442 nf_conntrack_get_ht(&ct_hash, &hashsz);
1448 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1449 struct nf_conntrack_net *cnet;
1452 tmp = nf_ct_tuplehash_to_ctrack(h);
1454 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1455 nf_ct_offload_timeout(tmp);
1459 if (nf_ct_is_expired(tmp)) {
1460 nf_ct_gc_expired(tmp);
1464 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1467 net = nf_ct_net(tmp);
1468 cnet = nf_ct_pernet(net);
1469 if (atomic_read(&cnet->count) < nf_conntrack_max95)
1472 /* need to take reference to avoid possible races */
1473 if (!refcount_inc_not_zero(&tmp->ct_general.use))
1476 if (gc_worker_skip_ct(tmp)) {
1481 if (gc_worker_can_early_drop(tmp))
1487 /* could check get_nulls_value() here and restart if ct
1488 * was moved to another chain. But given gc is best-effort
1489 * we will just continue with next hash slot.
1495 if (time_after(jiffies, end_time) && i < hashsz) {
1496 gc_work->next_bucket = i;
1500 } while (i < hashsz);
1502 if (gc_work->exiting)
1506 * Eviction will normally happen from the packet path, and not
1507 * from this gc worker.
1509 * This worker is only here to reap expired entries when system went
1510 * idle after a busy period.
1513 gc_work->early_drop = false;
1514 gc_work->next_bucket = 0;
1516 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1519 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1521 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1522 gc_work->exiting = false;
1525 static struct nf_conn *
1526 __nf_conntrack_alloc(struct net *net,
1527 const struct nf_conntrack_zone *zone,
1528 const struct nf_conntrack_tuple *orig,
1529 const struct nf_conntrack_tuple *repl,
1530 gfp_t gfp, u32 hash)
1532 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
1533 unsigned int ct_count;
1536 /* We don't want any race condition at early drop stage */
1537 ct_count = atomic_inc_return(&cnet->count);
1539 if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1540 if (!early_drop(net, hash)) {
1541 if (!conntrack_gc_work.early_drop)
1542 conntrack_gc_work.early_drop = true;
1543 atomic_dec(&cnet->count);
1544 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1545 return ERR_PTR(-ENOMEM);
1550 * Do not use kmem_cache_zalloc(), as this cache uses
1551 * SLAB_TYPESAFE_BY_RCU.
1553 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1557 spin_lock_init(&ct->lock);
1558 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1559 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1560 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1561 /* save hash for reusing when confirming */
1562 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1564 WRITE_ONCE(ct->timeout, 0);
1565 write_pnet(&ct->ct_net, net);
1566 memset_after(ct, 0, __nfct_init_offset);
1568 nf_ct_zone_add(ct, zone);
1570 /* Because we use RCU lookups, we set ct_general.use to zero before
1571 * this is inserted in any list.
1573 refcount_set(&ct->ct_general.use, 0);
1576 atomic_dec(&cnet->count);
1577 return ERR_PTR(-ENOMEM);
1580 struct nf_conn *nf_conntrack_alloc(struct net *net,
1581 const struct nf_conntrack_zone *zone,
1582 const struct nf_conntrack_tuple *orig,
1583 const struct nf_conntrack_tuple *repl,
1586 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1588 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1590 void nf_conntrack_free(struct nf_conn *ct)
1592 struct net *net = nf_ct_net(ct);
1593 struct nf_conntrack_net *cnet;
1595 /* A freed object has refcnt == 0, that's
1596 * the golden rule for SLAB_TYPESAFE_BY_RCU
1598 WARN_ON(refcount_read(&ct->ct_general.use) != 0);
1600 nf_ct_ext_destroy(ct);
1601 kmem_cache_free(nf_conntrack_cachep, ct);
1602 cnet = nf_ct_pernet(net);
1604 smp_mb__before_atomic();
1605 atomic_dec(&cnet->count);
1607 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1610 /* Allocate a new conntrack: we return -ENOMEM if classification
1611 failed due to stress. Otherwise it really is unclassifiable. */
1612 static noinline struct nf_conntrack_tuple_hash *
1613 init_conntrack(struct net *net, struct nf_conn *tmpl,
1614 const struct nf_conntrack_tuple *tuple,
1615 struct sk_buff *skb,
1616 unsigned int dataoff, u32 hash)
1619 struct nf_conn_help *help;
1620 struct nf_conntrack_tuple repl_tuple;
1621 struct nf_conntrack_ecache *ecache;
1622 struct nf_conntrack_expect *exp = NULL;
1623 const struct nf_conntrack_zone *zone;
1624 struct nf_conn_timeout *timeout_ext;
1625 struct nf_conntrack_zone tmp;
1626 struct nf_conntrack_net *cnet;
1628 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1629 pr_debug("Can't invert tuple.\n");
1633 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1634 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1637 return (struct nf_conntrack_tuple_hash *)ct;
1639 if (!nf_ct_add_synproxy(ct, tmpl)) {
1640 nf_conntrack_free(ct);
1641 return ERR_PTR(-ENOMEM);
1644 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1647 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1650 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1651 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1652 nf_ct_labels_ext_add(ct);
1654 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1655 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1656 ecache ? ecache->expmask : 0,
1660 cnet = nf_ct_pernet(net);
1661 if (cnet->expect_count) {
1662 spin_lock(&nf_conntrack_expect_lock);
1663 exp = nf_ct_find_expectation(net, zone, tuple);
1665 pr_debug("expectation arrives ct=%p exp=%p\n",
1667 /* Welcome, Mr. Bond. We've been expecting you... */
1668 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1669 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1670 ct->master = exp->master;
1672 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1674 rcu_assign_pointer(help->helper, exp->helper);
1677 #ifdef CONFIG_NF_CONNTRACK_MARK
1678 ct->mark = exp->master->mark;
1680 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1681 ct->secmark = exp->master->secmark;
1683 NF_CT_STAT_INC(net, expect_new);
1685 spin_unlock(&nf_conntrack_expect_lock);
1688 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1690 /* Now it is inserted into the unconfirmed list, set refcount to 1. */
1691 refcount_set(&ct->ct_general.use, 1);
1692 nf_ct_add_to_unconfirmed_list(ct);
1698 exp->expectfn(ct, exp);
1699 nf_ct_expect_put(exp);
1702 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1705 /* On success, returns 0, sets skb->_nfct | ctinfo */
1707 resolve_normal_ct(struct nf_conn *tmpl,
1708 struct sk_buff *skb,
1709 unsigned int dataoff,
1711 const struct nf_hook_state *state)
1713 const struct nf_conntrack_zone *zone;
1714 struct nf_conntrack_tuple tuple;
1715 struct nf_conntrack_tuple_hash *h;
1716 enum ip_conntrack_info ctinfo;
1717 struct nf_conntrack_zone tmp;
1718 u32 hash, zone_id, rid;
1721 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1722 dataoff, state->pf, protonum, state->net,
1724 pr_debug("Can't get tuple\n");
1728 /* look for tuple match */
1729 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1731 zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
1732 hash = hash_conntrack_raw(&tuple, zone_id, state->net);
1733 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1736 rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
1737 if (zone_id != rid) {
1738 u32 tmp = hash_conntrack_raw(&tuple, rid, state->net);
1740 h = __nf_conntrack_find_get(state->net, zone, &tuple, tmp);
1745 h = init_conntrack(state->net, tmpl, &tuple,
1746 skb, dataoff, hash);
1752 ct = nf_ct_tuplehash_to_ctrack(h);
1753 ct->local_origin = state->hook == NF_INET_LOCAL_OUT;
1755 ct = nf_ct_tuplehash_to_ctrack(h);
1757 /* It exists; we have (non-exclusive) reference. */
1758 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1759 ctinfo = IP_CT_ESTABLISHED_REPLY;
1761 /* Once we've had two way comms, always ESTABLISHED. */
1762 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1763 pr_debug("normal packet for %p\n", ct);
1764 ctinfo = IP_CT_ESTABLISHED;
1765 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1766 pr_debug("related packet for %p\n", ct);
1767 ctinfo = IP_CT_RELATED;
1769 pr_debug("new packet for %p\n", ct);
1773 nf_ct_set(skb, ct, ctinfo);
1778 * icmp packets need special treatment to handle error messages that are
1779 * related to a connection.
1781 * Callers need to check if skb has a conntrack assigned when this
1782 * helper returns; in such case skb belongs to an already known connection.
1784 static unsigned int __cold
1785 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1786 struct sk_buff *skb,
1787 unsigned int dataoff,
1789 const struct nf_hook_state *state)
1793 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1794 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1795 #if IS_ENABLED(CONFIG_IPV6)
1796 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1797 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1803 NF_CT_STAT_INC_ATOMIC(state->net, error);
1808 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1809 enum ip_conntrack_info ctinfo)
1811 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1814 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1816 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1820 /* Returns verdict for packet, or -1 for invalid. */
1821 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1822 struct sk_buff *skb,
1823 unsigned int dataoff,
1824 enum ip_conntrack_info ctinfo,
1825 const struct nf_hook_state *state)
1827 switch (nf_ct_protonum(ct)) {
1829 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1832 return nf_conntrack_udp_packet(ct, skb, dataoff,
1835 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1836 #if IS_ENABLED(CONFIG_IPV6)
1837 case IPPROTO_ICMPV6:
1838 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1840 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1841 case IPPROTO_UDPLITE:
1842 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1845 #ifdef CONFIG_NF_CT_PROTO_SCTP
1847 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1850 #ifdef CONFIG_NF_CT_PROTO_DCCP
1852 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1855 #ifdef CONFIG_NF_CT_PROTO_GRE
1857 return nf_conntrack_gre_packet(ct, skb, dataoff,
1862 return generic_packet(ct, skb, ctinfo);
1866 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1868 enum ip_conntrack_info ctinfo;
1869 struct nf_conn *ct, *tmpl;
1873 tmpl = nf_ct_get(skb, &ctinfo);
1874 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1875 /* Previously seen (loopback or untracked)? Ignore. */
1876 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1877 ctinfo == IP_CT_UNTRACKED)
1882 /* rcu_read_lock()ed by nf_hook_thresh */
1883 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1885 pr_debug("not prepared to track yet or error occurred\n");
1886 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1891 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1892 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1898 /* ICMP[v6] protocol trackers may assign one conntrack. */
1903 ret = resolve_normal_ct(tmpl, skb, dataoff,
1906 /* Too stressed to deal. */
1907 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1912 ct = nf_ct_get(skb, &ctinfo);
1914 /* Not valid part of a connection */
1915 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1920 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1922 /* Invalid: inverse of the return code tells
1923 * the netfilter core what to do */
1924 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1927 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1928 if (ret == -NF_DROP)
1929 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1930 /* Special case: TCP tracker reports an attempt to reopen a
1931 * closed/aborted connection. We have to go back and create a
1934 if (ret == -NF_REPEAT)
1940 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1941 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1942 nf_conntrack_event_cache(IPCT_REPLY, ct);
1949 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1951 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1952 implicitly racy: see __nf_conntrack_confirm */
1953 void nf_conntrack_alter_reply(struct nf_conn *ct,
1954 const struct nf_conntrack_tuple *newreply)
1956 struct nf_conn_help *help = nfct_help(ct);
1958 /* Should be unconfirmed, so not in hash table yet */
1959 WARN_ON(nf_ct_is_confirmed(ct));
1961 pr_debug("Altering reply tuple of %p to ", ct);
1962 nf_ct_dump_tuple(newreply);
1964 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1965 if (ct->master || (help && !hlist_empty(&help->expectations)))
1969 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1972 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1974 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1975 void __nf_ct_refresh_acct(struct nf_conn *ct,
1976 enum ip_conntrack_info ctinfo,
1977 const struct sk_buff *skb,
1981 /* Only update if this is not a fixed timeout */
1982 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1985 /* If not in hash table, timer will not be active yet */
1986 if (nf_ct_is_confirmed(ct))
1987 extra_jiffies += nfct_time_stamp;
1989 if (READ_ONCE(ct->timeout) != extra_jiffies)
1990 WRITE_ONCE(ct->timeout, extra_jiffies);
1993 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1995 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1997 bool nf_ct_kill_acct(struct nf_conn *ct,
1998 enum ip_conntrack_info ctinfo,
1999 const struct sk_buff *skb)
2001 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
2003 return nf_ct_delete(ct, 0, 0);
2005 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
2007 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
2009 #include <linux/netfilter/nfnetlink.h>
2010 #include <linux/netfilter/nfnetlink_conntrack.h>
2011 #include <linux/mutex.h>
2013 /* Generic function for tcp/udp/sctp/dccp and alike. */
2014 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
2015 const struct nf_conntrack_tuple *tuple)
2017 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
2018 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
2019 goto nla_put_failure;
2025 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
2027 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
2028 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
2029 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
2031 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
2033 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
2034 struct nf_conntrack_tuple *t,
2037 if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
2038 if (!tb[CTA_PROTO_SRC_PORT])
2041 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
2044 if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
2045 if (!tb[CTA_PROTO_DST_PORT])
2048 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
2053 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
2055 unsigned int nf_ct_port_nlattr_tuple_size(void)
2057 static unsigned int size __read_mostly;
2060 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2064 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2067 /* Used by ipt_REJECT and ip6t_REJECT. */
2068 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2071 enum ip_conntrack_info ctinfo;
2073 /* This ICMP is in reverse direction to the packet which caused it */
2074 ct = nf_ct_get(skb, &ctinfo);
2075 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2076 ctinfo = IP_CT_RELATED_REPLY;
2078 ctinfo = IP_CT_RELATED;
2080 /* Attach to new skbuff, and increment count */
2081 nf_ct_set(nskb, ct, ctinfo);
2082 nf_conntrack_get(skb_nfct(nskb));
2085 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2087 enum ip_conntrack_info ctinfo)
2089 const struct nf_nat_hook *nat_hook;
2090 struct nf_conntrack_tuple_hash *h;
2091 struct nf_conntrack_tuple tuple;
2092 unsigned int status;
2097 l3num = nf_ct_l3num(ct);
2099 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2103 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2104 l4num, net, &tuple))
2107 if (ct->status & IPS_SRC_NAT) {
2108 memcpy(tuple.src.u3.all,
2109 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2110 sizeof(tuple.src.u3.all));
2112 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2115 if (ct->status & IPS_DST_NAT) {
2116 memcpy(tuple.dst.u3.all,
2117 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2118 sizeof(tuple.dst.u3.all));
2120 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2123 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2127 /* Store status bits of the conntrack that is clashing to re-do NAT
2128 * mangling according to what it has been done already to this packet.
2130 status = ct->status;
2133 ct = nf_ct_tuplehash_to_ctrack(h);
2134 nf_ct_set(skb, ct, ctinfo);
2136 nat_hook = rcu_dereference(nf_nat_hook);
2140 if (status & IPS_SRC_NAT &&
2141 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2142 IP_CT_DIR_ORIGINAL) == NF_DROP)
2145 if (status & IPS_DST_NAT &&
2146 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2147 IP_CT_DIR_ORIGINAL) == NF_DROP)
2153 /* This packet is coming from userspace via nf_queue, complete the packet
2154 * processing after the helper invocation in nf_confirm().
2156 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2157 enum ip_conntrack_info ctinfo)
2159 const struct nf_conntrack_helper *helper;
2160 const struct nf_conn_help *help;
2163 help = nfct_help(ct);
2167 helper = rcu_dereference(help->helper);
2168 if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2171 switch (nf_ct_l3num(ct)) {
2173 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2175 #if IS_ENABLED(CONFIG_IPV6)
2176 case NFPROTO_IPV6: {
2180 pnum = ipv6_hdr(skb)->nexthdr;
2181 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2183 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2192 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2193 !nf_is_loopback_packet(skb)) {
2194 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2195 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2200 /* We've seen it coming out the other side: confirm it */
2201 return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2204 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2206 enum ip_conntrack_info ctinfo;
2210 ct = nf_ct_get(skb, &ctinfo);
2214 if (!nf_ct_is_confirmed(ct)) {
2215 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2219 ct = nf_ct_get(skb, &ctinfo);
2222 return nf_confirm_cthelper(skb, ct, ctinfo);
2225 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2226 const struct sk_buff *skb)
2228 const struct nf_conntrack_tuple *src_tuple;
2229 const struct nf_conntrack_tuple_hash *hash;
2230 struct nf_conntrack_tuple srctuple;
2231 enum ip_conntrack_info ctinfo;
2234 ct = nf_ct_get(skb, &ctinfo);
2236 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2237 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2241 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2242 NFPROTO_IPV4, dev_net(skb->dev),
2246 hash = nf_conntrack_find_get(dev_net(skb->dev),
2252 ct = nf_ct_tuplehash_to_ctrack(hash);
2253 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2254 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2260 /* Bring out ya dead! */
2261 static struct nf_conn *
2262 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2263 void *data, unsigned int *bucket)
2265 struct nf_conntrack_tuple_hash *h;
2267 struct hlist_nulls_node *n;
2270 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2271 struct hlist_nulls_head *hslot = &nf_conntrack_hash[*bucket];
2273 if (hlist_nulls_empty(hslot))
2276 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2278 nf_conntrack_lock(lockp);
2279 hlist_nulls_for_each_entry(h, n, hslot, hnnode) {
2280 if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2282 /* All nf_conn objects are added to hash table twice, one
2283 * for original direction tuple, once for the reply tuple.
2285 * Exception: In the IPS_NAT_CLASH case, only the reply
2286 * tuple is added (the original tuple already existed for
2287 * a different object).
2289 * We only need to call the iterator once for each
2290 * conntrack, so we just use the 'reply' direction
2291 * tuple while iterating.
2293 ct = nf_ct_tuplehash_to_ctrack(h);
2304 refcount_inc(&ct->ct_general.use);
2310 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2311 void *data, u32 portid, int report)
2313 unsigned int bucket = 0;
2318 mutex_lock(&nf_conntrack_mutex);
2319 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2320 /* Time to push up daises... */
2322 nf_ct_delete(ct, portid, report);
2326 mutex_unlock(&nf_conntrack_mutex);
2330 int (*iter)(struct nf_conn *i, void *data);
2335 static int iter_net_only(struct nf_conn *i, void *data)
2337 struct iter_data *d = data;
2339 if (!net_eq(d->net, nf_ct_net(i)))
2342 return d->iter(i, d->data);
2346 __nf_ct_unconfirmed_destroy(struct net *net)
2350 for_each_possible_cpu(cpu) {
2351 struct nf_conntrack_tuple_hash *h;
2352 struct hlist_nulls_node *n;
2353 struct ct_pcpu *pcpu;
2355 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2357 spin_lock_bh(&pcpu->lock);
2358 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2361 ct = nf_ct_tuplehash_to_ctrack(h);
2363 /* we cannot call iter() on unconfirmed list, the
2364 * owning cpu can reallocate ct->ext at any time.
2366 set_bit(IPS_DYING_BIT, &ct->status);
2368 spin_unlock_bh(&pcpu->lock);
2373 void nf_ct_unconfirmed_destroy(struct net *net)
2375 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2379 if (atomic_read(&cnet->count) > 0) {
2380 __nf_ct_unconfirmed_destroy(net);
2381 nf_queue_nf_hook_drop(net);
2385 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2387 void nf_ct_iterate_cleanup_net(struct net *net,
2388 int (*iter)(struct nf_conn *i, void *data),
2389 void *data, u32 portid, int report)
2391 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2396 if (atomic_read(&cnet->count) == 0)
2403 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2405 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2408 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2409 * @iter: callback to invoke for each conntrack
2410 * @data: data to pass to @iter
2412 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2413 * unconfirmed list as dying (so they will not be inserted into
2416 * Can only be called in module exit path.
2419 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2423 down_read(&net_rwsem);
2425 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2427 if (atomic_read(&cnet->count) == 0)
2429 __nf_ct_unconfirmed_destroy(net);
2430 nf_queue_nf_hook_drop(net);
2432 up_read(&net_rwsem);
2434 /* Need to wait for netns cleanup worker to finish, if its
2435 * running -- it might have deleted a net namespace from
2436 * the global list, so our __nf_ct_unconfirmed_destroy() might
2437 * not have affected all namespaces.
2441 /* a conntrack could have been unlinked from unconfirmed list
2442 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2443 * This makes sure its inserted into conntrack table.
2447 nf_ct_iterate_cleanup(iter, data, 0, 0);
2449 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2451 static int kill_all(struct nf_conn *i, void *data)
2453 return net_eq(nf_ct_net(i), data);
2456 void nf_conntrack_cleanup_start(void)
2458 conntrack_gc_work.exiting = true;
2461 void nf_conntrack_cleanup_end(void)
2463 RCU_INIT_POINTER(nf_ct_hook, NULL);
2464 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2465 kvfree(nf_conntrack_hash);
2467 nf_conntrack_proto_fini();
2468 nf_conntrack_seqadj_fini();
2469 nf_conntrack_labels_fini();
2470 nf_conntrack_helper_fini();
2471 nf_conntrack_timeout_fini();
2472 nf_conntrack_ecache_fini();
2473 nf_conntrack_tstamp_fini();
2474 nf_conntrack_acct_fini();
2475 nf_conntrack_expect_fini();
2477 kmem_cache_destroy(nf_conntrack_cachep);
2481 * Mishearing the voices in his head, our hero wonders how he's
2482 * supposed to kill the mall.
2484 void nf_conntrack_cleanup_net(struct net *net)
2488 list_add(&net->exit_list, &single);
2489 nf_conntrack_cleanup_net_list(&single);
2492 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2498 * This makes sure all current packets have passed through
2499 * netfilter framework. Roll on, two-stage module
2505 list_for_each_entry(net, net_exit_list, exit_list) {
2506 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2508 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2509 if (atomic_read(&cnet->count) != 0)
2514 goto i_see_dead_people;
2517 list_for_each_entry(net, net_exit_list, exit_list) {
2518 nf_conntrack_ecache_pernet_fini(net);
2519 nf_conntrack_expect_pernet_fini(net);
2520 free_percpu(net->ct.stat);
2521 free_percpu(net->ct.pcpu_lists);
2525 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2527 struct hlist_nulls_head *hash;
2528 unsigned int nr_slots, i;
2530 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2533 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2534 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2536 hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2539 for (i = 0; i < nr_slots; i++)
2540 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2544 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2546 int nf_conntrack_hash_resize(unsigned int hashsize)
2549 unsigned int old_size;
2550 struct hlist_nulls_head *hash, *old_hash;
2551 struct nf_conntrack_tuple_hash *h;
2557 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2561 mutex_lock(&nf_conntrack_mutex);
2562 old_size = nf_conntrack_htable_size;
2563 if (old_size == hashsize) {
2564 mutex_unlock(&nf_conntrack_mutex);
2570 nf_conntrack_all_lock();
2571 write_seqcount_begin(&nf_conntrack_generation);
2573 /* Lookups in the old hash might happen in parallel, which means we
2574 * might get false negatives during connection lookup. New connections
2575 * created because of a false negative won't make it into the hash
2576 * though since that required taking the locks.
2579 for (i = 0; i < nf_conntrack_htable_size; i++) {
2580 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2581 unsigned int zone_id;
2583 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2584 struct nf_conntrack_tuple_hash, hnnode);
2585 ct = nf_ct_tuplehash_to_ctrack(h);
2586 hlist_nulls_del_rcu(&h->hnnode);
2588 zone_id = nf_ct_zone_id(nf_ct_zone(ct), NF_CT_DIRECTION(h));
2589 bucket = __hash_conntrack(nf_ct_net(ct),
2590 &h->tuple, zone_id, hashsize);
2591 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2594 old_hash = nf_conntrack_hash;
2596 nf_conntrack_hash = hash;
2597 nf_conntrack_htable_size = hashsize;
2599 write_seqcount_end(&nf_conntrack_generation);
2600 nf_conntrack_all_unlock();
2603 mutex_unlock(&nf_conntrack_mutex);
2610 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2612 unsigned int hashsize;
2615 if (current->nsproxy->net_ns != &init_net)
2618 /* On boot, we can set this without any fancy locking. */
2619 if (!nf_conntrack_hash)
2620 return param_set_uint(val, kp);
2622 rc = kstrtouint(val, 0, &hashsize);
2626 return nf_conntrack_hash_resize(hashsize);
2629 static __always_inline unsigned int total_extension_size(void)
2631 /* remember to add new extensions below */
2632 BUILD_BUG_ON(NF_CT_EXT_NUM > 10);
2634 return sizeof(struct nf_ct_ext) +
2635 sizeof(struct nf_conn_help)
2636 #if IS_ENABLED(CONFIG_NF_NAT)
2637 + sizeof(struct nf_conn_nat)
2639 + sizeof(struct nf_conn_seqadj)
2640 + sizeof(struct nf_conn_acct)
2641 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2642 + sizeof(struct nf_conntrack_ecache)
2644 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2645 + sizeof(struct nf_conn_tstamp)
2647 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2648 + sizeof(struct nf_conn_timeout)
2650 #ifdef CONFIG_NF_CONNTRACK_LABELS
2651 + sizeof(struct nf_conn_labels)
2653 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2654 + sizeof(struct nf_conn_synproxy)
2656 #if IS_ENABLED(CONFIG_NET_ACT_CT)
2657 + sizeof(struct nf_conn_act_ct_ext)
2662 int nf_conntrack_init_start(void)
2664 unsigned long nr_pages = totalram_pages();
2669 /* struct nf_ct_ext uses u8 to store offsets/size */
2670 BUILD_BUG_ON(total_extension_size() > 255u);
2672 seqcount_spinlock_init(&nf_conntrack_generation,
2673 &nf_conntrack_locks_all_lock);
2675 for (i = 0; i < CONNTRACK_LOCKS; i++)
2676 spin_lock_init(&nf_conntrack_locks[i]);
2678 if (!nf_conntrack_htable_size) {
2679 nf_conntrack_htable_size
2680 = (((nr_pages << PAGE_SHIFT) / 16384)
2681 / sizeof(struct hlist_head));
2682 if (BITS_PER_LONG >= 64 &&
2683 nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2684 nf_conntrack_htable_size = 262144;
2685 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2686 nf_conntrack_htable_size = 65536;
2688 if (nf_conntrack_htable_size < 1024)
2689 nf_conntrack_htable_size = 1024;
2690 /* Use a max. factor of one by default to keep the average
2691 * hash chain length at 2 entries. Each entry has to be added
2692 * twice (once for original direction, once for reply).
2693 * When a table size is given we use the old value of 8 to
2694 * avoid implicit reduction of the max entries setting.
2699 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2700 if (!nf_conntrack_hash)
2703 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2705 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2706 sizeof(struct nf_conn),
2708 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2709 if (!nf_conntrack_cachep)
2712 ret = nf_conntrack_expect_init();
2716 ret = nf_conntrack_acct_init();
2720 ret = nf_conntrack_tstamp_init();
2724 ret = nf_conntrack_ecache_init();
2728 ret = nf_conntrack_timeout_init();
2732 ret = nf_conntrack_helper_init();
2736 ret = nf_conntrack_labels_init();
2740 ret = nf_conntrack_seqadj_init();
2744 ret = nf_conntrack_proto_init();
2748 conntrack_gc_work_init(&conntrack_gc_work);
2749 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2754 nf_conntrack_seqadj_fini();
2756 nf_conntrack_labels_fini();
2758 nf_conntrack_helper_fini();
2760 nf_conntrack_timeout_fini();
2762 nf_conntrack_ecache_fini();
2764 nf_conntrack_tstamp_fini();
2766 nf_conntrack_acct_fini();
2768 nf_conntrack_expect_fini();
2770 kmem_cache_destroy(nf_conntrack_cachep);
2772 kvfree(nf_conntrack_hash);
2776 static const struct nf_ct_hook nf_conntrack_hook = {
2777 .update = nf_conntrack_update,
2778 .destroy = nf_ct_destroy,
2779 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2780 .attach = nf_conntrack_attach,
2783 void nf_conntrack_init_end(void)
2785 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2789 * We need to use special "null" values, not used in hash table
2791 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2792 #define DYING_NULLS_VAL ((1<<30)+1)
2794 int nf_conntrack_init_net(struct net *net)
2796 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2800 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2801 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2802 atomic_set(&cnet->count, 0);
2804 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2805 if (!net->ct.pcpu_lists)
2808 for_each_possible_cpu(cpu) {
2809 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2811 spin_lock_init(&pcpu->lock);
2812 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2813 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2816 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2818 goto err_pcpu_lists;
2820 ret = nf_conntrack_expect_pernet_init(net);
2824 nf_conntrack_acct_pernet_init(net);
2825 nf_conntrack_tstamp_pernet_init(net);
2826 nf_conntrack_ecache_pernet_init(net);
2827 nf_conntrack_helper_pernet_init(net);
2828 nf_conntrack_proto_pernet_init(net);
2833 free_percpu(net->ct.stat);
2835 free_percpu(net->ct.pcpu_lists);