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_bpf.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_core.h>
42 #include <net/netfilter/nf_conntrack_extend.h>
43 #include <net/netfilter/nf_conntrack_acct.h>
44 #include <net/netfilter/nf_conntrack_ecache.h>
45 #include <net/netfilter/nf_conntrack_zones.h>
46 #include <net/netfilter/nf_conntrack_timestamp.h>
47 #include <net/netfilter/nf_conntrack_timeout.h>
48 #include <net/netfilter/nf_conntrack_labels.h>
49 #include <net/netfilter/nf_conntrack_synproxy.h>
50 #include <net/netfilter/nf_nat.h>
51 #include <net/netfilter/nf_nat_helper.h>
52 #include <net/netns/hash.h>
55 #include "nf_internals.h"
57 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
58 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
60 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
61 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
63 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
64 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
66 struct conntrack_gc_work {
67 struct delayed_work dwork;
76 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
77 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
78 static __read_mostly bool nf_conntrack_locks_all;
80 /* serialize hash resizes and nf_ct_iterate_cleanup */
81 static DEFINE_MUTEX(nf_conntrack_mutex);
83 #define GC_SCAN_INTERVAL_MAX (60ul * HZ)
84 #define GC_SCAN_INTERVAL_MIN (1ul * HZ)
86 /* clamp timeouts to this value (TCP unacked) */
87 #define GC_SCAN_INTERVAL_CLAMP (300ul * HZ)
89 /* Initial bias pretending we have 100 entries at the upper bound so we don't
90 * wakeup often just because we have three entries with a 1s timeout while still
91 * allowing non-idle machines to wakeup more often when needed.
93 #define GC_SCAN_INITIAL_COUNT 100
94 #define GC_SCAN_INTERVAL_INIT GC_SCAN_INTERVAL_MAX
96 #define GC_SCAN_MAX_DURATION msecs_to_jiffies(10)
97 #define GC_SCAN_EXPIRED_MAX (64000u / HZ)
99 #define MIN_CHAINLEN 8u
100 #define MAX_CHAINLEN (32u - MIN_CHAINLEN)
102 static struct conntrack_gc_work conntrack_gc_work;
104 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
106 /* 1) Acquire the lock */
109 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
110 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
112 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
115 /* fast path failed, unlock */
118 /* Slow path 1) get global lock */
119 spin_lock(&nf_conntrack_locks_all_lock);
121 /* Slow path 2) get the lock we want */
124 /* Slow path 3) release the global lock */
125 spin_unlock(&nf_conntrack_locks_all_lock);
127 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
129 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
131 h1 %= CONNTRACK_LOCKS;
132 h2 %= CONNTRACK_LOCKS;
133 spin_unlock(&nf_conntrack_locks[h1]);
135 spin_unlock(&nf_conntrack_locks[h2]);
138 /* return true if we need to recompute hashes (in case hash table was resized) */
139 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
140 unsigned int h2, unsigned int sequence)
142 h1 %= CONNTRACK_LOCKS;
143 h2 %= CONNTRACK_LOCKS;
145 nf_conntrack_lock(&nf_conntrack_locks[h1]);
147 spin_lock_nested(&nf_conntrack_locks[h2],
148 SINGLE_DEPTH_NESTING);
150 nf_conntrack_lock(&nf_conntrack_locks[h2]);
151 spin_lock_nested(&nf_conntrack_locks[h1],
152 SINGLE_DEPTH_NESTING);
154 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
155 nf_conntrack_double_unlock(h1, h2);
161 static void nf_conntrack_all_lock(void)
162 __acquires(&nf_conntrack_locks_all_lock)
166 spin_lock(&nf_conntrack_locks_all_lock);
168 /* For nf_contrack_locks_all, only the latest time when another
169 * CPU will see an update is controlled, by the "release" of the
171 * The earliest time is not controlled, an thus KCSAN could detect
172 * a race when nf_conntract_lock() reads the variable.
173 * WRITE_ONCE() is used to ensure the compiler will not
174 * optimize the write.
176 WRITE_ONCE(nf_conntrack_locks_all, true);
178 for (i = 0; i < CONNTRACK_LOCKS; i++) {
179 spin_lock(&nf_conntrack_locks[i]);
181 /* This spin_unlock provides the "release" to ensure that
182 * nf_conntrack_locks_all==true is visible to everyone that
183 * acquired spin_lock(&nf_conntrack_locks[]).
185 spin_unlock(&nf_conntrack_locks[i]);
189 static void nf_conntrack_all_unlock(void)
190 __releases(&nf_conntrack_locks_all_lock)
192 /* All prior stores must be complete before we clear
193 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
194 * might observe the false value but not the entire
196 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
198 smp_store_release(&nf_conntrack_locks_all, false);
199 spin_unlock(&nf_conntrack_locks_all_lock);
202 unsigned int nf_conntrack_htable_size __read_mostly;
203 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
205 unsigned int nf_conntrack_max __read_mostly;
206 EXPORT_SYMBOL_GPL(nf_conntrack_max);
207 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
208 static siphash_aligned_key_t nf_conntrack_hash_rnd;
210 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
212 const struct net *net)
216 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
218 /* The direction must be ignored, handle usable tuplehash members manually */
219 a = (u64)tuple->src.u3.all[0] << 32 | tuple->src.u3.all[3];
220 b = (u64)tuple->dst.u3.all[0] << 32 | tuple->dst.u3.all[3];
222 c = (__force u64)tuple->src.u.all << 32 | (__force u64)tuple->dst.u.all << 16;
223 c |= tuple->dst.protonum;
225 d = (u64)zoneid << 32 | net_hash_mix(net);
227 /* IPv4: u3.all[1,2,3] == 0 */
228 c ^= (u64)tuple->src.u3.all[1] << 32 | tuple->src.u3.all[2];
229 d += (u64)tuple->dst.u3.all[1] << 32 | tuple->dst.u3.all[2];
231 return (u32)siphash_4u64(a, b, c, d, &nf_conntrack_hash_rnd);
234 static u32 scale_hash(u32 hash)
236 return reciprocal_scale(hash, nf_conntrack_htable_size);
239 static u32 __hash_conntrack(const struct net *net,
240 const struct nf_conntrack_tuple *tuple,
244 return reciprocal_scale(hash_conntrack_raw(tuple, zoneid, net), size);
247 static u32 hash_conntrack(const struct net *net,
248 const struct nf_conntrack_tuple *tuple,
251 return scale_hash(hash_conntrack_raw(tuple, zoneid, net));
254 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
255 unsigned int dataoff,
256 struct nf_conntrack_tuple *tuple)
260 } _inet_hdr, *inet_hdr;
262 /* Actually only need first 4 bytes to get ports. */
263 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
267 tuple->src.u.udp.port = inet_hdr->sport;
268 tuple->dst.u.udp.port = inet_hdr->dport;
273 nf_ct_get_tuple(const struct sk_buff *skb,
275 unsigned int dataoff,
279 struct nf_conntrack_tuple *tuple)
285 memset(tuple, 0, sizeof(*tuple));
287 tuple->src.l3num = l3num;
290 nhoff += offsetof(struct iphdr, saddr);
291 size = 2 * sizeof(__be32);
294 nhoff += offsetof(struct ipv6hdr, saddr);
295 size = sizeof(_addrs);
301 ap = skb_header_pointer(skb, nhoff, size, _addrs);
307 tuple->src.u3.ip = ap[0];
308 tuple->dst.u3.ip = ap[1];
311 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
312 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
316 tuple->dst.protonum = protonum;
317 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
320 #if IS_ENABLED(CONFIG_IPV6)
322 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
325 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
326 #ifdef CONFIG_NF_CT_PROTO_GRE
328 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
332 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
333 case IPPROTO_UDPLITE:
335 #ifdef CONFIG_NF_CT_PROTO_SCTP
338 #ifdef CONFIG_NF_CT_PROTO_DCCP
342 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
350 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
354 const struct iphdr *iph;
357 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
361 /* Conntrack defragments packets, we might still see fragments
362 * inside ICMP packets though.
364 if (iph->frag_off & htons(IP_OFFSET))
367 dataoff = nhoff + (iph->ihl << 2);
368 *protonum = iph->protocol;
370 /* Check bogus IP headers */
371 if (dataoff > skb->len) {
372 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
373 nhoff, iph->ihl << 2, skb->len);
379 #if IS_ENABLED(CONFIG_IPV6)
380 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
384 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
388 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
389 &nexthdr, sizeof(nexthdr)) != 0) {
390 pr_debug("can't get nexthdr\n");
393 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
395 * (protoff == skb->len) means the packet has not data, just
396 * IPv6 and possibly extensions headers, but it is tracked anyway
398 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
399 pr_debug("can't find proto in pkt\n");
408 static int get_l4proto(const struct sk_buff *skb,
409 unsigned int nhoff, u8 pf, u8 *l4num)
413 return ipv4_get_l4proto(skb, nhoff, l4num);
414 #if IS_ENABLED(CONFIG_IPV6)
416 return ipv6_get_l4proto(skb, nhoff, l4num);
425 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
427 struct net *net, struct nf_conntrack_tuple *tuple)
432 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
436 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
438 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
441 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
442 const struct nf_conntrack_tuple *orig)
444 memset(inverse, 0, sizeof(*inverse));
446 inverse->src.l3num = orig->src.l3num;
448 switch (orig->src.l3num) {
450 inverse->src.u3.ip = orig->dst.u3.ip;
451 inverse->dst.u3.ip = orig->src.u3.ip;
454 inverse->src.u3.in6 = orig->dst.u3.in6;
455 inverse->dst.u3.in6 = orig->src.u3.in6;
461 inverse->dst.dir = !orig->dst.dir;
463 inverse->dst.protonum = orig->dst.protonum;
465 switch (orig->dst.protonum) {
467 return nf_conntrack_invert_icmp_tuple(inverse, orig);
468 #if IS_ENABLED(CONFIG_IPV6)
470 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
474 inverse->src.u.all = orig->dst.u.all;
475 inverse->dst.u.all = orig->src.u.all;
478 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
480 /* Generate a almost-unique pseudo-id for a given conntrack.
482 * intentionally doesn't re-use any of the seeds used for hash
483 * table location, we assume id gets exposed to userspace.
485 * Following nf_conn items do not change throughout lifetime
489 * 2. nf_conn->master address (normally NULL)
490 * 3. the associated net namespace
491 * 4. the original direction tuple
493 u32 nf_ct_get_id(const struct nf_conn *ct)
495 static siphash_aligned_key_t ct_id_seed;
496 unsigned long a, b, c, d;
498 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
500 a = (unsigned long)ct;
501 b = (unsigned long)ct->master;
502 c = (unsigned long)nf_ct_net(ct);
503 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
504 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
507 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
509 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
512 EXPORT_SYMBOL_GPL(nf_ct_get_id);
515 clean_from_lists(struct nf_conn *ct)
517 pr_debug("clean_from_lists(%p)\n", ct);
518 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
519 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
521 /* Destroy all pending expectations */
522 nf_ct_remove_expectations(ct);
525 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
527 /* Released via nf_ct_destroy() */
528 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
529 const struct nf_conntrack_zone *zone,
532 struct nf_conn *tmpl, *p;
534 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
535 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
540 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
542 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
543 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
546 tmpl = kzalloc(sizeof(*tmpl), flags);
551 tmpl->status = IPS_TEMPLATE;
552 write_pnet(&tmpl->ct_net, net);
553 nf_ct_zone_add(tmpl, zone);
554 refcount_set(&tmpl->ct_general.use, 1);
558 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
560 void nf_ct_tmpl_free(struct nf_conn *tmpl)
564 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
565 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
569 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
571 static void destroy_gre_conntrack(struct nf_conn *ct)
573 #ifdef CONFIG_NF_CT_PROTO_GRE
574 struct nf_conn *master = ct->master;
577 nf_ct_gre_keymap_destroy(master);
581 void nf_ct_destroy(struct nf_conntrack *nfct)
583 struct nf_conn *ct = (struct nf_conn *)nfct;
585 pr_debug("%s(%p)\n", __func__, ct);
586 WARN_ON(refcount_read(&nfct->use) != 0);
588 if (unlikely(nf_ct_is_template(ct))) {
593 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
594 destroy_gre_conntrack(ct);
596 /* Expectations will have been removed in clean_from_lists,
597 * except TFTP can create an expectation on the first packet,
598 * before connection is in the list, so we need to clean here,
601 nf_ct_remove_expectations(ct);
604 nf_ct_put(ct->master);
606 pr_debug("%s: returning ct=%p to slab\n", __func__, ct);
607 nf_conntrack_free(ct);
609 EXPORT_SYMBOL(nf_ct_destroy);
611 static void __nf_ct_delete_from_lists(struct nf_conn *ct)
613 struct net *net = nf_ct_net(ct);
614 unsigned int hash, reply_hash;
615 unsigned int sequence;
618 sequence = read_seqcount_begin(&nf_conntrack_generation);
619 hash = hash_conntrack(net,
620 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
621 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
622 reply_hash = hash_conntrack(net,
623 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
624 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
625 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
627 clean_from_lists(ct);
628 nf_conntrack_double_unlock(hash, reply_hash);
631 static void nf_ct_delete_from_lists(struct nf_conn *ct)
633 nf_ct_helper_destroy(ct);
636 __nf_ct_delete_from_lists(ct);
641 static void nf_ct_add_to_ecache_list(struct nf_conn *ct)
643 #ifdef CONFIG_NF_CONNTRACK_EVENTS
644 struct nf_conntrack_net *cnet = nf_ct_pernet(nf_ct_net(ct));
646 spin_lock(&cnet->ecache.dying_lock);
647 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
648 &cnet->ecache.dying_list);
649 spin_unlock(&cnet->ecache.dying_lock);
653 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
655 struct nf_conn_tstamp *tstamp;
658 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
661 tstamp = nf_conn_tstamp_find(ct);
663 s32 timeout = READ_ONCE(ct->timeout) - nfct_time_stamp;
665 tstamp->stop = ktime_get_real_ns();
667 tstamp->stop -= jiffies_to_nsecs(-timeout);
670 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
671 portid, report) < 0) {
672 /* destroy event was not delivered. nf_ct_put will
673 * be done by event cache worker on redelivery.
675 nf_ct_helper_destroy(ct);
677 __nf_ct_delete_from_lists(ct);
678 nf_ct_add_to_ecache_list(ct);
681 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
686 if (nf_conntrack_ecache_dwork_pending(net))
687 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
688 nf_ct_delete_from_lists(ct);
692 EXPORT_SYMBOL_GPL(nf_ct_delete);
695 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
696 const struct nf_conntrack_tuple *tuple,
697 const struct nf_conntrack_zone *zone,
698 const struct net *net)
700 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
702 /* A conntrack can be recreated with the equal tuple,
703 * so we need to check that the conntrack is confirmed
705 return nf_ct_tuple_equal(tuple, &h->tuple) &&
706 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
707 nf_ct_is_confirmed(ct) &&
708 net_eq(net, nf_ct_net(ct));
712 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
714 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
715 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
716 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
717 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
718 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
719 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
720 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
723 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
724 static void nf_ct_gc_expired(struct nf_conn *ct)
726 if (!refcount_inc_not_zero(&ct->ct_general.use))
729 /* load ->status after refcount increase */
730 smp_acquire__after_ctrl_dep();
732 if (nf_ct_should_gc(ct))
740 * - Caller must take a reference on returned object
741 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
743 static struct nf_conntrack_tuple_hash *
744 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
745 const struct nf_conntrack_tuple *tuple, u32 hash)
747 struct nf_conntrack_tuple_hash *h;
748 struct hlist_nulls_head *ct_hash;
749 struct hlist_nulls_node *n;
750 unsigned int bucket, hsize;
753 nf_conntrack_get_ht(&ct_hash, &hsize);
754 bucket = reciprocal_scale(hash, hsize);
756 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
759 ct = nf_ct_tuplehash_to_ctrack(h);
760 if (nf_ct_is_expired(ct)) {
761 nf_ct_gc_expired(ct);
765 if (nf_ct_key_equal(h, tuple, zone, net))
769 * if the nulls value we got at the end of this lookup is
770 * not the expected one, we must restart lookup.
771 * We probably met an item that was moved to another chain.
773 if (get_nulls_value(n) != bucket) {
774 NF_CT_STAT_INC_ATOMIC(net, search_restart);
781 /* Find a connection corresponding to a tuple. */
782 static struct nf_conntrack_tuple_hash *
783 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
784 const struct nf_conntrack_tuple *tuple, u32 hash)
786 struct nf_conntrack_tuple_hash *h;
791 h = ____nf_conntrack_find(net, zone, tuple, hash);
793 /* We have a candidate that matches the tuple we're interested
794 * in, try to obtain a reference and re-check tuple
796 ct = nf_ct_tuplehash_to_ctrack(h);
797 if (likely(refcount_inc_not_zero(&ct->ct_general.use))) {
798 /* re-check key after refcount */
799 smp_acquire__after_ctrl_dep();
801 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
804 /* TYPESAFE_BY_RCU recycled the candidate */
816 struct nf_conntrack_tuple_hash *
817 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
818 const struct nf_conntrack_tuple *tuple)
820 unsigned int rid, zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
821 struct nf_conntrack_tuple_hash *thash;
823 thash = __nf_conntrack_find_get(net, zone, tuple,
824 hash_conntrack_raw(tuple, zone_id, net));
829 rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
831 return __nf_conntrack_find_get(net, zone, tuple,
832 hash_conntrack_raw(tuple, rid, net));
835 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
837 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
839 unsigned int reply_hash)
841 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
842 &nf_conntrack_hash[hash]);
843 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
844 &nf_conntrack_hash[reply_hash]);
847 static bool nf_ct_ext_valid_pre(const struct nf_ct_ext *ext)
849 /* if ext->gen_id is not equal to nf_conntrack_ext_genid, some extensions
850 * may contain stale pointers to e.g. helper that has been removed.
852 * The helper can't clear this because the nf_conn object isn't in
853 * any hash and synchronize_rcu() isn't enough because associated skb
854 * might sit in a queue.
856 return !ext || ext->gen_id == atomic_read(&nf_conntrack_ext_genid);
859 static bool nf_ct_ext_valid_post(struct nf_ct_ext *ext)
864 if (ext->gen_id != atomic_read(&nf_conntrack_ext_genid))
867 /* inserted into conntrack table, nf_ct_iterate_cleanup()
868 * will find it. Disable nf_ct_ext_find() id check.
870 WRITE_ONCE(ext->gen_id, 0);
875 nf_conntrack_hash_check_insert(struct nf_conn *ct)
877 const struct nf_conntrack_zone *zone;
878 struct net *net = nf_ct_net(ct);
879 unsigned int hash, reply_hash;
880 struct nf_conntrack_tuple_hash *h;
881 struct hlist_nulls_node *n;
882 unsigned int max_chainlen;
883 unsigned int chainlen = 0;
884 unsigned int sequence;
887 zone = nf_ct_zone(ct);
889 if (!nf_ct_ext_valid_pre(ct->ext)) {
890 NF_CT_STAT_INC(net, insert_failed);
896 sequence = read_seqcount_begin(&nf_conntrack_generation);
897 hash = hash_conntrack(net,
898 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
899 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
900 reply_hash = hash_conntrack(net,
901 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
902 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
903 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
905 max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
907 /* See if there's one in the list already, including reverse */
908 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
909 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
913 if (chainlen++ > max_chainlen)
919 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
920 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
923 if (chainlen++ > max_chainlen)
928 /* The caller holds a reference to this object */
929 refcount_set(&ct->ct_general.use, 2);
930 __nf_conntrack_hash_insert(ct, hash, reply_hash);
931 nf_conntrack_double_unlock(hash, reply_hash);
932 NF_CT_STAT_INC(net, insert);
935 if (!nf_ct_ext_valid_post(ct->ext)) {
937 NF_CT_STAT_INC(net, drop);
943 NF_CT_STAT_INC(net, chaintoolong);
946 nf_conntrack_double_unlock(hash, reply_hash);
950 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
952 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
955 struct nf_conn_acct *acct;
957 acct = nf_conn_acct_find(ct);
959 struct nf_conn_counter *counter = acct->counter;
961 atomic64_add(packets, &counter[dir].packets);
962 atomic64_add(bytes, &counter[dir].bytes);
965 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
967 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
968 const struct nf_conn *loser_ct)
970 struct nf_conn_acct *acct;
972 acct = nf_conn_acct_find(loser_ct);
974 struct nf_conn_counter *counter = acct->counter;
977 /* u32 should be fine since we must have seen one packet. */
978 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
979 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
983 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
985 struct nf_conn_tstamp *tstamp;
987 refcount_inc(&ct->ct_general.use);
989 /* set conntrack timestamp, if enabled. */
990 tstamp = nf_conn_tstamp_find(ct);
992 tstamp->start = ktime_get_real_ns();
995 /* caller must hold locks to prevent concurrent changes */
996 static int __nf_ct_resolve_clash(struct sk_buff *skb,
997 struct nf_conntrack_tuple_hash *h)
999 /* This is the conntrack entry already in hashes that won race. */
1000 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1001 enum ip_conntrack_info ctinfo;
1002 struct nf_conn *loser_ct;
1004 loser_ct = nf_ct_get(skb, &ctinfo);
1006 if (nf_ct_is_dying(ct))
1009 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
1010 nf_ct_match(ct, loser_ct)) {
1011 struct net *net = nf_ct_net(ct);
1013 nf_conntrack_get(&ct->ct_general);
1015 nf_ct_acct_merge(ct, ctinfo, loser_ct);
1016 nf_ct_put(loser_ct);
1017 nf_ct_set(skb, ct, ctinfo);
1019 NF_CT_STAT_INC(net, clash_resolve);
1027 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
1029 * @skb: skb that causes the collision
1030 * @repl_idx: hash slot for reply direction
1032 * Called when origin or reply direction had a clash.
1033 * The skb can be handled without packet drop provided the reply direction
1034 * is unique or there the existing entry has the identical tuple in both
1037 * Caller must hold conntrack table locks to prevent concurrent updates.
1039 * Returns NF_DROP if the clash could not be handled.
1041 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
1043 struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
1044 const struct nf_conntrack_zone *zone;
1045 struct nf_conntrack_tuple_hash *h;
1046 struct hlist_nulls_node *n;
1049 zone = nf_ct_zone(loser_ct);
1050 net = nf_ct_net(loser_ct);
1052 /* Reply direction must never result in a clash, unless both origin
1053 * and reply tuples are identical.
1055 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
1056 if (nf_ct_key_equal(h,
1057 &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1059 return __nf_ct_resolve_clash(skb, h);
1062 /* We want the clashing entry to go away real soon: 1 second timeout. */
1063 WRITE_ONCE(loser_ct->timeout, nfct_time_stamp + HZ);
1065 /* IPS_NAT_CLASH removes the entry automatically on the first
1066 * reply. Also prevents UDP tracker from moving the entry to
1067 * ASSURED state, i.e. the entry can always be evicted under
1070 loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
1072 __nf_conntrack_insert_prepare(loser_ct);
1074 /* fake add for ORIGINAL dir: we want lookups to only find the entry
1075 * already in the table. This also hides the clashing entry from
1076 * ctnetlink iteration, i.e. conntrack -L won't show them.
1078 hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1080 hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1081 &nf_conntrack_hash[repl_idx]);
1083 NF_CT_STAT_INC(net, clash_resolve);
1088 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1090 * @skb: skb that causes the clash
1091 * @h: tuplehash of the clashing entry already in table
1092 * @reply_hash: hash slot for reply direction
1094 * A conntrack entry can be inserted to the connection tracking table
1095 * if there is no existing entry with an identical tuple.
1097 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1098 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1099 * will find the already-existing entry.
1101 * The major problem with such packet drop is the extra delay added by
1102 * the packet loss -- it will take some time for a retransmit to occur
1103 * (or the sender to time out when waiting for a reply).
1105 * This function attempts to handle the situation without packet drop.
1107 * If @skb has no NAT transformation or if the colliding entries are
1108 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1109 * and @skb is associated with the conntrack entry already in the table.
1111 * Failing that, the new, unconfirmed conntrack is still added to the table
1112 * provided that the collision only occurs in the ORIGINAL direction.
1113 * The new entry will be added only in the non-clashing REPLY direction,
1114 * so packets in the ORIGINAL direction will continue to match the existing
1115 * entry. The new entry will also have a fixed timeout so it expires --
1116 * due to the collision, it will only see reply traffic.
1118 * Returns NF_DROP if the clash could not be resolved.
1120 static __cold noinline int
1121 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1124 /* This is the conntrack entry already in hashes that won race. */
1125 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1126 const struct nf_conntrack_l4proto *l4proto;
1127 enum ip_conntrack_info ctinfo;
1128 struct nf_conn *loser_ct;
1132 loser_ct = nf_ct_get(skb, &ctinfo);
1133 net = nf_ct_net(loser_ct);
1135 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1136 if (!l4proto->allow_clash)
1139 ret = __nf_ct_resolve_clash(skb, h);
1140 if (ret == NF_ACCEPT)
1143 ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1144 if (ret == NF_ACCEPT)
1148 NF_CT_STAT_INC(net, drop);
1149 NF_CT_STAT_INC(net, insert_failed);
1153 /* Confirm a connection given skb; places it in hash table */
1155 __nf_conntrack_confirm(struct sk_buff *skb)
1157 unsigned int chainlen = 0, sequence, max_chainlen;
1158 const struct nf_conntrack_zone *zone;
1159 unsigned int hash, reply_hash;
1160 struct nf_conntrack_tuple_hash *h;
1162 struct nf_conn_help *help;
1163 struct hlist_nulls_node *n;
1164 enum ip_conntrack_info ctinfo;
1168 ct = nf_ct_get(skb, &ctinfo);
1169 net = nf_ct_net(ct);
1171 /* ipt_REJECT uses nf_conntrack_attach to attach related
1172 ICMP/TCP RST packets in other direction. Actual packet
1173 which created connection will be IP_CT_NEW or for an
1174 expected connection, IP_CT_RELATED. */
1175 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1178 zone = nf_ct_zone(ct);
1182 sequence = read_seqcount_begin(&nf_conntrack_generation);
1183 /* reuse the hash saved before */
1184 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1185 hash = scale_hash(hash);
1186 reply_hash = hash_conntrack(net,
1187 &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1188 nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
1189 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1191 /* We're not in hash table, and we refuse to set up related
1192 * connections for unconfirmed conns. But packet copies and
1193 * REJECT will give spurious warnings here.
1196 /* Another skb with the same unconfirmed conntrack may
1197 * win the race. This may happen for bridge(br_flood)
1198 * or broadcast/multicast packets do skb_clone with
1199 * unconfirmed conntrack.
1201 if (unlikely(nf_ct_is_confirmed(ct))) {
1203 nf_conntrack_double_unlock(hash, reply_hash);
1208 if (!nf_ct_ext_valid_pre(ct->ext)) {
1209 NF_CT_STAT_INC(net, insert_failed);
1213 pr_debug("Confirming conntrack %p\n", ct);
1214 /* We have to check the DYING flag after unlink to prevent
1215 * a race against nf_ct_get_next_corpse() possibly called from
1216 * user context, else we insert an already 'dead' hash, blocking
1217 * further use of that particular connection -JM.
1219 ct->status |= IPS_CONFIRMED;
1221 if (unlikely(nf_ct_is_dying(ct))) {
1222 NF_CT_STAT_INC(net, insert_failed);
1226 max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
1227 /* See if there's one in the list already, including reverse:
1228 NAT could have grabbed it without realizing, since we're
1229 not in the hash. If there is, we lost race. */
1230 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
1231 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1234 if (chainlen++ > max_chainlen)
1239 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
1240 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1243 if (chainlen++ > max_chainlen) {
1245 NF_CT_STAT_INC(net, chaintoolong);
1246 NF_CT_STAT_INC(net, insert_failed);
1252 /* Timer relative to confirmation time, not original
1253 setting time, otherwise we'd get timer wrap in
1254 weird delay cases. */
1255 ct->timeout += nfct_time_stamp;
1257 __nf_conntrack_insert_prepare(ct);
1259 /* Since the lookup is lockless, hash insertion must be done after
1260 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1261 * guarantee that no other CPU can find the conntrack before the above
1262 * stores are visible.
1264 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1265 nf_conntrack_double_unlock(hash, reply_hash);
1268 /* ext area is still valid (rcu read lock is held,
1269 * but will go out of scope soon, we need to remove
1270 * this conntrack again.
1272 if (!nf_ct_ext_valid_post(ct->ext)) {
1274 NF_CT_STAT_INC(net, drop);
1278 help = nfct_help(ct);
1279 if (help && help->helper)
1280 nf_conntrack_event_cache(IPCT_HELPER, ct);
1282 nf_conntrack_event_cache(master_ct(ct) ?
1283 IPCT_RELATED : IPCT_NEW, ct);
1287 ret = nf_ct_resolve_clash(skb, h, reply_hash);
1289 nf_conntrack_double_unlock(hash, reply_hash);
1293 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1295 /* Returns true if a connection correspondings to the tuple (required
1298 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1299 const struct nf_conn *ignored_conntrack)
1301 struct net *net = nf_ct_net(ignored_conntrack);
1302 const struct nf_conntrack_zone *zone;
1303 struct nf_conntrack_tuple_hash *h;
1304 struct hlist_nulls_head *ct_hash;
1305 unsigned int hash, hsize;
1306 struct hlist_nulls_node *n;
1309 zone = nf_ct_zone(ignored_conntrack);
1313 nf_conntrack_get_ht(&ct_hash, &hsize);
1314 hash = __hash_conntrack(net, tuple, nf_ct_zone_id(zone, IP_CT_DIR_REPLY), hsize);
1316 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1317 ct = nf_ct_tuplehash_to_ctrack(h);
1319 if (ct == ignored_conntrack)
1322 if (nf_ct_is_expired(ct)) {
1323 nf_ct_gc_expired(ct);
1327 if (nf_ct_key_equal(h, tuple, zone, net)) {
1328 /* Tuple is taken already, so caller will need to find
1329 * a new source port to use.
1332 * If the *original tuples* are identical, then both
1333 * conntracks refer to the same flow.
1334 * This is a rare situation, it can occur e.g. when
1335 * more than one UDP packet is sent from same socket
1336 * in different threads.
1338 * Let nf_ct_resolve_clash() deal with this later.
1340 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1341 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1342 nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1345 NF_CT_STAT_INC_ATOMIC(net, found);
1351 if (get_nulls_value(n) != hash) {
1352 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1360 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1362 #define NF_CT_EVICTION_RANGE 8
1364 /* There's a small race here where we may free a just-assured
1365 connection. Too bad: we're in trouble anyway. */
1366 static unsigned int early_drop_list(struct net *net,
1367 struct hlist_nulls_head *head)
1369 struct nf_conntrack_tuple_hash *h;
1370 struct hlist_nulls_node *n;
1371 unsigned int drops = 0;
1372 struct nf_conn *tmp;
1374 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1375 tmp = nf_ct_tuplehash_to_ctrack(h);
1377 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1380 if (nf_ct_is_expired(tmp)) {
1381 nf_ct_gc_expired(tmp);
1385 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1386 !net_eq(nf_ct_net(tmp), net) ||
1387 nf_ct_is_dying(tmp))
1390 if (!refcount_inc_not_zero(&tmp->ct_general.use))
1393 /* load ->ct_net and ->status after refcount increase */
1394 smp_acquire__after_ctrl_dep();
1396 /* kill only if still in same netns -- might have moved due to
1397 * SLAB_TYPESAFE_BY_RCU rules.
1399 * We steal the timer reference. If that fails timer has
1400 * already fired or someone else deleted it. Just drop ref
1401 * and move to next entry.
1403 if (net_eq(nf_ct_net(tmp), net) &&
1404 nf_ct_is_confirmed(tmp) &&
1405 nf_ct_delete(tmp, 0, 0))
1414 static noinline int early_drop(struct net *net, unsigned int hash)
1416 unsigned int i, bucket;
1418 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1419 struct hlist_nulls_head *ct_hash;
1420 unsigned int hsize, drops;
1423 nf_conntrack_get_ht(&ct_hash, &hsize);
1425 bucket = reciprocal_scale(hash, hsize);
1427 bucket = (bucket + 1) % hsize;
1429 drops = early_drop_list(net, &ct_hash[bucket]);
1433 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1441 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1443 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1446 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1448 const struct nf_conntrack_l4proto *l4proto;
1450 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1453 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1454 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1460 static void gc_worker(struct work_struct *work)
1462 unsigned int i, hashsz, nf_conntrack_max95 = 0;
1463 u32 end_time, start_time = nfct_time_stamp;
1464 struct conntrack_gc_work *gc_work;
1465 unsigned int expired_count = 0;
1466 unsigned long next_run;
1470 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1472 i = gc_work->next_bucket;
1473 if (gc_work->early_drop)
1474 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1477 gc_work->avg_timeout = GC_SCAN_INTERVAL_INIT;
1478 gc_work->count = GC_SCAN_INITIAL_COUNT;
1479 gc_work->start_time = start_time;
1482 next_run = gc_work->avg_timeout;
1483 count = gc_work->count;
1485 end_time = start_time + GC_SCAN_MAX_DURATION;
1488 struct nf_conntrack_tuple_hash *h;
1489 struct hlist_nulls_head *ct_hash;
1490 struct hlist_nulls_node *n;
1491 struct nf_conn *tmp;
1495 nf_conntrack_get_ht(&ct_hash, &hashsz);
1501 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1502 struct nf_conntrack_net *cnet;
1506 tmp = nf_ct_tuplehash_to_ctrack(h);
1508 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1509 nf_ct_offload_timeout(tmp);
1513 if (expired_count > GC_SCAN_EXPIRED_MAX) {
1516 gc_work->next_bucket = i;
1517 gc_work->avg_timeout = next_run;
1518 gc_work->count = count;
1520 delta_time = nfct_time_stamp - gc_work->start_time;
1522 /* re-sched immediately if total cycle time is exceeded */
1523 next_run = delta_time < (s32)GC_SCAN_INTERVAL_MAX;
1527 if (nf_ct_is_expired(tmp)) {
1528 nf_ct_gc_expired(tmp);
1533 expires = clamp(nf_ct_expires(tmp), GC_SCAN_INTERVAL_MIN, GC_SCAN_INTERVAL_CLAMP);
1534 expires = (expires - (long)next_run) / ++count;
1535 next_run += expires;
1537 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1540 net = nf_ct_net(tmp);
1541 cnet = nf_ct_pernet(net);
1542 if (atomic_read(&cnet->count) < nf_conntrack_max95)
1545 /* need to take reference to avoid possible races */
1546 if (!refcount_inc_not_zero(&tmp->ct_general.use))
1549 /* load ->status after refcount increase */
1550 smp_acquire__after_ctrl_dep();
1552 if (gc_worker_skip_ct(tmp)) {
1557 if (gc_worker_can_early_drop(tmp)) {
1565 /* could check get_nulls_value() here and restart if ct
1566 * was moved to another chain. But given gc is best-effort
1567 * we will just continue with next hash slot.
1573 delta_time = nfct_time_stamp - end_time;
1574 if (delta_time > 0 && i < hashsz) {
1575 gc_work->avg_timeout = next_run;
1576 gc_work->count = count;
1577 gc_work->next_bucket = i;
1581 } while (i < hashsz);
1583 gc_work->next_bucket = 0;
1585 next_run = clamp(next_run, GC_SCAN_INTERVAL_MIN, GC_SCAN_INTERVAL_MAX);
1587 delta_time = max_t(s32, nfct_time_stamp - gc_work->start_time, 1);
1588 if (next_run > (unsigned long)delta_time)
1589 next_run -= delta_time;
1594 if (gc_work->exiting)
1598 gc_work->early_drop = false;
1600 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1603 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1605 INIT_DELAYED_WORK(&gc_work->dwork, gc_worker);
1606 gc_work->exiting = false;
1609 static struct nf_conn *
1610 __nf_conntrack_alloc(struct net *net,
1611 const struct nf_conntrack_zone *zone,
1612 const struct nf_conntrack_tuple *orig,
1613 const struct nf_conntrack_tuple *repl,
1614 gfp_t gfp, u32 hash)
1616 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
1617 unsigned int ct_count;
1620 /* We don't want any race condition at early drop stage */
1621 ct_count = atomic_inc_return(&cnet->count);
1623 if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1624 if (!early_drop(net, hash)) {
1625 if (!conntrack_gc_work.early_drop)
1626 conntrack_gc_work.early_drop = true;
1627 atomic_dec(&cnet->count);
1628 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1629 return ERR_PTR(-ENOMEM);
1634 * Do not use kmem_cache_zalloc(), as this cache uses
1635 * SLAB_TYPESAFE_BY_RCU.
1637 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1641 spin_lock_init(&ct->lock);
1642 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1643 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1644 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1645 /* save hash for reusing when confirming */
1646 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1648 WRITE_ONCE(ct->timeout, 0);
1649 write_pnet(&ct->ct_net, net);
1650 memset_after(ct, 0, __nfct_init_offset);
1652 nf_ct_zone_add(ct, zone);
1654 /* Because we use RCU lookups, we set ct_general.use to zero before
1655 * this is inserted in any list.
1657 refcount_set(&ct->ct_general.use, 0);
1660 atomic_dec(&cnet->count);
1661 return ERR_PTR(-ENOMEM);
1664 struct nf_conn *nf_conntrack_alloc(struct net *net,
1665 const struct nf_conntrack_zone *zone,
1666 const struct nf_conntrack_tuple *orig,
1667 const struct nf_conntrack_tuple *repl,
1670 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1672 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1674 void nf_conntrack_free(struct nf_conn *ct)
1676 struct net *net = nf_ct_net(ct);
1677 struct nf_conntrack_net *cnet;
1679 /* A freed object has refcnt == 0, that's
1680 * the golden rule for SLAB_TYPESAFE_BY_RCU
1682 WARN_ON(refcount_read(&ct->ct_general.use) != 0);
1684 if (ct->status & IPS_SRC_NAT_DONE) {
1685 const struct nf_nat_hook *nat_hook;
1688 nat_hook = rcu_dereference(nf_nat_hook);
1690 nat_hook->remove_nat_bysrc(ct);
1695 kmem_cache_free(nf_conntrack_cachep, ct);
1696 cnet = nf_ct_pernet(net);
1698 smp_mb__before_atomic();
1699 atomic_dec(&cnet->count);
1701 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1704 /* Allocate a new conntrack: we return -ENOMEM if classification
1705 failed due to stress. Otherwise it really is unclassifiable. */
1706 static noinline struct nf_conntrack_tuple_hash *
1707 init_conntrack(struct net *net, struct nf_conn *tmpl,
1708 const struct nf_conntrack_tuple *tuple,
1709 struct sk_buff *skb,
1710 unsigned int dataoff, u32 hash)
1713 struct nf_conn_help *help;
1714 struct nf_conntrack_tuple repl_tuple;
1715 #ifdef CONFIG_NF_CONNTRACK_EVENTS
1716 struct nf_conntrack_ecache *ecache;
1718 struct nf_conntrack_expect *exp = NULL;
1719 const struct nf_conntrack_zone *zone;
1720 struct nf_conn_timeout *timeout_ext;
1721 struct nf_conntrack_zone tmp;
1722 struct nf_conntrack_net *cnet;
1724 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1725 pr_debug("Can't invert tuple.\n");
1729 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1730 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1733 return (struct nf_conntrack_tuple_hash *)ct;
1735 if (!nf_ct_add_synproxy(ct, tmpl)) {
1736 nf_conntrack_free(ct);
1737 return ERR_PTR(-ENOMEM);
1740 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1743 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1746 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1747 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1748 nf_ct_labels_ext_add(ct);
1750 #ifdef CONFIG_NF_CONNTRACK_EVENTS
1751 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1753 if ((ecache || net->ct.sysctl_events) &&
1754 !nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1755 ecache ? ecache->expmask : 0,
1757 nf_conntrack_free(ct);
1758 return ERR_PTR(-ENOMEM);
1762 cnet = nf_ct_pernet(net);
1763 if (cnet->expect_count) {
1764 spin_lock_bh(&nf_conntrack_expect_lock);
1765 exp = nf_ct_find_expectation(net, zone, tuple);
1767 pr_debug("expectation arrives ct=%p exp=%p\n",
1769 /* Welcome, Mr. Bond. We've been expecting you... */
1770 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1771 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1772 ct->master = exp->master;
1774 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1776 rcu_assign_pointer(help->helper, exp->helper);
1779 #ifdef CONFIG_NF_CONNTRACK_MARK
1780 ct->mark = exp->master->mark;
1782 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1783 ct->secmark = exp->master->secmark;
1785 NF_CT_STAT_INC(net, expect_new);
1787 spin_unlock_bh(&nf_conntrack_expect_lock);
1790 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1792 /* Other CPU might have obtained a pointer to this object before it was
1793 * released. Because refcount is 0, refcount_inc_not_zero() will fail.
1795 * After refcount_set(1) it will succeed; ensure that zeroing of
1796 * ct->status and the correct ct->net pointer are visible; else other
1797 * core might observe CONFIRMED bit which means the entry is valid and
1798 * in the hash table, but its not (anymore).
1802 /* Now it is going to be associated with an sk_buff, set refcount to 1. */
1803 refcount_set(&ct->ct_general.use, 1);
1807 exp->expectfn(ct, exp);
1808 nf_ct_expect_put(exp);
1811 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1814 /* On success, returns 0, sets skb->_nfct | ctinfo */
1816 resolve_normal_ct(struct nf_conn *tmpl,
1817 struct sk_buff *skb,
1818 unsigned int dataoff,
1820 const struct nf_hook_state *state)
1822 const struct nf_conntrack_zone *zone;
1823 struct nf_conntrack_tuple tuple;
1824 struct nf_conntrack_tuple_hash *h;
1825 enum ip_conntrack_info ctinfo;
1826 struct nf_conntrack_zone tmp;
1827 u32 hash, zone_id, rid;
1830 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1831 dataoff, state->pf, protonum, state->net,
1833 pr_debug("Can't get tuple\n");
1837 /* look for tuple match */
1838 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1840 zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
1841 hash = hash_conntrack_raw(&tuple, zone_id, state->net);
1842 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1845 rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
1846 if (zone_id != rid) {
1847 u32 tmp = hash_conntrack_raw(&tuple, rid, state->net);
1849 h = __nf_conntrack_find_get(state->net, zone, &tuple, tmp);
1854 h = init_conntrack(state->net, tmpl, &tuple,
1855 skb, dataoff, hash);
1861 ct = nf_ct_tuplehash_to_ctrack(h);
1863 /* It exists; we have (non-exclusive) reference. */
1864 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1865 ctinfo = IP_CT_ESTABLISHED_REPLY;
1867 /* Once we've had two way comms, always ESTABLISHED. */
1868 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1869 pr_debug("normal packet for %p\n", ct);
1870 ctinfo = IP_CT_ESTABLISHED;
1871 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1872 pr_debug("related packet for %p\n", ct);
1873 ctinfo = IP_CT_RELATED;
1875 pr_debug("new packet for %p\n", ct);
1879 nf_ct_set(skb, ct, ctinfo);
1884 * icmp packets need special treatment to handle error messages that are
1885 * related to a connection.
1887 * Callers need to check if skb has a conntrack assigned when this
1888 * helper returns; in such case skb belongs to an already known connection.
1890 static unsigned int __cold
1891 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1892 struct sk_buff *skb,
1893 unsigned int dataoff,
1895 const struct nf_hook_state *state)
1899 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1900 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1901 #if IS_ENABLED(CONFIG_IPV6)
1902 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1903 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1909 NF_CT_STAT_INC_ATOMIC(state->net, error);
1914 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1915 enum ip_conntrack_info ctinfo)
1917 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1920 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1922 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1926 /* Returns verdict for packet, or -1 for invalid. */
1927 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1928 struct sk_buff *skb,
1929 unsigned int dataoff,
1930 enum ip_conntrack_info ctinfo,
1931 const struct nf_hook_state *state)
1933 switch (nf_ct_protonum(ct)) {
1935 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1938 return nf_conntrack_udp_packet(ct, skb, dataoff,
1941 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1942 #if IS_ENABLED(CONFIG_IPV6)
1943 case IPPROTO_ICMPV6:
1944 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1946 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1947 case IPPROTO_UDPLITE:
1948 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1951 #ifdef CONFIG_NF_CT_PROTO_SCTP
1953 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1956 #ifdef CONFIG_NF_CT_PROTO_DCCP
1958 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1961 #ifdef CONFIG_NF_CT_PROTO_GRE
1963 return nf_conntrack_gre_packet(ct, skb, dataoff,
1968 return generic_packet(ct, skb, ctinfo);
1972 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1974 enum ip_conntrack_info ctinfo;
1975 struct nf_conn *ct, *tmpl;
1979 tmpl = nf_ct_get(skb, &ctinfo);
1980 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1981 /* Previously seen (loopback or untracked)? Ignore. */
1982 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1983 ctinfo == IP_CT_UNTRACKED)
1988 /* rcu_read_lock()ed by nf_hook_thresh */
1989 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1991 pr_debug("not prepared to track yet or error occurred\n");
1992 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1997 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1998 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
2004 /* ICMP[v6] protocol trackers may assign one conntrack. */
2009 ret = resolve_normal_ct(tmpl, skb, dataoff,
2012 /* Too stressed to deal. */
2013 NF_CT_STAT_INC_ATOMIC(state->net, drop);
2018 ct = nf_ct_get(skb, &ctinfo);
2020 /* Not valid part of a connection */
2021 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
2026 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
2028 /* Invalid: inverse of the return code tells
2029 * the netfilter core what to do */
2030 pr_debug("nf_conntrack_in: Can't track with proto module\n");
2033 /* Special case: TCP tracker reports an attempt to reopen a
2034 * closed/aborted connection. We have to go back and create a
2037 if (ret == -NF_REPEAT)
2040 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
2041 if (ret == -NF_DROP)
2042 NF_CT_STAT_INC_ATOMIC(state->net, drop);
2048 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
2049 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
2050 nf_conntrack_event_cache(IPCT_REPLY, ct);
2057 EXPORT_SYMBOL_GPL(nf_conntrack_in);
2059 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
2060 implicitly racy: see __nf_conntrack_confirm */
2061 void nf_conntrack_alter_reply(struct nf_conn *ct,
2062 const struct nf_conntrack_tuple *newreply)
2064 struct nf_conn_help *help = nfct_help(ct);
2066 /* Should be unconfirmed, so not in hash table yet */
2067 WARN_ON(nf_ct_is_confirmed(ct));
2069 pr_debug("Altering reply tuple of %p to ", ct);
2070 nf_ct_dump_tuple(newreply);
2072 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
2073 if (ct->master || (help && !hlist_empty(&help->expectations)))
2076 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
2078 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
2079 void __nf_ct_refresh_acct(struct nf_conn *ct,
2080 enum ip_conntrack_info ctinfo,
2081 const struct sk_buff *skb,
2085 /* Only update if this is not a fixed timeout */
2086 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
2089 /* If not in hash table, timer will not be active yet */
2090 if (nf_ct_is_confirmed(ct))
2091 extra_jiffies += nfct_time_stamp;
2093 if (READ_ONCE(ct->timeout) != extra_jiffies)
2094 WRITE_ONCE(ct->timeout, extra_jiffies);
2097 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
2099 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
2101 bool nf_ct_kill_acct(struct nf_conn *ct,
2102 enum ip_conntrack_info ctinfo,
2103 const struct sk_buff *skb)
2105 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
2107 return nf_ct_delete(ct, 0, 0);
2109 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
2111 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
2113 #include <linux/netfilter/nfnetlink.h>
2114 #include <linux/netfilter/nfnetlink_conntrack.h>
2115 #include <linux/mutex.h>
2117 /* Generic function for tcp/udp/sctp/dccp and alike. */
2118 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
2119 const struct nf_conntrack_tuple *tuple)
2121 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
2122 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
2123 goto nla_put_failure;
2129 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
2131 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
2132 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
2133 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
2135 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
2137 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
2138 struct nf_conntrack_tuple *t,
2141 if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
2142 if (!tb[CTA_PROTO_SRC_PORT])
2145 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
2148 if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
2149 if (!tb[CTA_PROTO_DST_PORT])
2152 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
2157 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
2159 unsigned int nf_ct_port_nlattr_tuple_size(void)
2161 static unsigned int size __read_mostly;
2164 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2168 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2171 /* Used by ipt_REJECT and ip6t_REJECT. */
2172 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2175 enum ip_conntrack_info ctinfo;
2177 /* This ICMP is in reverse direction to the packet which caused it */
2178 ct = nf_ct_get(skb, &ctinfo);
2179 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2180 ctinfo = IP_CT_RELATED_REPLY;
2182 ctinfo = IP_CT_RELATED;
2184 /* Attach to new skbuff, and increment count */
2185 nf_ct_set(nskb, ct, ctinfo);
2186 nf_conntrack_get(skb_nfct(nskb));
2189 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2191 enum ip_conntrack_info ctinfo)
2193 const struct nf_nat_hook *nat_hook;
2194 struct nf_conntrack_tuple_hash *h;
2195 struct nf_conntrack_tuple tuple;
2196 unsigned int status;
2201 l3num = nf_ct_l3num(ct);
2203 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2207 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2208 l4num, net, &tuple))
2211 if (ct->status & IPS_SRC_NAT) {
2212 memcpy(tuple.src.u3.all,
2213 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2214 sizeof(tuple.src.u3.all));
2216 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2219 if (ct->status & IPS_DST_NAT) {
2220 memcpy(tuple.dst.u3.all,
2221 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2222 sizeof(tuple.dst.u3.all));
2224 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2227 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2231 /* Store status bits of the conntrack that is clashing to re-do NAT
2232 * mangling according to what it has been done already to this packet.
2234 status = ct->status;
2237 ct = nf_ct_tuplehash_to_ctrack(h);
2238 nf_ct_set(skb, ct, ctinfo);
2240 nat_hook = rcu_dereference(nf_nat_hook);
2244 if (status & IPS_SRC_NAT &&
2245 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2246 IP_CT_DIR_ORIGINAL) == NF_DROP)
2249 if (status & IPS_DST_NAT &&
2250 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2251 IP_CT_DIR_ORIGINAL) == NF_DROP)
2257 /* This packet is coming from userspace via nf_queue, complete the packet
2258 * processing after the helper invocation in nf_confirm().
2260 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2261 enum ip_conntrack_info ctinfo)
2263 const struct nf_conntrack_helper *helper;
2264 const struct nf_conn_help *help;
2267 help = nfct_help(ct);
2271 helper = rcu_dereference(help->helper);
2272 if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2275 switch (nf_ct_l3num(ct)) {
2277 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2279 #if IS_ENABLED(CONFIG_IPV6)
2280 case NFPROTO_IPV6: {
2284 pnum = ipv6_hdr(skb)->nexthdr;
2285 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2287 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2296 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2297 !nf_is_loopback_packet(skb)) {
2298 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2299 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2304 /* We've seen it coming out the other side: confirm it */
2305 return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2308 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2310 enum ip_conntrack_info ctinfo;
2314 ct = nf_ct_get(skb, &ctinfo);
2318 if (!nf_ct_is_confirmed(ct)) {
2319 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2323 ct = nf_ct_get(skb, &ctinfo);
2326 return nf_confirm_cthelper(skb, ct, ctinfo);
2329 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2330 const struct sk_buff *skb)
2332 const struct nf_conntrack_tuple *src_tuple;
2333 const struct nf_conntrack_tuple_hash *hash;
2334 struct nf_conntrack_tuple srctuple;
2335 enum ip_conntrack_info ctinfo;
2338 ct = nf_ct_get(skb, &ctinfo);
2340 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2341 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2345 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2346 NFPROTO_IPV4, dev_net(skb->dev),
2350 hash = nf_conntrack_find_get(dev_net(skb->dev),
2356 ct = nf_ct_tuplehash_to_ctrack(hash);
2357 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2358 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2364 /* Bring out ya dead! */
2365 static struct nf_conn *
2366 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2367 const struct nf_ct_iter_data *iter_data, unsigned int *bucket)
2369 struct nf_conntrack_tuple_hash *h;
2371 struct hlist_nulls_node *n;
2374 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2375 struct hlist_nulls_head *hslot = &nf_conntrack_hash[*bucket];
2377 if (hlist_nulls_empty(hslot))
2380 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2382 nf_conntrack_lock(lockp);
2383 hlist_nulls_for_each_entry(h, n, hslot, hnnode) {
2384 if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2386 /* All nf_conn objects are added to hash table twice, one
2387 * for original direction tuple, once for the reply tuple.
2389 * Exception: In the IPS_NAT_CLASH case, only the reply
2390 * tuple is added (the original tuple already existed for
2391 * a different object).
2393 * We only need to call the iterator once for each
2394 * conntrack, so we just use the 'reply' direction
2395 * tuple while iterating.
2397 ct = nf_ct_tuplehash_to_ctrack(h);
2399 if (iter_data->net &&
2400 !net_eq(iter_data->net, nf_ct_net(ct)))
2403 if (iter(ct, iter_data->data))
2413 refcount_inc(&ct->ct_general.use);
2419 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2420 const struct nf_ct_iter_data *iter_data)
2422 unsigned int bucket = 0;
2427 mutex_lock(&nf_conntrack_mutex);
2428 while ((ct = get_next_corpse(iter, iter_data, &bucket)) != NULL) {
2429 /* Time to push up daises... */
2431 nf_ct_delete(ct, iter_data->portid, iter_data->report);
2435 mutex_unlock(&nf_conntrack_mutex);
2438 void nf_ct_iterate_cleanup_net(int (*iter)(struct nf_conn *i, void *data),
2439 const struct nf_ct_iter_data *iter_data)
2441 struct net *net = iter_data->net;
2442 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2446 if (atomic_read(&cnet->count) == 0)
2449 nf_ct_iterate_cleanup(iter, iter_data);
2451 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2454 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2455 * @iter: callback to invoke for each conntrack
2456 * @data: data to pass to @iter
2458 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2459 * unconfirmed list as dying (so they will not be inserted into
2462 * Can only be called in module exit path.
2465 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2467 struct nf_ct_iter_data iter_data = {};
2470 down_read(&net_rwsem);
2472 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2474 if (atomic_read(&cnet->count) == 0)
2476 nf_queue_nf_hook_drop(net);
2478 up_read(&net_rwsem);
2480 /* Need to wait for netns cleanup worker to finish, if its
2481 * running -- it might have deleted a net namespace from
2482 * the global list, so hook drop above might not have
2483 * affected all namespaces.
2487 /* a skb w. unconfirmed conntrack could have been reinjected just
2488 * before we called nf_queue_nf_hook_drop().
2490 * This makes sure its inserted into conntrack table.
2494 nf_ct_ext_bump_genid();
2495 iter_data.data = data;
2496 nf_ct_iterate_cleanup(iter, &iter_data);
2498 /* Another cpu might be in a rcu read section with
2499 * rcu protected pointer cleared in iter callback
2500 * or hidden via nf_ct_ext_bump_genid() above.
2502 * Wait until those are done.
2506 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2508 static int kill_all(struct nf_conn *i, void *data)
2513 void nf_conntrack_cleanup_start(void)
2515 cleanup_nf_conntrack_bpf();
2516 conntrack_gc_work.exiting = true;
2519 void nf_conntrack_cleanup_end(void)
2521 RCU_INIT_POINTER(nf_ct_hook, NULL);
2522 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2523 kvfree(nf_conntrack_hash);
2525 nf_conntrack_proto_fini();
2526 nf_conntrack_helper_fini();
2527 nf_conntrack_expect_fini();
2529 kmem_cache_destroy(nf_conntrack_cachep);
2533 * Mishearing the voices in his head, our hero wonders how he's
2534 * supposed to kill the mall.
2536 void nf_conntrack_cleanup_net(struct net *net)
2540 list_add(&net->exit_list, &single);
2541 nf_conntrack_cleanup_net_list(&single);
2544 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2546 struct nf_ct_iter_data iter_data = {};
2551 * This makes sure all current packets have passed through
2552 * netfilter framework. Roll on, two-stage module
2558 list_for_each_entry(net, net_exit_list, exit_list) {
2559 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2561 iter_data.net = net;
2562 nf_ct_iterate_cleanup_net(kill_all, &iter_data);
2563 if (atomic_read(&cnet->count) != 0)
2568 goto i_see_dead_people;
2571 list_for_each_entry(net, net_exit_list, exit_list) {
2572 nf_conntrack_ecache_pernet_fini(net);
2573 nf_conntrack_expect_pernet_fini(net);
2574 free_percpu(net->ct.stat);
2578 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2580 struct hlist_nulls_head *hash;
2581 unsigned int nr_slots, i;
2583 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2586 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2587 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2589 hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2592 for (i = 0; i < nr_slots; i++)
2593 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2597 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2599 int nf_conntrack_hash_resize(unsigned int hashsize)
2602 unsigned int old_size;
2603 struct hlist_nulls_head *hash, *old_hash;
2604 struct nf_conntrack_tuple_hash *h;
2610 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2614 mutex_lock(&nf_conntrack_mutex);
2615 old_size = nf_conntrack_htable_size;
2616 if (old_size == hashsize) {
2617 mutex_unlock(&nf_conntrack_mutex);
2623 nf_conntrack_all_lock();
2624 write_seqcount_begin(&nf_conntrack_generation);
2626 /* Lookups in the old hash might happen in parallel, which means we
2627 * might get false negatives during connection lookup. New connections
2628 * created because of a false negative won't make it into the hash
2629 * though since that required taking the locks.
2632 for (i = 0; i < nf_conntrack_htable_size; i++) {
2633 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2634 unsigned int zone_id;
2636 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2637 struct nf_conntrack_tuple_hash, hnnode);
2638 ct = nf_ct_tuplehash_to_ctrack(h);
2639 hlist_nulls_del_rcu(&h->hnnode);
2641 zone_id = nf_ct_zone_id(nf_ct_zone(ct), NF_CT_DIRECTION(h));
2642 bucket = __hash_conntrack(nf_ct_net(ct),
2643 &h->tuple, zone_id, hashsize);
2644 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2647 old_hash = nf_conntrack_hash;
2649 nf_conntrack_hash = hash;
2650 nf_conntrack_htable_size = hashsize;
2652 write_seqcount_end(&nf_conntrack_generation);
2653 nf_conntrack_all_unlock();
2656 mutex_unlock(&nf_conntrack_mutex);
2663 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2665 unsigned int hashsize;
2668 if (current->nsproxy->net_ns != &init_net)
2671 /* On boot, we can set this without any fancy locking. */
2672 if (!nf_conntrack_hash)
2673 return param_set_uint(val, kp);
2675 rc = kstrtouint(val, 0, &hashsize);
2679 return nf_conntrack_hash_resize(hashsize);
2682 int nf_conntrack_init_start(void)
2684 unsigned long nr_pages = totalram_pages();
2689 seqcount_spinlock_init(&nf_conntrack_generation,
2690 &nf_conntrack_locks_all_lock);
2692 for (i = 0; i < CONNTRACK_LOCKS; i++)
2693 spin_lock_init(&nf_conntrack_locks[i]);
2695 if (!nf_conntrack_htable_size) {
2696 nf_conntrack_htable_size
2697 = (((nr_pages << PAGE_SHIFT) / 16384)
2698 / sizeof(struct hlist_head));
2699 if (BITS_PER_LONG >= 64 &&
2700 nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2701 nf_conntrack_htable_size = 262144;
2702 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2703 nf_conntrack_htable_size = 65536;
2705 if (nf_conntrack_htable_size < 1024)
2706 nf_conntrack_htable_size = 1024;
2707 /* Use a max. factor of one by default to keep the average
2708 * hash chain length at 2 entries. Each entry has to be added
2709 * twice (once for original direction, once for reply).
2710 * When a table size is given we use the old value of 8 to
2711 * avoid implicit reduction of the max entries setting.
2716 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2717 if (!nf_conntrack_hash)
2720 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2722 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2723 sizeof(struct nf_conn),
2725 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2726 if (!nf_conntrack_cachep)
2729 ret = nf_conntrack_expect_init();
2733 ret = nf_conntrack_helper_init();
2737 ret = nf_conntrack_proto_init();
2741 conntrack_gc_work_init(&conntrack_gc_work);
2742 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2744 ret = register_nf_conntrack_bpf();
2751 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2752 nf_conntrack_proto_fini();
2754 nf_conntrack_helper_fini();
2756 nf_conntrack_expect_fini();
2758 kmem_cache_destroy(nf_conntrack_cachep);
2760 kvfree(nf_conntrack_hash);
2764 static const struct nf_ct_hook nf_conntrack_hook = {
2765 .update = nf_conntrack_update,
2766 .destroy = nf_ct_destroy,
2767 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2768 .attach = nf_conntrack_attach,
2771 void nf_conntrack_init_end(void)
2773 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2777 * We need to use special "null" values, not used in hash table
2779 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2781 int nf_conntrack_init_net(struct net *net)
2783 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2786 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2787 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2788 atomic_set(&cnet->count, 0);
2790 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2794 ret = nf_conntrack_expect_pernet_init(net);
2798 nf_conntrack_acct_pernet_init(net);
2799 nf_conntrack_tstamp_pernet_init(net);
2800 nf_conntrack_ecache_pernet_init(net);
2801 nf_conntrack_proto_pernet_init(net);
2806 free_percpu(net->ct.stat);
2810 /* ctnetlink code shared by both ctnetlink and nf_conntrack_bpf */
2812 int __nf_ct_change_timeout(struct nf_conn *ct, u64 timeout)
2814 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
2817 __nf_ct_set_timeout(ct, timeout);
2819 if (test_bit(IPS_DYING_BIT, &ct->status))
2824 EXPORT_SYMBOL_GPL(__nf_ct_change_timeout);
2826 void __nf_ct_change_status(struct nf_conn *ct, unsigned long on, unsigned long off)
2830 /* Ignore these unchangable bits */
2831 on &= ~IPS_UNCHANGEABLE_MASK;
2832 off &= ~IPS_UNCHANGEABLE_MASK;
2834 for (bit = 0; bit < __IPS_MAX_BIT; bit++) {
2835 if (on & (1 << bit))
2836 set_bit(bit, &ct->status);
2837 else if (off & (1 << bit))
2838 clear_bit(bit, &ct->status);
2841 EXPORT_SYMBOL_GPL(__nf_ct_change_status);
2843 int nf_ct_change_status_common(struct nf_conn *ct, unsigned int status)
2847 d = ct->status ^ status;
2849 if (d & (IPS_EXPECTED|IPS_CONFIRMED|IPS_DYING))
2853 if (d & IPS_SEEN_REPLY && !(status & IPS_SEEN_REPLY))
2854 /* SEEN_REPLY bit can only be set */
2857 if (d & IPS_ASSURED && !(status & IPS_ASSURED))
2858 /* ASSURED bit can only be set */
2861 __nf_ct_change_status(ct, status, 0);
2864 EXPORT_SYMBOL_GPL(nf_ct_change_status_common);