1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter. This is separated from,
3 but required by, the NAT layer; it can also be used by an iptables
6 /* (C) 1999-2001 Paul `Rusty' Russell
7 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9 * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/jhash.h>
25 #include <linux/siphash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
37 #include <net/netfilter/nf_conntrack.h>
38 #include <net/netfilter/nf_conntrack_l4proto.h>
39 #include <net/netfilter/nf_conntrack_expect.h>
40 #include <net/netfilter/nf_conntrack_helper.h>
41 #include <net/netfilter/nf_conntrack_seqadj.h>
42 #include <net/netfilter/nf_conntrack_core.h>
43 #include <net/netfilter/nf_conntrack_extend.h>
44 #include <net/netfilter/nf_conntrack_acct.h>
45 #include <net/netfilter/nf_conntrack_ecache.h>
46 #include <net/netfilter/nf_conntrack_zones.h>
47 #include <net/netfilter/nf_conntrack_timestamp.h>
48 #include <net/netfilter/nf_conntrack_timeout.h>
49 #include <net/netfilter/nf_conntrack_labels.h>
50 #include <net/netfilter/nf_conntrack_synproxy.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_helper.h>
53 #include <net/netns/hash.h>
56 #include "nf_internals.h"
58 extern unsigned int nf_conntrack_net_id;
60 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
61 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
63 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
64 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
66 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
67 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
69 struct conntrack_gc_work {
70 struct delayed_work dwork;
77 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
78 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
79 static __read_mostly bool nf_conntrack_locks_all;
81 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
82 #define GC_MAX_BUCKETS_DIV 128u
83 /* upper bound of full table scan */
84 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
85 /* desired ratio of entries found to be expired */
86 #define GC_EVICT_RATIO 50u
88 static struct conntrack_gc_work conntrack_gc_work;
90 extern unsigned int nf_conntrack_net_id;
92 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
94 /* 1) Acquire the lock */
97 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
98 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
100 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
103 /* fast path failed, unlock */
106 /* Slow path 1) get global lock */
107 spin_lock(&nf_conntrack_locks_all_lock);
109 /* Slow path 2) get the lock we want */
112 /* Slow path 3) release the global lock */
113 spin_unlock(&nf_conntrack_locks_all_lock);
115 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
117 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
119 h1 %= CONNTRACK_LOCKS;
120 h2 %= CONNTRACK_LOCKS;
121 spin_unlock(&nf_conntrack_locks[h1]);
123 spin_unlock(&nf_conntrack_locks[h2]);
126 /* return true if we need to recompute hashes (in case hash table was resized) */
127 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
128 unsigned int h2, unsigned int sequence)
130 h1 %= CONNTRACK_LOCKS;
131 h2 %= CONNTRACK_LOCKS;
133 nf_conntrack_lock(&nf_conntrack_locks[h1]);
135 spin_lock_nested(&nf_conntrack_locks[h2],
136 SINGLE_DEPTH_NESTING);
138 nf_conntrack_lock(&nf_conntrack_locks[h2]);
139 spin_lock_nested(&nf_conntrack_locks[h1],
140 SINGLE_DEPTH_NESTING);
142 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
143 nf_conntrack_double_unlock(h1, h2);
149 static void nf_conntrack_all_lock(void)
150 __acquires(&nf_conntrack_locks_all_lock)
154 spin_lock(&nf_conntrack_locks_all_lock);
156 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 unsigned int nf_conntrack_hash_rnd __read_mostly;
190 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
191 const struct net *net)
196 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
198 /* The direction must be ignored, so we hash everything up to the
199 * destination ports (which is a multiple of 4) and treat the last
200 * three bytes manually.
202 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
203 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
204 return jhash2((u32 *)tuple, n, seed ^
205 (((__force __u16)tuple->dst.u.all << 16) |
206 tuple->dst.protonum));
209 static u32 scale_hash(u32 hash)
211 return reciprocal_scale(hash, nf_conntrack_htable_size);
214 static u32 __hash_conntrack(const struct net *net,
215 const struct nf_conntrack_tuple *tuple,
218 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
221 static u32 hash_conntrack(const struct net *net,
222 const struct nf_conntrack_tuple *tuple)
224 return scale_hash(hash_conntrack_raw(tuple, net));
227 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
228 unsigned int dataoff,
229 struct nf_conntrack_tuple *tuple)
233 } _inet_hdr, *inet_hdr;
235 /* Actually only need first 4 bytes to get ports. */
236 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
240 tuple->src.u.udp.port = inet_hdr->sport;
241 tuple->dst.u.udp.port = inet_hdr->dport;
246 nf_ct_get_tuple(const struct sk_buff *skb,
248 unsigned int dataoff,
252 struct nf_conntrack_tuple *tuple)
258 memset(tuple, 0, sizeof(*tuple));
260 tuple->src.l3num = l3num;
263 nhoff += offsetof(struct iphdr, saddr);
264 size = 2 * sizeof(__be32);
267 nhoff += offsetof(struct ipv6hdr, saddr);
268 size = sizeof(_addrs);
274 ap = skb_header_pointer(skb, nhoff, size, _addrs);
280 tuple->src.u3.ip = ap[0];
281 tuple->dst.u3.ip = ap[1];
284 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
285 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
289 tuple->dst.protonum = protonum;
290 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
293 #if IS_ENABLED(CONFIG_IPV6)
295 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
298 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
299 #ifdef CONFIG_NF_CT_PROTO_GRE
301 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
304 case IPPROTO_UDP: /* fallthrough */
305 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
306 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
307 case IPPROTO_UDPLITE:
308 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
310 #ifdef CONFIG_NF_CT_PROTO_SCTP
312 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
314 #ifdef CONFIG_NF_CT_PROTO_DCCP
316 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
325 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
329 const struct iphdr *iph;
332 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
336 /* Conntrack defragments packets, we might still see fragments
337 * inside ICMP packets though.
339 if (iph->frag_off & htons(IP_OFFSET))
342 dataoff = nhoff + (iph->ihl << 2);
343 *protonum = iph->protocol;
345 /* Check bogus IP headers */
346 if (dataoff > skb->len) {
347 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
348 nhoff, iph->ihl << 2, skb->len);
354 #if IS_ENABLED(CONFIG_IPV6)
355 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
359 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
363 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
364 &nexthdr, sizeof(nexthdr)) != 0) {
365 pr_debug("can't get nexthdr\n");
368 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
370 * (protoff == skb->len) means the packet has not data, just
371 * IPv6 and possibly extensions headers, but it is tracked anyway
373 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
374 pr_debug("can't find proto in pkt\n");
383 static int get_l4proto(const struct sk_buff *skb,
384 unsigned int nhoff, u8 pf, u8 *l4num)
388 return ipv4_get_l4proto(skb, nhoff, l4num);
389 #if IS_ENABLED(CONFIG_IPV6)
391 return ipv6_get_l4proto(skb, nhoff, l4num);
400 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
402 struct net *net, struct nf_conntrack_tuple *tuple)
407 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
411 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
413 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
416 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
417 const struct nf_conntrack_tuple *orig)
419 memset(inverse, 0, sizeof(*inverse));
421 inverse->src.l3num = orig->src.l3num;
423 switch (orig->src.l3num) {
425 inverse->src.u3.ip = orig->dst.u3.ip;
426 inverse->dst.u3.ip = orig->src.u3.ip;
429 inverse->src.u3.in6 = orig->dst.u3.in6;
430 inverse->dst.u3.in6 = orig->src.u3.in6;
436 inverse->dst.dir = !orig->dst.dir;
438 inverse->dst.protonum = orig->dst.protonum;
440 switch (orig->dst.protonum) {
442 return nf_conntrack_invert_icmp_tuple(inverse, orig);
443 #if IS_ENABLED(CONFIG_IPV6)
445 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
449 inverse->src.u.all = orig->dst.u.all;
450 inverse->dst.u.all = orig->src.u.all;
453 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
455 /* Generate a almost-unique pseudo-id for a given conntrack.
457 * intentionally doesn't re-use any of the seeds used for hash
458 * table location, we assume id gets exposed to userspace.
460 * Following nf_conn items do not change throughout lifetime
464 * 2. nf_conn->master address (normally NULL)
465 * 3. the associated net namespace
466 * 4. the original direction tuple
468 u32 nf_ct_get_id(const struct nf_conn *ct)
470 static __read_mostly siphash_key_t ct_id_seed;
471 unsigned long a, b, c, d;
473 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
475 a = (unsigned long)ct;
476 b = (unsigned long)ct->master;
477 c = (unsigned long)nf_ct_net(ct);
478 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
479 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
482 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
484 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
487 EXPORT_SYMBOL_GPL(nf_ct_get_id);
490 clean_from_lists(struct nf_conn *ct)
492 pr_debug("clean_from_lists(%p)\n", ct);
493 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
494 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
496 /* Destroy all pending expectations */
497 nf_ct_remove_expectations(ct);
500 /* must be called with local_bh_disable */
501 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
503 struct ct_pcpu *pcpu;
505 /* add this conntrack to the (per cpu) dying list */
506 ct->cpu = smp_processor_id();
507 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
509 spin_lock(&pcpu->lock);
510 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
512 spin_unlock(&pcpu->lock);
515 /* must be called with local_bh_disable */
516 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
518 struct ct_pcpu *pcpu;
520 /* add this conntrack to the (per cpu) unconfirmed list */
521 ct->cpu = smp_processor_id();
522 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
524 spin_lock(&pcpu->lock);
525 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
527 spin_unlock(&pcpu->lock);
530 /* must be called with local_bh_disable */
531 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
533 struct ct_pcpu *pcpu;
535 /* We overload first tuple to link into unconfirmed or dying list.*/
536 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
538 spin_lock(&pcpu->lock);
539 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
540 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
541 spin_unlock(&pcpu->lock);
544 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
546 /* Released via destroy_conntrack() */
547 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
548 const struct nf_conntrack_zone *zone,
551 struct nf_conn *tmpl, *p;
553 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
554 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
559 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
561 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
562 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
565 tmpl = kzalloc(sizeof(*tmpl), flags);
570 tmpl->status = IPS_TEMPLATE;
571 write_pnet(&tmpl->ct_net, net);
572 nf_ct_zone_add(tmpl, zone);
573 atomic_set(&tmpl->ct_general.use, 0);
577 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
579 void nf_ct_tmpl_free(struct nf_conn *tmpl)
581 nf_ct_ext_destroy(tmpl);
583 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
584 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
588 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
590 static void destroy_gre_conntrack(struct nf_conn *ct)
592 #ifdef CONFIG_NF_CT_PROTO_GRE
593 struct nf_conn *master = ct->master;
596 nf_ct_gre_keymap_destroy(master);
601 destroy_conntrack(struct nf_conntrack *nfct)
603 struct nf_conn *ct = (struct nf_conn *)nfct;
605 pr_debug("destroy_conntrack(%p)\n", ct);
606 WARN_ON(atomic_read(&nfct->use) != 0);
608 if (unlikely(nf_ct_is_template(ct))) {
613 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
614 destroy_gre_conntrack(ct);
617 /* Expectations will have been removed in clean_from_lists,
618 * except TFTP can create an expectation on the first packet,
619 * before connection is in the list, so we need to clean here,
622 nf_ct_remove_expectations(ct);
624 nf_ct_del_from_dying_or_unconfirmed_list(ct);
629 nf_ct_put(ct->master);
631 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
632 nf_conntrack_free(ct);
635 static void nf_ct_delete_from_lists(struct nf_conn *ct)
637 struct net *net = nf_ct_net(ct);
638 unsigned int hash, reply_hash;
639 unsigned int sequence;
641 nf_ct_helper_destroy(ct);
645 sequence = read_seqcount_begin(&nf_conntrack_generation);
646 hash = hash_conntrack(net,
647 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
648 reply_hash = hash_conntrack(net,
649 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
650 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
652 clean_from_lists(ct);
653 nf_conntrack_double_unlock(hash, reply_hash);
655 nf_ct_add_to_dying_list(ct);
660 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
662 struct nf_conn_tstamp *tstamp;
665 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
668 tstamp = nf_conn_tstamp_find(ct);
669 if (tstamp && tstamp->stop == 0)
670 tstamp->stop = ktime_get_real_ns();
672 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
673 portid, report) < 0) {
674 /* destroy event was not delivered. nf_ct_put will
675 * be done by event cache worker on redelivery.
677 nf_ct_delete_from_lists(ct);
678 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
683 if (nf_conntrack_ecache_dwork_pending(net))
684 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
685 nf_ct_delete_from_lists(ct);
689 EXPORT_SYMBOL_GPL(nf_ct_delete);
692 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
693 const struct nf_conntrack_tuple *tuple,
694 const struct nf_conntrack_zone *zone,
695 const struct net *net)
697 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
699 /* A conntrack can be recreated with the equal tuple,
700 * so we need to check that the conntrack is confirmed
702 return nf_ct_tuple_equal(tuple, &h->tuple) &&
703 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
704 nf_ct_is_confirmed(ct) &&
705 net_eq(net, nf_ct_net(ct));
709 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
711 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
712 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
713 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
714 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
715 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
716 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
717 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
720 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
721 static void nf_ct_gc_expired(struct nf_conn *ct)
723 if (!atomic_inc_not_zero(&ct->ct_general.use))
726 if (nf_ct_should_gc(ct))
734 * - Caller must take a reference on returned object
735 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
737 static struct nf_conntrack_tuple_hash *
738 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
739 const struct nf_conntrack_tuple *tuple, u32 hash)
741 struct nf_conntrack_tuple_hash *h;
742 struct hlist_nulls_head *ct_hash;
743 struct hlist_nulls_node *n;
744 unsigned int bucket, hsize;
747 nf_conntrack_get_ht(&ct_hash, &hsize);
748 bucket = reciprocal_scale(hash, hsize);
750 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
753 ct = nf_ct_tuplehash_to_ctrack(h);
754 if (nf_ct_is_expired(ct)) {
755 nf_ct_gc_expired(ct);
759 if (nf_ct_key_equal(h, tuple, zone, net))
763 * if the nulls value we got at the end of this lookup is
764 * not the expected one, we must restart lookup.
765 * We probably met an item that was moved to another chain.
767 if (get_nulls_value(n) != bucket) {
768 NF_CT_STAT_INC_ATOMIC(net, search_restart);
775 /* Find a connection corresponding to a tuple. */
776 static struct nf_conntrack_tuple_hash *
777 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
778 const struct nf_conntrack_tuple *tuple, u32 hash)
780 struct nf_conntrack_tuple_hash *h;
785 h = ____nf_conntrack_find(net, zone, tuple, hash);
787 /* We have a candidate that matches the tuple we're interested
788 * in, try to obtain a reference and re-check tuple
790 ct = nf_ct_tuplehash_to_ctrack(h);
791 if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
792 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
795 /* TYPESAFE_BY_RCU recycled the candidate */
807 struct nf_conntrack_tuple_hash *
808 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
809 const struct nf_conntrack_tuple *tuple)
811 return __nf_conntrack_find_get(net, zone, tuple,
812 hash_conntrack_raw(tuple, net));
814 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
816 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
818 unsigned int reply_hash)
820 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
821 &nf_conntrack_hash[hash]);
822 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
823 &nf_conntrack_hash[reply_hash]);
827 nf_conntrack_hash_check_insert(struct nf_conn *ct)
829 const struct nf_conntrack_zone *zone;
830 struct net *net = nf_ct_net(ct);
831 unsigned int hash, reply_hash;
832 struct nf_conntrack_tuple_hash *h;
833 struct hlist_nulls_node *n;
834 unsigned int sequence;
836 zone = nf_ct_zone(ct);
840 sequence = read_seqcount_begin(&nf_conntrack_generation);
841 hash = hash_conntrack(net,
842 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
843 reply_hash = hash_conntrack(net,
844 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
845 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
847 /* See if there's one in the list already, including reverse */
848 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
849 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
853 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
854 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
859 /* The caller holds a reference to this object */
860 atomic_set(&ct->ct_general.use, 2);
861 __nf_conntrack_hash_insert(ct, hash, reply_hash);
862 nf_conntrack_double_unlock(hash, reply_hash);
863 NF_CT_STAT_INC(net, insert);
868 nf_conntrack_double_unlock(hash, reply_hash);
872 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
874 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
877 struct nf_conn_acct *acct;
879 acct = nf_conn_acct_find(ct);
881 struct nf_conn_counter *counter = acct->counter;
883 atomic64_add(packets, &counter[dir].packets);
884 atomic64_add(bytes, &counter[dir].bytes);
887 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
889 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
890 const struct nf_conn *loser_ct)
892 struct nf_conn_acct *acct;
894 acct = nf_conn_acct_find(loser_ct);
896 struct nf_conn_counter *counter = acct->counter;
899 /* u32 should be fine since we must have seen one packet. */
900 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
901 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
905 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
907 struct nf_conn_tstamp *tstamp;
909 atomic_inc(&ct->ct_general.use);
910 ct->status |= IPS_CONFIRMED;
912 /* set conntrack timestamp, if enabled. */
913 tstamp = nf_conn_tstamp_find(ct);
915 tstamp->start = ktime_get_real_ns();
918 /* caller must hold locks to prevent concurrent changes */
919 static int __nf_ct_resolve_clash(struct sk_buff *skb,
920 struct nf_conntrack_tuple_hash *h)
922 /* This is the conntrack entry already in hashes that won race. */
923 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
924 enum ip_conntrack_info ctinfo;
925 struct nf_conn *loser_ct;
927 loser_ct = nf_ct_get(skb, &ctinfo);
929 if (nf_ct_is_dying(ct))
932 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
933 nf_ct_match(ct, loser_ct)) {
934 struct net *net = nf_ct_net(ct);
936 nf_conntrack_get(&ct->ct_general);
938 nf_ct_acct_merge(ct, ctinfo, loser_ct);
939 nf_ct_add_to_dying_list(loser_ct);
940 nf_conntrack_put(&loser_ct->ct_general);
941 nf_ct_set(skb, ct, ctinfo);
943 NF_CT_STAT_INC(net, clash_resolve);
951 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
953 * @skb: skb that causes the collision
954 * @repl_idx: hash slot for reply direction
956 * Called when origin or reply direction had a clash.
957 * The skb can be handled without packet drop provided the reply direction
958 * is unique or there the existing entry has the identical tuple in both
961 * Caller must hold conntrack table locks to prevent concurrent updates.
963 * Returns NF_DROP if the clash could not be handled.
965 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
967 struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
968 const struct nf_conntrack_zone *zone;
969 struct nf_conntrack_tuple_hash *h;
970 struct hlist_nulls_node *n;
973 zone = nf_ct_zone(loser_ct);
974 net = nf_ct_net(loser_ct);
976 /* Reply direction must never result in a clash, unless both origin
977 * and reply tuples are identical.
979 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
980 if (nf_ct_key_equal(h,
981 &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
983 return __nf_ct_resolve_clash(skb, h);
986 /* We want the clashing entry to go away real soon: 1 second timeout. */
987 loser_ct->timeout = nfct_time_stamp + HZ;
989 /* IPS_NAT_CLASH removes the entry automatically on the first
990 * reply. Also prevents UDP tracker from moving the entry to
991 * ASSURED state, i.e. the entry can always be evicted under
994 loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
996 __nf_conntrack_insert_prepare(loser_ct);
998 /* fake add for ORIGINAL dir: we want lookups to only find the entry
999 * already in the table. This also hides the clashing entry from
1000 * ctnetlink iteration, i.e. conntrack -L won't show them.
1002 hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1004 hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1005 &nf_conntrack_hash[repl_idx]);
1007 NF_CT_STAT_INC(net, clash_resolve);
1012 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1014 * @skb: skb that causes the clash
1015 * @h: tuplehash of the clashing entry already in table
1016 * @reply_hash: hash slot for reply direction
1018 * A conntrack entry can be inserted to the connection tracking table
1019 * if there is no existing entry with an identical tuple.
1021 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1022 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1023 * will find the already-existing entry.
1025 * The major problem with such packet drop is the extra delay added by
1026 * the packet loss -- it will take some time for a retransmit to occur
1027 * (or the sender to time out when waiting for a reply).
1029 * This function attempts to handle the situation without packet drop.
1031 * If @skb has no NAT transformation or if the colliding entries are
1032 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1033 * and @skb is associated with the conntrack entry already in the table.
1035 * Failing that, the new, unconfirmed conntrack is still added to the table
1036 * provided that the collision only occurs in the ORIGINAL direction.
1037 * The new entry will be added only in the non-clashing REPLY direction,
1038 * so packets in the ORIGINAL direction will continue to match the existing
1039 * entry. The new entry will also have a fixed timeout so it expires --
1040 * due to the collision, it will only see reply traffic.
1042 * Returns NF_DROP if the clash could not be resolved.
1044 static __cold noinline int
1045 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1048 /* This is the conntrack entry already in hashes that won race. */
1049 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1050 const struct nf_conntrack_l4proto *l4proto;
1051 enum ip_conntrack_info ctinfo;
1052 struct nf_conn *loser_ct;
1056 loser_ct = nf_ct_get(skb, &ctinfo);
1057 net = nf_ct_net(loser_ct);
1059 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1060 if (!l4proto->allow_clash)
1063 ret = __nf_ct_resolve_clash(skb, h);
1064 if (ret == NF_ACCEPT)
1067 ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1068 if (ret == NF_ACCEPT)
1072 nf_ct_add_to_dying_list(loser_ct);
1073 NF_CT_STAT_INC(net, drop);
1074 NF_CT_STAT_INC(net, insert_failed);
1078 /* Confirm a connection given skb; places it in hash table */
1080 __nf_conntrack_confirm(struct sk_buff *skb)
1082 const struct nf_conntrack_zone *zone;
1083 unsigned int hash, reply_hash;
1084 struct nf_conntrack_tuple_hash *h;
1086 struct nf_conn_help *help;
1087 struct hlist_nulls_node *n;
1088 enum ip_conntrack_info ctinfo;
1090 unsigned int sequence;
1093 ct = nf_ct_get(skb, &ctinfo);
1094 net = nf_ct_net(ct);
1096 /* ipt_REJECT uses nf_conntrack_attach to attach related
1097 ICMP/TCP RST packets in other direction. Actual packet
1098 which created connection will be IP_CT_NEW or for an
1099 expected connection, IP_CT_RELATED. */
1100 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1103 zone = nf_ct_zone(ct);
1107 sequence = read_seqcount_begin(&nf_conntrack_generation);
1108 /* reuse the hash saved before */
1109 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1110 hash = scale_hash(hash);
1111 reply_hash = hash_conntrack(net,
1112 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
1114 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1116 /* We're not in hash table, and we refuse to set up related
1117 * connections for unconfirmed conns. But packet copies and
1118 * REJECT will give spurious warnings here.
1121 /* Another skb with the same unconfirmed conntrack may
1122 * win the race. This may happen for bridge(br_flood)
1123 * or broadcast/multicast packets do skb_clone with
1124 * unconfirmed conntrack.
1126 if (unlikely(nf_ct_is_confirmed(ct))) {
1128 nf_conntrack_double_unlock(hash, reply_hash);
1133 pr_debug("Confirming conntrack %p\n", ct);
1134 /* We have to check the DYING flag after unlink to prevent
1135 * a race against nf_ct_get_next_corpse() possibly called from
1136 * user context, else we insert an already 'dead' hash, blocking
1137 * further use of that particular connection -JM.
1139 nf_ct_del_from_dying_or_unconfirmed_list(ct);
1141 if (unlikely(nf_ct_is_dying(ct))) {
1142 nf_ct_add_to_dying_list(ct);
1143 NF_CT_STAT_INC(net, insert_failed);
1147 /* See if there's one in the list already, including reverse:
1148 NAT could have grabbed it without realizing, since we're
1149 not in the hash. If there is, we lost race. */
1150 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
1151 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1155 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
1156 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1160 /* Timer relative to confirmation time, not original
1161 setting time, otherwise we'd get timer wrap in
1162 weird delay cases. */
1163 ct->timeout += nfct_time_stamp;
1165 __nf_conntrack_insert_prepare(ct);
1167 /* Since the lookup is lockless, hash insertion must be done after
1168 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1169 * guarantee that no other CPU can find the conntrack before the above
1170 * stores are visible.
1172 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1173 nf_conntrack_double_unlock(hash, reply_hash);
1176 help = nfct_help(ct);
1177 if (help && help->helper)
1178 nf_conntrack_event_cache(IPCT_HELPER, ct);
1180 nf_conntrack_event_cache(master_ct(ct) ?
1181 IPCT_RELATED : IPCT_NEW, ct);
1185 ret = nf_ct_resolve_clash(skb, h, reply_hash);
1187 nf_conntrack_double_unlock(hash, reply_hash);
1191 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1193 /* Returns true if a connection correspondings to the tuple (required
1196 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1197 const struct nf_conn *ignored_conntrack)
1199 struct net *net = nf_ct_net(ignored_conntrack);
1200 const struct nf_conntrack_zone *zone;
1201 struct nf_conntrack_tuple_hash *h;
1202 struct hlist_nulls_head *ct_hash;
1203 unsigned int hash, hsize;
1204 struct hlist_nulls_node *n;
1207 zone = nf_ct_zone(ignored_conntrack);
1211 nf_conntrack_get_ht(&ct_hash, &hsize);
1212 hash = __hash_conntrack(net, tuple, hsize);
1214 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1215 ct = nf_ct_tuplehash_to_ctrack(h);
1217 if (ct == ignored_conntrack)
1220 if (nf_ct_is_expired(ct)) {
1221 nf_ct_gc_expired(ct);
1225 if (nf_ct_key_equal(h, tuple, zone, net)) {
1226 /* Tuple is taken already, so caller will need to find
1227 * a new source port to use.
1230 * If the *original tuples* are identical, then both
1231 * conntracks refer to the same flow.
1232 * This is a rare situation, it can occur e.g. when
1233 * more than one UDP packet is sent from same socket
1234 * in different threads.
1236 * Let nf_ct_resolve_clash() deal with this later.
1238 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1239 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1240 nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1243 NF_CT_STAT_INC_ATOMIC(net, found);
1249 if (get_nulls_value(n) != hash) {
1250 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1258 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1260 #define NF_CT_EVICTION_RANGE 8
1262 /* There's a small race here where we may free a just-assured
1263 connection. Too bad: we're in trouble anyway. */
1264 static unsigned int early_drop_list(struct net *net,
1265 struct hlist_nulls_head *head)
1267 struct nf_conntrack_tuple_hash *h;
1268 struct hlist_nulls_node *n;
1269 unsigned int drops = 0;
1270 struct nf_conn *tmp;
1272 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1273 tmp = nf_ct_tuplehash_to_ctrack(h);
1275 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1278 if (nf_ct_is_expired(tmp)) {
1279 nf_ct_gc_expired(tmp);
1283 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1284 !net_eq(nf_ct_net(tmp), net) ||
1285 nf_ct_is_dying(tmp))
1288 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1291 /* kill only if still in same netns -- might have moved due to
1292 * SLAB_TYPESAFE_BY_RCU rules.
1294 * We steal the timer reference. If that fails timer has
1295 * already fired or someone else deleted it. Just drop ref
1296 * and move to next entry.
1298 if (net_eq(nf_ct_net(tmp), net) &&
1299 nf_ct_is_confirmed(tmp) &&
1300 nf_ct_delete(tmp, 0, 0))
1309 static noinline int early_drop(struct net *net, unsigned int hash)
1311 unsigned int i, bucket;
1313 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1314 struct hlist_nulls_head *ct_hash;
1315 unsigned int hsize, drops;
1318 nf_conntrack_get_ht(&ct_hash, &hsize);
1320 bucket = reciprocal_scale(hash, hsize);
1322 bucket = (bucket + 1) % hsize;
1324 drops = early_drop_list(net, &ct_hash[bucket]);
1328 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1336 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1338 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1341 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1343 const struct nf_conntrack_l4proto *l4proto;
1345 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1348 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1349 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1355 static void gc_worker(struct work_struct *work)
1357 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
1358 unsigned int i, goal, buckets = 0, expired_count = 0;
1359 unsigned int nf_conntrack_max95 = 0;
1360 struct conntrack_gc_work *gc_work;
1361 unsigned int ratio, scanned = 0;
1362 unsigned long next_run;
1364 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1366 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
1367 i = gc_work->last_bucket;
1368 if (gc_work->early_drop)
1369 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1372 struct nf_conntrack_tuple_hash *h;
1373 struct hlist_nulls_head *ct_hash;
1374 struct hlist_nulls_node *n;
1375 unsigned int hashsz;
1376 struct nf_conn *tmp;
1381 nf_conntrack_get_ht(&ct_hash, &hashsz);
1385 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1386 struct nf_conntrack_net *cnet;
1389 tmp = nf_ct_tuplehash_to_ctrack(h);
1392 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1393 nf_ct_offload_timeout(tmp);
1397 if (nf_ct_is_expired(tmp)) {
1398 nf_ct_gc_expired(tmp);
1403 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1406 net = nf_ct_net(tmp);
1407 cnet = net_generic(net, nf_conntrack_net_id);
1408 if (atomic_read(&cnet->count) < nf_conntrack_max95)
1411 /* need to take reference to avoid possible races */
1412 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1415 if (gc_worker_skip_ct(tmp)) {
1420 if (gc_worker_can_early_drop(tmp))
1426 /* could check get_nulls_value() here and restart if ct
1427 * was moved to another chain. But given gc is best-effort
1428 * we will just continue with next hash slot.
1432 } while (++buckets < goal);
1434 if (gc_work->exiting)
1438 * Eviction will normally happen from the packet path, and not
1439 * from this gc worker.
1441 * This worker is only here to reap expired entries when system went
1442 * idle after a busy period.
1444 * The heuristics below are supposed to balance conflicting goals:
1446 * 1. Minimize time until we notice a stale entry
1447 * 2. Maximize scan intervals to not waste cycles
1449 * Normally, expire ratio will be close to 0.
1451 * As soon as a sizeable fraction of the entries have expired
1452 * increase scan frequency.
1454 ratio = scanned ? expired_count * 100 / scanned : 0;
1455 if (ratio > GC_EVICT_RATIO) {
1456 gc_work->next_gc_run = min_interval;
1458 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1460 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1462 gc_work->next_gc_run += min_interval;
1463 if (gc_work->next_gc_run > max)
1464 gc_work->next_gc_run = max;
1467 next_run = gc_work->next_gc_run;
1468 gc_work->last_bucket = i;
1469 gc_work->early_drop = false;
1470 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1473 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1475 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1476 gc_work->next_gc_run = HZ;
1477 gc_work->exiting = false;
1480 static struct nf_conn *
1481 __nf_conntrack_alloc(struct net *net,
1482 const struct nf_conntrack_zone *zone,
1483 const struct nf_conntrack_tuple *orig,
1484 const struct nf_conntrack_tuple *repl,
1485 gfp_t gfp, u32 hash)
1487 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
1488 unsigned int ct_count;
1491 /* We don't want any race condition at early drop stage */
1492 ct_count = atomic_inc_return(&cnet->count);
1494 if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1495 if (!early_drop(net, hash)) {
1496 if (!conntrack_gc_work.early_drop)
1497 conntrack_gc_work.early_drop = true;
1498 atomic_dec(&cnet->count);
1499 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1500 return ERR_PTR(-ENOMEM);
1505 * Do not use kmem_cache_zalloc(), as this cache uses
1506 * SLAB_TYPESAFE_BY_RCU.
1508 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1512 spin_lock_init(&ct->lock);
1513 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1514 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1515 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1516 /* save hash for reusing when confirming */
1517 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1520 write_pnet(&ct->ct_net, net);
1521 memset(&ct->__nfct_init_offset, 0,
1522 offsetof(struct nf_conn, proto) -
1523 offsetof(struct nf_conn, __nfct_init_offset));
1525 nf_ct_zone_add(ct, zone);
1527 /* Because we use RCU lookups, we set ct_general.use to zero before
1528 * this is inserted in any list.
1530 atomic_set(&ct->ct_general.use, 0);
1533 atomic_dec(&cnet->count);
1534 return ERR_PTR(-ENOMEM);
1537 struct nf_conn *nf_conntrack_alloc(struct net *net,
1538 const struct nf_conntrack_zone *zone,
1539 const struct nf_conntrack_tuple *orig,
1540 const struct nf_conntrack_tuple *repl,
1543 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1545 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1547 void nf_conntrack_free(struct nf_conn *ct)
1549 struct net *net = nf_ct_net(ct);
1550 struct nf_conntrack_net *cnet;
1552 /* A freed object has refcnt == 0, that's
1553 * the golden rule for SLAB_TYPESAFE_BY_RCU
1555 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1557 nf_ct_ext_destroy(ct);
1558 kmem_cache_free(nf_conntrack_cachep, ct);
1559 cnet = net_generic(net, nf_conntrack_net_id);
1561 smp_mb__before_atomic();
1562 atomic_dec(&cnet->count);
1564 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1567 /* Allocate a new conntrack: we return -ENOMEM if classification
1568 failed due to stress. Otherwise it really is unclassifiable. */
1569 static noinline struct nf_conntrack_tuple_hash *
1570 init_conntrack(struct net *net, struct nf_conn *tmpl,
1571 const struct nf_conntrack_tuple *tuple,
1572 struct sk_buff *skb,
1573 unsigned int dataoff, u32 hash)
1576 struct nf_conn_help *help;
1577 struct nf_conntrack_tuple repl_tuple;
1578 struct nf_conntrack_ecache *ecache;
1579 struct nf_conntrack_expect *exp = NULL;
1580 const struct nf_conntrack_zone *zone;
1581 struct nf_conn_timeout *timeout_ext;
1582 struct nf_conntrack_zone tmp;
1583 struct nf_conntrack_net *cnet;
1585 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1586 pr_debug("Can't invert tuple.\n");
1590 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1591 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1594 return (struct nf_conntrack_tuple_hash *)ct;
1596 if (!nf_ct_add_synproxy(ct, tmpl)) {
1597 nf_conntrack_free(ct);
1598 return ERR_PTR(-ENOMEM);
1601 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1604 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1607 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1608 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1609 nf_ct_labels_ext_add(ct);
1611 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1612 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1613 ecache ? ecache->expmask : 0,
1617 cnet = net_generic(net, nf_conntrack_net_id);
1618 if (cnet->expect_count) {
1619 spin_lock(&nf_conntrack_expect_lock);
1620 exp = nf_ct_find_expectation(net, zone, tuple);
1622 pr_debug("expectation arrives ct=%p exp=%p\n",
1624 /* Welcome, Mr. Bond. We've been expecting you... */
1625 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1626 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1627 ct->master = exp->master;
1629 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1631 rcu_assign_pointer(help->helper, exp->helper);
1634 #ifdef CONFIG_NF_CONNTRACK_MARK
1635 ct->mark = exp->master->mark;
1637 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1638 ct->secmark = exp->master->secmark;
1640 NF_CT_STAT_INC(net, expect_new);
1642 spin_unlock(&nf_conntrack_expect_lock);
1645 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1647 /* Now it is inserted into the unconfirmed list, bump refcount */
1648 nf_conntrack_get(&ct->ct_general);
1649 nf_ct_add_to_unconfirmed_list(ct);
1655 exp->expectfn(ct, exp);
1656 nf_ct_expect_put(exp);
1659 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1662 /* On success, returns 0, sets skb->_nfct | ctinfo */
1664 resolve_normal_ct(struct nf_conn *tmpl,
1665 struct sk_buff *skb,
1666 unsigned int dataoff,
1668 const struct nf_hook_state *state)
1670 const struct nf_conntrack_zone *zone;
1671 struct nf_conntrack_tuple tuple;
1672 struct nf_conntrack_tuple_hash *h;
1673 enum ip_conntrack_info ctinfo;
1674 struct nf_conntrack_zone tmp;
1678 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1679 dataoff, state->pf, protonum, state->net,
1681 pr_debug("Can't get tuple\n");
1685 /* look for tuple match */
1686 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1687 hash = hash_conntrack_raw(&tuple, state->net);
1688 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1690 h = init_conntrack(state->net, tmpl, &tuple,
1691 skb, dataoff, hash);
1697 ct = nf_ct_tuplehash_to_ctrack(h);
1699 /* It exists; we have (non-exclusive) reference. */
1700 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1701 ctinfo = IP_CT_ESTABLISHED_REPLY;
1703 /* Once we've had two way comms, always ESTABLISHED. */
1704 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1705 pr_debug("normal packet for %p\n", ct);
1706 ctinfo = IP_CT_ESTABLISHED;
1707 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1708 pr_debug("related packet for %p\n", ct);
1709 ctinfo = IP_CT_RELATED;
1711 pr_debug("new packet for %p\n", ct);
1715 nf_ct_set(skb, ct, ctinfo);
1720 * icmp packets need special treatment to handle error messages that are
1721 * related to a connection.
1723 * Callers need to check if skb has a conntrack assigned when this
1724 * helper returns; in such case skb belongs to an already known connection.
1726 static unsigned int __cold
1727 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1728 struct sk_buff *skb,
1729 unsigned int dataoff,
1731 const struct nf_hook_state *state)
1735 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1736 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1737 #if IS_ENABLED(CONFIG_IPV6)
1738 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1739 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1745 NF_CT_STAT_INC_ATOMIC(state->net, error);
1750 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1751 enum ip_conntrack_info ctinfo)
1753 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1756 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1758 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1762 /* Returns verdict for packet, or -1 for invalid. */
1763 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1764 struct sk_buff *skb,
1765 unsigned int dataoff,
1766 enum ip_conntrack_info ctinfo,
1767 const struct nf_hook_state *state)
1769 switch (nf_ct_protonum(ct)) {
1771 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1774 return nf_conntrack_udp_packet(ct, skb, dataoff,
1777 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1778 #if IS_ENABLED(CONFIG_IPV6)
1779 case IPPROTO_ICMPV6:
1780 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1782 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1783 case IPPROTO_UDPLITE:
1784 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1787 #ifdef CONFIG_NF_CT_PROTO_SCTP
1789 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1792 #ifdef CONFIG_NF_CT_PROTO_DCCP
1794 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1797 #ifdef CONFIG_NF_CT_PROTO_GRE
1799 return nf_conntrack_gre_packet(ct, skb, dataoff,
1804 return generic_packet(ct, skb, ctinfo);
1808 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1810 enum ip_conntrack_info ctinfo;
1811 struct nf_conn *ct, *tmpl;
1815 tmpl = nf_ct_get(skb, &ctinfo);
1816 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1817 /* Previously seen (loopback or untracked)? Ignore. */
1818 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1819 ctinfo == IP_CT_UNTRACKED)
1824 /* rcu_read_lock()ed by nf_hook_thresh */
1825 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1827 pr_debug("not prepared to track yet or error occurred\n");
1828 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1833 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1834 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1840 /* ICMP[v6] protocol trackers may assign one conntrack. */
1845 ret = resolve_normal_ct(tmpl, skb, dataoff,
1848 /* Too stressed to deal. */
1849 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1854 ct = nf_ct_get(skb, &ctinfo);
1856 /* Not valid part of a connection */
1857 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1862 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1864 /* Invalid: inverse of the return code tells
1865 * the netfilter core what to do */
1866 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1867 nf_conntrack_put(&ct->ct_general);
1869 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1870 if (ret == -NF_DROP)
1871 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1872 /* Special case: TCP tracker reports an attempt to reopen a
1873 * closed/aborted connection. We have to go back and create a
1876 if (ret == -NF_REPEAT)
1882 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1883 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1884 nf_conntrack_event_cache(IPCT_REPLY, ct);
1891 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1893 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1894 implicitly racy: see __nf_conntrack_confirm */
1895 void nf_conntrack_alter_reply(struct nf_conn *ct,
1896 const struct nf_conntrack_tuple *newreply)
1898 struct nf_conn_help *help = nfct_help(ct);
1900 /* Should be unconfirmed, so not in hash table yet */
1901 WARN_ON(nf_ct_is_confirmed(ct));
1903 pr_debug("Altering reply tuple of %p to ", ct);
1904 nf_ct_dump_tuple(newreply);
1906 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1907 if (ct->master || (help && !hlist_empty(&help->expectations)))
1911 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1914 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1916 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1917 void __nf_ct_refresh_acct(struct nf_conn *ct,
1918 enum ip_conntrack_info ctinfo,
1919 const struct sk_buff *skb,
1923 /* Only update if this is not a fixed timeout */
1924 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1927 /* If not in hash table, timer will not be active yet */
1928 if (nf_ct_is_confirmed(ct))
1929 extra_jiffies += nfct_time_stamp;
1931 if (READ_ONCE(ct->timeout) != extra_jiffies)
1932 WRITE_ONCE(ct->timeout, extra_jiffies);
1935 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1937 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1939 bool nf_ct_kill_acct(struct nf_conn *ct,
1940 enum ip_conntrack_info ctinfo,
1941 const struct sk_buff *skb)
1943 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1945 return nf_ct_delete(ct, 0, 0);
1947 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1949 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1951 #include <linux/netfilter/nfnetlink.h>
1952 #include <linux/netfilter/nfnetlink_conntrack.h>
1953 #include <linux/mutex.h>
1955 /* Generic function for tcp/udp/sctp/dccp and alike. */
1956 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1957 const struct nf_conntrack_tuple *tuple)
1959 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1960 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1961 goto nla_put_failure;
1967 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1969 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1970 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1971 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1973 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1975 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1976 struct nf_conntrack_tuple *t,
1979 if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
1980 if (!tb[CTA_PROTO_SRC_PORT])
1983 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1986 if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
1987 if (!tb[CTA_PROTO_DST_PORT])
1990 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1995 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1997 unsigned int nf_ct_port_nlattr_tuple_size(void)
1999 static unsigned int size __read_mostly;
2002 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2006 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2009 /* Used by ipt_REJECT and ip6t_REJECT. */
2010 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2013 enum ip_conntrack_info ctinfo;
2015 /* This ICMP is in reverse direction to the packet which caused it */
2016 ct = nf_ct_get(skb, &ctinfo);
2017 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2018 ctinfo = IP_CT_RELATED_REPLY;
2020 ctinfo = IP_CT_RELATED;
2022 /* Attach to new skbuff, and increment count */
2023 nf_ct_set(nskb, ct, ctinfo);
2024 nf_conntrack_get(skb_nfct(nskb));
2027 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2029 enum ip_conntrack_info ctinfo)
2031 struct nf_conntrack_tuple_hash *h;
2032 struct nf_conntrack_tuple tuple;
2033 struct nf_nat_hook *nat_hook;
2034 unsigned int status;
2039 l3num = nf_ct_l3num(ct);
2041 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2045 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2046 l4num, net, &tuple))
2049 if (ct->status & IPS_SRC_NAT) {
2050 memcpy(tuple.src.u3.all,
2051 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2052 sizeof(tuple.src.u3.all));
2054 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2057 if (ct->status & IPS_DST_NAT) {
2058 memcpy(tuple.dst.u3.all,
2059 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2060 sizeof(tuple.dst.u3.all));
2062 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2065 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2069 /* Store status bits of the conntrack that is clashing to re-do NAT
2070 * mangling according to what it has been done already to this packet.
2072 status = ct->status;
2075 ct = nf_ct_tuplehash_to_ctrack(h);
2076 nf_ct_set(skb, ct, ctinfo);
2078 nat_hook = rcu_dereference(nf_nat_hook);
2082 if (status & IPS_SRC_NAT &&
2083 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2084 IP_CT_DIR_ORIGINAL) == NF_DROP)
2087 if (status & IPS_DST_NAT &&
2088 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2089 IP_CT_DIR_ORIGINAL) == NF_DROP)
2095 /* This packet is coming from userspace via nf_queue, complete the packet
2096 * processing after the helper invocation in nf_confirm().
2098 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2099 enum ip_conntrack_info ctinfo)
2101 const struct nf_conntrack_helper *helper;
2102 const struct nf_conn_help *help;
2105 help = nfct_help(ct);
2109 helper = rcu_dereference(help->helper);
2110 if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2113 switch (nf_ct_l3num(ct)) {
2115 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2117 #if IS_ENABLED(CONFIG_IPV6)
2118 case NFPROTO_IPV6: {
2122 pnum = ipv6_hdr(skb)->nexthdr;
2123 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2125 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2134 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2135 !nf_is_loopback_packet(skb)) {
2136 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2137 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2142 /* We've seen it coming out the other side: confirm it */
2143 return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2146 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2148 enum ip_conntrack_info ctinfo;
2152 ct = nf_ct_get(skb, &ctinfo);
2156 if (!nf_ct_is_confirmed(ct)) {
2157 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2161 ct = nf_ct_get(skb, &ctinfo);
2164 return nf_confirm_cthelper(skb, ct, ctinfo);
2167 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2168 const struct sk_buff *skb)
2170 const struct nf_conntrack_tuple *src_tuple;
2171 const struct nf_conntrack_tuple_hash *hash;
2172 struct nf_conntrack_tuple srctuple;
2173 enum ip_conntrack_info ctinfo;
2176 ct = nf_ct_get(skb, &ctinfo);
2178 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2179 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2183 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2184 NFPROTO_IPV4, dev_net(skb->dev),
2188 hash = nf_conntrack_find_get(dev_net(skb->dev),
2194 ct = nf_ct_tuplehash_to_ctrack(hash);
2195 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2196 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2202 /* Bring out ya dead! */
2203 static struct nf_conn *
2204 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2205 void *data, unsigned int *bucket)
2207 struct nf_conntrack_tuple_hash *h;
2209 struct hlist_nulls_node *n;
2212 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2213 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2215 nf_conntrack_lock(lockp);
2216 if (*bucket < nf_conntrack_htable_size) {
2217 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
2218 if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2220 /* All nf_conn objects are added to hash table twice, one
2221 * for original direction tuple, once for the reply tuple.
2223 * Exception: In the IPS_NAT_CLASH case, only the reply
2224 * tuple is added (the original tuple already existed for
2225 * a different object).
2227 * We only need to call the iterator once for each
2228 * conntrack, so we just use the 'reply' direction
2229 * tuple while iterating.
2231 ct = nf_ct_tuplehash_to_ctrack(h);
2243 atomic_inc(&ct->ct_general.use);
2249 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2250 void *data, u32 portid, int report)
2252 unsigned int bucket = 0, sequence;
2258 sequence = read_seqcount_begin(&nf_conntrack_generation);
2260 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2261 /* Time to push up daises... */
2263 nf_ct_delete(ct, portid, report);
2268 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2275 int (*iter)(struct nf_conn *i, void *data);
2280 static int iter_net_only(struct nf_conn *i, void *data)
2282 struct iter_data *d = data;
2284 if (!net_eq(d->net, nf_ct_net(i)))
2287 return d->iter(i, d->data);
2291 __nf_ct_unconfirmed_destroy(struct net *net)
2295 for_each_possible_cpu(cpu) {
2296 struct nf_conntrack_tuple_hash *h;
2297 struct hlist_nulls_node *n;
2298 struct ct_pcpu *pcpu;
2300 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2302 spin_lock_bh(&pcpu->lock);
2303 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2306 ct = nf_ct_tuplehash_to_ctrack(h);
2308 /* we cannot call iter() on unconfirmed list, the
2309 * owning cpu can reallocate ct->ext at any time.
2311 set_bit(IPS_DYING_BIT, &ct->status);
2313 spin_unlock_bh(&pcpu->lock);
2318 void nf_ct_unconfirmed_destroy(struct net *net)
2320 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
2324 if (atomic_read(&cnet->count) > 0) {
2325 __nf_ct_unconfirmed_destroy(net);
2326 nf_queue_nf_hook_drop(net);
2330 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2332 void nf_ct_iterate_cleanup_net(struct net *net,
2333 int (*iter)(struct nf_conn *i, void *data),
2334 void *data, u32 portid, int report)
2336 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
2341 if (atomic_read(&cnet->count) == 0)
2348 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2350 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2353 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2354 * @iter: callback to invoke for each conntrack
2355 * @data: data to pass to @iter
2357 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2358 * unconfirmed list as dying (so they will not be inserted into
2361 * Can only be called in module exit path.
2364 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2368 down_read(&net_rwsem);
2370 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
2372 if (atomic_read(&cnet->count) == 0)
2374 __nf_ct_unconfirmed_destroy(net);
2375 nf_queue_nf_hook_drop(net);
2377 up_read(&net_rwsem);
2379 /* Need to wait for netns cleanup worker to finish, if its
2380 * running -- it might have deleted a net namespace from
2381 * the global list, so our __nf_ct_unconfirmed_destroy() might
2382 * not have affected all namespaces.
2386 /* a conntrack could have been unlinked from unconfirmed list
2387 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2388 * This makes sure its inserted into conntrack table.
2392 nf_ct_iterate_cleanup(iter, data, 0, 0);
2394 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2396 static int kill_all(struct nf_conn *i, void *data)
2398 return net_eq(nf_ct_net(i), data);
2401 void nf_conntrack_cleanup_start(void)
2403 conntrack_gc_work.exiting = true;
2404 RCU_INIT_POINTER(ip_ct_attach, NULL);
2407 void nf_conntrack_cleanup_end(void)
2409 RCU_INIT_POINTER(nf_ct_hook, NULL);
2410 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2411 kvfree(nf_conntrack_hash);
2413 nf_conntrack_proto_fini();
2414 nf_conntrack_seqadj_fini();
2415 nf_conntrack_labels_fini();
2416 nf_conntrack_helper_fini();
2417 nf_conntrack_timeout_fini();
2418 nf_conntrack_ecache_fini();
2419 nf_conntrack_tstamp_fini();
2420 nf_conntrack_acct_fini();
2421 nf_conntrack_expect_fini();
2423 kmem_cache_destroy(nf_conntrack_cachep);
2427 * Mishearing the voices in his head, our hero wonders how he's
2428 * supposed to kill the mall.
2430 void nf_conntrack_cleanup_net(struct net *net)
2434 list_add(&net->exit_list, &single);
2435 nf_conntrack_cleanup_net_list(&single);
2438 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2444 * This makes sure all current packets have passed through
2445 * netfilter framework. Roll on, two-stage module
2451 list_for_each_entry(net, net_exit_list, exit_list) {
2452 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
2454 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2455 if (atomic_read(&cnet->count) != 0)
2460 goto i_see_dead_people;
2463 list_for_each_entry(net, net_exit_list, exit_list) {
2464 nf_conntrack_proto_pernet_fini(net);
2465 nf_conntrack_ecache_pernet_fini(net);
2466 nf_conntrack_expect_pernet_fini(net);
2467 free_percpu(net->ct.stat);
2468 free_percpu(net->ct.pcpu_lists);
2472 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2474 struct hlist_nulls_head *hash;
2475 unsigned int nr_slots, i;
2477 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2480 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2481 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2483 hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2486 for (i = 0; i < nr_slots; i++)
2487 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2491 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2493 int nf_conntrack_hash_resize(unsigned int hashsize)
2496 unsigned int old_size;
2497 struct hlist_nulls_head *hash, *old_hash;
2498 struct nf_conntrack_tuple_hash *h;
2504 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2508 old_size = nf_conntrack_htable_size;
2509 if (old_size == hashsize) {
2515 nf_conntrack_all_lock();
2516 write_seqcount_begin(&nf_conntrack_generation);
2518 /* Lookups in the old hash might happen in parallel, which means we
2519 * might get false negatives during connection lookup. New connections
2520 * created because of a false negative won't make it into the hash
2521 * though since that required taking the locks.
2524 for (i = 0; i < nf_conntrack_htable_size; i++) {
2525 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2526 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2527 struct nf_conntrack_tuple_hash, hnnode);
2528 ct = nf_ct_tuplehash_to_ctrack(h);
2529 hlist_nulls_del_rcu(&h->hnnode);
2530 bucket = __hash_conntrack(nf_ct_net(ct),
2531 &h->tuple, hashsize);
2532 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2535 old_size = nf_conntrack_htable_size;
2536 old_hash = nf_conntrack_hash;
2538 nf_conntrack_hash = hash;
2539 nf_conntrack_htable_size = hashsize;
2541 write_seqcount_end(&nf_conntrack_generation);
2542 nf_conntrack_all_unlock();
2550 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2552 unsigned int hashsize;
2555 if (current->nsproxy->net_ns != &init_net)
2558 /* On boot, we can set this without any fancy locking. */
2559 if (!nf_conntrack_hash)
2560 return param_set_uint(val, kp);
2562 rc = kstrtouint(val, 0, &hashsize);
2566 return nf_conntrack_hash_resize(hashsize);
2569 static __always_inline unsigned int total_extension_size(void)
2571 /* remember to add new extensions below */
2572 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2574 return sizeof(struct nf_ct_ext) +
2575 sizeof(struct nf_conn_help)
2576 #if IS_ENABLED(CONFIG_NF_NAT)
2577 + sizeof(struct nf_conn_nat)
2579 + sizeof(struct nf_conn_seqadj)
2580 + sizeof(struct nf_conn_acct)
2581 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2582 + sizeof(struct nf_conntrack_ecache)
2584 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2585 + sizeof(struct nf_conn_tstamp)
2587 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2588 + sizeof(struct nf_conn_timeout)
2590 #ifdef CONFIG_NF_CONNTRACK_LABELS
2591 + sizeof(struct nf_conn_labels)
2593 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2594 + sizeof(struct nf_conn_synproxy)
2599 int nf_conntrack_init_start(void)
2601 unsigned long nr_pages = totalram_pages();
2606 /* struct nf_ct_ext uses u8 to store offsets/size */
2607 BUILD_BUG_ON(total_extension_size() > 255u);
2609 seqcount_spinlock_init(&nf_conntrack_generation,
2610 &nf_conntrack_locks_all_lock);
2612 for (i = 0; i < CONNTRACK_LOCKS; i++)
2613 spin_lock_init(&nf_conntrack_locks[i]);
2615 if (!nf_conntrack_htable_size) {
2616 /* Idea from tcp.c: use 1/16384 of memory.
2617 * On i386: 32MB machine has 512 buckets.
2618 * >= 1GB machines have 16384 buckets.
2619 * >= 4GB machines have 65536 buckets.
2621 nf_conntrack_htable_size
2622 = (((nr_pages << PAGE_SHIFT) / 16384)
2623 / sizeof(struct hlist_head));
2624 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2625 nf_conntrack_htable_size = 65536;
2626 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2627 nf_conntrack_htable_size = 16384;
2628 if (nf_conntrack_htable_size < 32)
2629 nf_conntrack_htable_size = 32;
2631 /* Use a max. factor of four by default to get the same max as
2632 * with the old struct list_heads. When a table size is given
2633 * we use the old value of 8 to avoid reducing the max.
2638 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2639 if (!nf_conntrack_hash)
2642 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2644 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2645 sizeof(struct nf_conn),
2647 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2648 if (!nf_conntrack_cachep)
2651 ret = nf_conntrack_expect_init();
2655 ret = nf_conntrack_acct_init();
2659 ret = nf_conntrack_tstamp_init();
2663 ret = nf_conntrack_ecache_init();
2667 ret = nf_conntrack_timeout_init();
2671 ret = nf_conntrack_helper_init();
2675 ret = nf_conntrack_labels_init();
2679 ret = nf_conntrack_seqadj_init();
2683 ret = nf_conntrack_proto_init();
2687 conntrack_gc_work_init(&conntrack_gc_work);
2688 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2693 nf_conntrack_seqadj_fini();
2695 nf_conntrack_labels_fini();
2697 nf_conntrack_helper_fini();
2699 nf_conntrack_timeout_fini();
2701 nf_conntrack_ecache_fini();
2703 nf_conntrack_tstamp_fini();
2705 nf_conntrack_acct_fini();
2707 nf_conntrack_expect_fini();
2709 kmem_cache_destroy(nf_conntrack_cachep);
2711 kvfree(nf_conntrack_hash);
2715 static struct nf_ct_hook nf_conntrack_hook = {
2716 .update = nf_conntrack_update,
2717 .destroy = destroy_conntrack,
2718 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2721 void nf_conntrack_init_end(void)
2723 /* For use by REJECT target */
2724 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2725 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2729 * We need to use special "null" values, not used in hash table
2731 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2732 #define DYING_NULLS_VAL ((1<<30)+1)
2734 int nf_conntrack_init_net(struct net *net)
2736 struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id);
2740 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2741 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2742 atomic_set(&cnet->count, 0);
2744 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2745 if (!net->ct.pcpu_lists)
2748 for_each_possible_cpu(cpu) {
2749 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2751 spin_lock_init(&pcpu->lock);
2752 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2753 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2756 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2758 goto err_pcpu_lists;
2760 ret = nf_conntrack_expect_pernet_init(net);
2764 nf_conntrack_acct_pernet_init(net);
2765 nf_conntrack_tstamp_pernet_init(net);
2766 nf_conntrack_ecache_pernet_init(net);
2767 nf_conntrack_helper_pernet_init(net);
2768 nf_conntrack_proto_pernet_init(net);
2773 free_percpu(net->ct.stat);
2775 free_percpu(net->ct.pcpu_lists);