1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter. This is separated from,
3 but required by, the NAT layer; it can also be used by an iptables
6 /* (C) 1999-2001 Paul `Rusty' Russell
7 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9 * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/jhash.h>
25 #include <linux/siphash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
37 #include <net/netfilter/nf_conntrack.h>
38 #include <net/netfilter/nf_conntrack_l4proto.h>
39 #include <net/netfilter/nf_conntrack_expect.h>
40 #include <net/netfilter/nf_conntrack_helper.h>
41 #include <net/netfilter/nf_conntrack_seqadj.h>
42 #include <net/netfilter/nf_conntrack_core.h>
43 #include <net/netfilter/nf_conntrack_extend.h>
44 #include <net/netfilter/nf_conntrack_acct.h>
45 #include <net/netfilter/nf_conntrack_ecache.h>
46 #include <net/netfilter/nf_conntrack_zones.h>
47 #include <net/netfilter/nf_conntrack_timestamp.h>
48 #include <net/netfilter/nf_conntrack_timeout.h>
49 #include <net/netfilter/nf_conntrack_labels.h>
50 #include <net/netfilter/nf_conntrack_synproxy.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_helper.h>
53 #include <net/netns/hash.h>
56 #include "nf_internals.h"
58 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
59 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
61 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
62 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
64 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
65 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
67 struct conntrack_gc_work {
68 struct delayed_work dwork;
74 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
75 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
76 static __read_mostly bool nf_conntrack_locks_all;
78 #define GC_SCAN_INTERVAL (120u * HZ)
79 #define GC_SCAN_MAX_DURATION msecs_to_jiffies(10)
81 static struct conntrack_gc_work conntrack_gc_work;
83 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
85 /* 1) Acquire the lock */
88 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
89 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
91 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
94 /* fast path failed, unlock */
97 /* Slow path 1) get global lock */
98 spin_lock(&nf_conntrack_locks_all_lock);
100 /* Slow path 2) get the lock we want */
103 /* Slow path 3) release the global lock */
104 spin_unlock(&nf_conntrack_locks_all_lock);
106 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
108 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
110 h1 %= CONNTRACK_LOCKS;
111 h2 %= CONNTRACK_LOCKS;
112 spin_unlock(&nf_conntrack_locks[h1]);
114 spin_unlock(&nf_conntrack_locks[h2]);
117 /* return true if we need to recompute hashes (in case hash table was resized) */
118 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
119 unsigned int h2, unsigned int sequence)
121 h1 %= CONNTRACK_LOCKS;
122 h2 %= CONNTRACK_LOCKS;
124 nf_conntrack_lock(&nf_conntrack_locks[h1]);
126 spin_lock_nested(&nf_conntrack_locks[h2],
127 SINGLE_DEPTH_NESTING);
129 nf_conntrack_lock(&nf_conntrack_locks[h2]);
130 spin_lock_nested(&nf_conntrack_locks[h1],
131 SINGLE_DEPTH_NESTING);
133 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
134 nf_conntrack_double_unlock(h1, h2);
140 static void nf_conntrack_all_lock(void)
141 __acquires(&nf_conntrack_locks_all_lock)
145 spin_lock(&nf_conntrack_locks_all_lock);
147 /* For nf_contrack_locks_all, only the latest time when another
148 * CPU will see an update is controlled, by the "release" of the
150 * The earliest time is not controlled, an thus KCSAN could detect
151 * a race when nf_conntract_lock() reads the variable.
152 * WRITE_ONCE() is used to ensure the compiler will not
153 * optimize the write.
155 WRITE_ONCE(nf_conntrack_locks_all, true);
157 for (i = 0; i < CONNTRACK_LOCKS; i++) {
158 spin_lock(&nf_conntrack_locks[i]);
160 /* This spin_unlock provides the "release" to ensure that
161 * nf_conntrack_locks_all==true is visible to everyone that
162 * acquired spin_lock(&nf_conntrack_locks[]).
164 spin_unlock(&nf_conntrack_locks[i]);
168 static void nf_conntrack_all_unlock(void)
169 __releases(&nf_conntrack_locks_all_lock)
171 /* All prior stores must be complete before we clear
172 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
173 * might observe the false value but not the entire
175 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
177 smp_store_release(&nf_conntrack_locks_all, false);
178 spin_unlock(&nf_conntrack_locks_all_lock);
181 unsigned int nf_conntrack_htable_size __read_mostly;
182 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
184 unsigned int nf_conntrack_max __read_mostly;
185 EXPORT_SYMBOL_GPL(nf_conntrack_max);
186 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
187 static unsigned int nf_conntrack_hash_rnd __read_mostly;
189 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
190 const struct net *net)
195 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
197 /* The direction must be ignored, so we hash everything up to the
198 * destination ports (which is a multiple of 4) and treat the last
199 * three bytes manually.
201 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
202 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
203 return jhash2((u32 *)tuple, n, seed ^
204 (((__force __u16)tuple->dst.u.all << 16) |
205 tuple->dst.protonum));
208 static u32 scale_hash(u32 hash)
210 return reciprocal_scale(hash, nf_conntrack_htable_size);
213 static u32 __hash_conntrack(const struct net *net,
214 const struct nf_conntrack_tuple *tuple,
217 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
220 static u32 hash_conntrack(const struct net *net,
221 const struct nf_conntrack_tuple *tuple)
223 return scale_hash(hash_conntrack_raw(tuple, net));
226 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
227 unsigned int dataoff,
228 struct nf_conntrack_tuple *tuple)
232 } _inet_hdr, *inet_hdr;
234 /* Actually only need first 4 bytes to get ports. */
235 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
239 tuple->src.u.udp.port = inet_hdr->sport;
240 tuple->dst.u.udp.port = inet_hdr->dport;
245 nf_ct_get_tuple(const struct sk_buff *skb,
247 unsigned int dataoff,
251 struct nf_conntrack_tuple *tuple)
257 memset(tuple, 0, sizeof(*tuple));
259 tuple->src.l3num = l3num;
262 nhoff += offsetof(struct iphdr, saddr);
263 size = 2 * sizeof(__be32);
266 nhoff += offsetof(struct ipv6hdr, saddr);
267 size = sizeof(_addrs);
273 ap = skb_header_pointer(skb, nhoff, size, _addrs);
279 tuple->src.u3.ip = ap[0];
280 tuple->dst.u3.ip = ap[1];
283 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
284 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
288 tuple->dst.protonum = protonum;
289 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
292 #if IS_ENABLED(CONFIG_IPV6)
294 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
297 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
298 #ifdef CONFIG_NF_CT_PROTO_GRE
300 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
303 case IPPROTO_UDP: /* fallthrough */
304 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
305 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
306 case IPPROTO_UDPLITE:
307 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
309 #ifdef CONFIG_NF_CT_PROTO_SCTP
311 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
313 #ifdef CONFIG_NF_CT_PROTO_DCCP
315 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
324 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
328 const struct iphdr *iph;
331 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
335 /* Conntrack defragments packets, we might still see fragments
336 * inside ICMP packets though.
338 if (iph->frag_off & htons(IP_OFFSET))
341 dataoff = nhoff + (iph->ihl << 2);
342 *protonum = iph->protocol;
344 /* Check bogus IP headers */
345 if (dataoff > skb->len) {
346 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
347 nhoff, iph->ihl << 2, skb->len);
353 #if IS_ENABLED(CONFIG_IPV6)
354 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
358 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
362 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
363 &nexthdr, sizeof(nexthdr)) != 0) {
364 pr_debug("can't get nexthdr\n");
367 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
369 * (protoff == skb->len) means the packet has not data, just
370 * IPv6 and possibly extensions headers, but it is tracked anyway
372 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
373 pr_debug("can't find proto in pkt\n");
382 static int get_l4proto(const struct sk_buff *skb,
383 unsigned int nhoff, u8 pf, u8 *l4num)
387 return ipv4_get_l4proto(skb, nhoff, l4num);
388 #if IS_ENABLED(CONFIG_IPV6)
390 return ipv6_get_l4proto(skb, nhoff, l4num);
399 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
401 struct net *net, struct nf_conntrack_tuple *tuple)
406 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
410 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
412 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
415 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
416 const struct nf_conntrack_tuple *orig)
418 memset(inverse, 0, sizeof(*inverse));
420 inverse->src.l3num = orig->src.l3num;
422 switch (orig->src.l3num) {
424 inverse->src.u3.ip = orig->dst.u3.ip;
425 inverse->dst.u3.ip = orig->src.u3.ip;
428 inverse->src.u3.in6 = orig->dst.u3.in6;
429 inverse->dst.u3.in6 = orig->src.u3.in6;
435 inverse->dst.dir = !orig->dst.dir;
437 inverse->dst.protonum = orig->dst.protonum;
439 switch (orig->dst.protonum) {
441 return nf_conntrack_invert_icmp_tuple(inverse, orig);
442 #if IS_ENABLED(CONFIG_IPV6)
444 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
448 inverse->src.u.all = orig->dst.u.all;
449 inverse->dst.u.all = orig->src.u.all;
452 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
454 /* Generate a almost-unique pseudo-id for a given conntrack.
456 * intentionally doesn't re-use any of the seeds used for hash
457 * table location, we assume id gets exposed to userspace.
459 * Following nf_conn items do not change throughout lifetime
463 * 2. nf_conn->master address (normally NULL)
464 * 3. the associated net namespace
465 * 4. the original direction tuple
467 u32 nf_ct_get_id(const struct nf_conn *ct)
469 static __read_mostly siphash_key_t ct_id_seed;
470 unsigned long a, b, c, d;
472 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
474 a = (unsigned long)ct;
475 b = (unsigned long)ct->master;
476 c = (unsigned long)nf_ct_net(ct);
477 d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
478 sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
481 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
483 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
486 EXPORT_SYMBOL_GPL(nf_ct_get_id);
489 clean_from_lists(struct nf_conn *ct)
491 pr_debug("clean_from_lists(%p)\n", ct);
492 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
493 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
495 /* Destroy all pending expectations */
496 nf_ct_remove_expectations(ct);
499 /* must be called with local_bh_disable */
500 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
502 struct ct_pcpu *pcpu;
504 /* add this conntrack to the (per cpu) dying list */
505 ct->cpu = smp_processor_id();
506 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
508 spin_lock(&pcpu->lock);
509 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
511 spin_unlock(&pcpu->lock);
514 /* must be called with local_bh_disable */
515 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
517 struct ct_pcpu *pcpu;
519 /* add this conntrack to the (per cpu) unconfirmed list */
520 ct->cpu = smp_processor_id();
521 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
523 spin_lock(&pcpu->lock);
524 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
526 spin_unlock(&pcpu->lock);
529 /* must be called with local_bh_disable */
530 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
532 struct ct_pcpu *pcpu;
534 /* We overload first tuple to link into unconfirmed or dying list.*/
535 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
537 spin_lock(&pcpu->lock);
538 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
539 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
540 spin_unlock(&pcpu->lock);
543 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
545 /* Released via destroy_conntrack() */
546 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
547 const struct nf_conntrack_zone *zone,
550 struct nf_conn *tmpl, *p;
552 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
553 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
558 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
560 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
561 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
564 tmpl = kzalloc(sizeof(*tmpl), flags);
569 tmpl->status = IPS_TEMPLATE;
570 write_pnet(&tmpl->ct_net, net);
571 nf_ct_zone_add(tmpl, zone);
572 atomic_set(&tmpl->ct_general.use, 0);
576 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
578 void nf_ct_tmpl_free(struct nf_conn *tmpl)
580 nf_ct_ext_destroy(tmpl);
582 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
583 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
587 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
589 static void destroy_gre_conntrack(struct nf_conn *ct)
591 #ifdef CONFIG_NF_CT_PROTO_GRE
592 struct nf_conn *master = ct->master;
595 nf_ct_gre_keymap_destroy(master);
600 destroy_conntrack(struct nf_conntrack *nfct)
602 struct nf_conn *ct = (struct nf_conn *)nfct;
604 pr_debug("destroy_conntrack(%p)\n", ct);
605 WARN_ON(atomic_read(&nfct->use) != 0);
607 if (unlikely(nf_ct_is_template(ct))) {
612 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
613 destroy_gre_conntrack(ct);
616 /* Expectations will have been removed in clean_from_lists,
617 * except TFTP can create an expectation on the first packet,
618 * before connection is in the list, so we need to clean here,
621 nf_ct_remove_expectations(ct);
623 nf_ct_del_from_dying_or_unconfirmed_list(ct);
628 nf_ct_put(ct->master);
630 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
631 nf_conntrack_free(ct);
634 static void nf_ct_delete_from_lists(struct nf_conn *ct)
636 struct net *net = nf_ct_net(ct);
637 unsigned int hash, reply_hash;
638 unsigned int sequence;
640 nf_ct_helper_destroy(ct);
644 sequence = read_seqcount_begin(&nf_conntrack_generation);
645 hash = hash_conntrack(net,
646 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
647 reply_hash = hash_conntrack(net,
648 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
649 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
651 clean_from_lists(ct);
652 nf_conntrack_double_unlock(hash, reply_hash);
654 nf_ct_add_to_dying_list(ct);
659 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
661 struct nf_conn_tstamp *tstamp;
664 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
667 tstamp = nf_conn_tstamp_find(ct);
669 s32 timeout = ct->timeout - nfct_time_stamp;
671 tstamp->stop = ktime_get_real_ns();
673 tstamp->stop -= jiffies_to_nsecs(-timeout);
676 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
677 portid, report) < 0) {
678 /* destroy event was not delivered. nf_ct_put will
679 * be done by event cache worker on redelivery.
681 nf_ct_delete_from_lists(ct);
682 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
687 if (nf_conntrack_ecache_dwork_pending(net))
688 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
689 nf_ct_delete_from_lists(ct);
693 EXPORT_SYMBOL_GPL(nf_ct_delete);
696 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
697 const struct nf_conntrack_tuple *tuple,
698 const struct nf_conntrack_zone *zone,
699 const struct net *net)
701 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
703 /* A conntrack can be recreated with the equal tuple,
704 * so we need to check that the conntrack is confirmed
706 return nf_ct_tuple_equal(tuple, &h->tuple) &&
707 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
708 nf_ct_is_confirmed(ct) &&
709 net_eq(net, nf_ct_net(ct));
713 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
715 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
716 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
717 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
718 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
719 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
720 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
721 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
724 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
725 static void nf_ct_gc_expired(struct nf_conn *ct)
727 if (!atomic_inc_not_zero(&ct->ct_general.use))
730 if (nf_ct_should_gc(ct))
738 * - Caller must take a reference on returned object
739 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
741 static struct nf_conntrack_tuple_hash *
742 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
743 const struct nf_conntrack_tuple *tuple, u32 hash)
745 struct nf_conntrack_tuple_hash *h;
746 struct hlist_nulls_head *ct_hash;
747 struct hlist_nulls_node *n;
748 unsigned int bucket, hsize;
751 nf_conntrack_get_ht(&ct_hash, &hsize);
752 bucket = reciprocal_scale(hash, hsize);
754 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
757 ct = nf_ct_tuplehash_to_ctrack(h);
758 if (nf_ct_is_expired(ct)) {
759 nf_ct_gc_expired(ct);
763 if (nf_ct_key_equal(h, tuple, zone, net))
767 * if the nulls value we got at the end of this lookup is
768 * not the expected one, we must restart lookup.
769 * We probably met an item that was moved to another chain.
771 if (get_nulls_value(n) != bucket) {
772 NF_CT_STAT_INC_ATOMIC(net, search_restart);
779 /* Find a connection corresponding to a tuple. */
780 static struct nf_conntrack_tuple_hash *
781 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
782 const struct nf_conntrack_tuple *tuple, u32 hash)
784 struct nf_conntrack_tuple_hash *h;
789 h = ____nf_conntrack_find(net, zone, tuple, hash);
791 /* We have a candidate that matches the tuple we're interested
792 * in, try to obtain a reference and re-check tuple
794 ct = nf_ct_tuplehash_to_ctrack(h);
795 if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
796 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
799 /* TYPESAFE_BY_RCU recycled the candidate */
811 struct nf_conntrack_tuple_hash *
812 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
813 const struct nf_conntrack_tuple *tuple)
815 return __nf_conntrack_find_get(net, zone, tuple,
816 hash_conntrack_raw(tuple, net));
818 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
820 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
822 unsigned int reply_hash)
824 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
825 &nf_conntrack_hash[hash]);
826 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
827 &nf_conntrack_hash[reply_hash]);
831 nf_conntrack_hash_check_insert(struct nf_conn *ct)
833 const struct nf_conntrack_zone *zone;
834 struct net *net = nf_ct_net(ct);
835 unsigned int hash, reply_hash;
836 struct nf_conntrack_tuple_hash *h;
837 struct hlist_nulls_node *n;
838 unsigned int sequence;
840 zone = nf_ct_zone(ct);
844 sequence = read_seqcount_begin(&nf_conntrack_generation);
845 hash = hash_conntrack(net,
846 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
847 reply_hash = hash_conntrack(net,
848 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
849 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
851 /* See if there's one in the list already, including reverse */
852 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
853 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
857 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
858 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
863 /* The caller holds a reference to this object */
864 atomic_set(&ct->ct_general.use, 2);
865 __nf_conntrack_hash_insert(ct, hash, reply_hash);
866 nf_conntrack_double_unlock(hash, reply_hash);
867 NF_CT_STAT_INC(net, insert);
872 nf_conntrack_double_unlock(hash, reply_hash);
876 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
878 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
881 struct nf_conn_acct *acct;
883 acct = nf_conn_acct_find(ct);
885 struct nf_conn_counter *counter = acct->counter;
887 atomic64_add(packets, &counter[dir].packets);
888 atomic64_add(bytes, &counter[dir].bytes);
891 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
893 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
894 const struct nf_conn *loser_ct)
896 struct nf_conn_acct *acct;
898 acct = nf_conn_acct_find(loser_ct);
900 struct nf_conn_counter *counter = acct->counter;
903 /* u32 should be fine since we must have seen one packet. */
904 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
905 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
909 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
911 struct nf_conn_tstamp *tstamp;
913 atomic_inc(&ct->ct_general.use);
914 ct->status |= IPS_CONFIRMED;
916 /* set conntrack timestamp, if enabled. */
917 tstamp = nf_conn_tstamp_find(ct);
919 tstamp->start = ktime_get_real_ns();
922 /* caller must hold locks to prevent concurrent changes */
923 static int __nf_ct_resolve_clash(struct sk_buff *skb,
924 struct nf_conntrack_tuple_hash *h)
926 /* This is the conntrack entry already in hashes that won race. */
927 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
928 enum ip_conntrack_info ctinfo;
929 struct nf_conn *loser_ct;
931 loser_ct = nf_ct_get(skb, &ctinfo);
933 if (nf_ct_is_dying(ct))
936 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
937 nf_ct_match(ct, loser_ct)) {
938 struct net *net = nf_ct_net(ct);
940 nf_conntrack_get(&ct->ct_general);
942 nf_ct_acct_merge(ct, ctinfo, loser_ct);
943 nf_ct_add_to_dying_list(loser_ct);
944 nf_conntrack_put(&loser_ct->ct_general);
945 nf_ct_set(skb, ct, ctinfo);
947 NF_CT_STAT_INC(net, clash_resolve);
955 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
957 * @skb: skb that causes the collision
958 * @repl_idx: hash slot for reply direction
960 * Called when origin or reply direction had a clash.
961 * The skb can be handled without packet drop provided the reply direction
962 * is unique or there the existing entry has the identical tuple in both
965 * Caller must hold conntrack table locks to prevent concurrent updates.
967 * Returns NF_DROP if the clash could not be handled.
969 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
971 struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
972 const struct nf_conntrack_zone *zone;
973 struct nf_conntrack_tuple_hash *h;
974 struct hlist_nulls_node *n;
977 zone = nf_ct_zone(loser_ct);
978 net = nf_ct_net(loser_ct);
980 /* Reply direction must never result in a clash, unless both origin
981 * and reply tuples are identical.
983 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
984 if (nf_ct_key_equal(h,
985 &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
987 return __nf_ct_resolve_clash(skb, h);
990 /* We want the clashing entry to go away real soon: 1 second timeout. */
991 loser_ct->timeout = nfct_time_stamp + HZ;
993 /* IPS_NAT_CLASH removes the entry automatically on the first
994 * reply. Also prevents UDP tracker from moving the entry to
995 * ASSURED state, i.e. the entry can always be evicted under
998 loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
1000 __nf_conntrack_insert_prepare(loser_ct);
1002 /* fake add for ORIGINAL dir: we want lookups to only find the entry
1003 * already in the table. This also hides the clashing entry from
1004 * ctnetlink iteration, i.e. conntrack -L won't show them.
1006 hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1008 hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1009 &nf_conntrack_hash[repl_idx]);
1011 NF_CT_STAT_INC(net, clash_resolve);
1016 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1018 * @skb: skb that causes the clash
1019 * @h: tuplehash of the clashing entry already in table
1020 * @reply_hash: hash slot for reply direction
1022 * A conntrack entry can be inserted to the connection tracking table
1023 * if there is no existing entry with an identical tuple.
1025 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1026 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1027 * will find the already-existing entry.
1029 * The major problem with such packet drop is the extra delay added by
1030 * the packet loss -- it will take some time for a retransmit to occur
1031 * (or the sender to time out when waiting for a reply).
1033 * This function attempts to handle the situation without packet drop.
1035 * If @skb has no NAT transformation or if the colliding entries are
1036 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1037 * and @skb is associated with the conntrack entry already in the table.
1039 * Failing that, the new, unconfirmed conntrack is still added to the table
1040 * provided that the collision only occurs in the ORIGINAL direction.
1041 * The new entry will be added only in the non-clashing REPLY direction,
1042 * so packets in the ORIGINAL direction will continue to match the existing
1043 * entry. The new entry will also have a fixed timeout so it expires --
1044 * due to the collision, it will only see reply traffic.
1046 * Returns NF_DROP if the clash could not be resolved.
1048 static __cold noinline int
1049 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1052 /* This is the conntrack entry already in hashes that won race. */
1053 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1054 const struct nf_conntrack_l4proto *l4proto;
1055 enum ip_conntrack_info ctinfo;
1056 struct nf_conn *loser_ct;
1060 loser_ct = nf_ct_get(skb, &ctinfo);
1061 net = nf_ct_net(loser_ct);
1063 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1064 if (!l4proto->allow_clash)
1067 ret = __nf_ct_resolve_clash(skb, h);
1068 if (ret == NF_ACCEPT)
1071 ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1072 if (ret == NF_ACCEPT)
1076 nf_ct_add_to_dying_list(loser_ct);
1077 NF_CT_STAT_INC(net, drop);
1078 NF_CT_STAT_INC(net, insert_failed);
1082 /* Confirm a connection given skb; places it in hash table */
1084 __nf_conntrack_confirm(struct sk_buff *skb)
1086 const struct nf_conntrack_zone *zone;
1087 unsigned int hash, reply_hash;
1088 struct nf_conntrack_tuple_hash *h;
1090 struct nf_conn_help *help;
1091 struct hlist_nulls_node *n;
1092 enum ip_conntrack_info ctinfo;
1094 unsigned int sequence;
1097 ct = nf_ct_get(skb, &ctinfo);
1098 net = nf_ct_net(ct);
1100 /* ipt_REJECT uses nf_conntrack_attach to attach related
1101 ICMP/TCP RST packets in other direction. Actual packet
1102 which created connection will be IP_CT_NEW or for an
1103 expected connection, IP_CT_RELATED. */
1104 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1107 zone = nf_ct_zone(ct);
1111 sequence = read_seqcount_begin(&nf_conntrack_generation);
1112 /* reuse the hash saved before */
1113 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1114 hash = scale_hash(hash);
1115 reply_hash = hash_conntrack(net,
1116 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
1118 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1120 /* We're not in hash table, and we refuse to set up related
1121 * connections for unconfirmed conns. But packet copies and
1122 * REJECT will give spurious warnings here.
1125 /* Another skb with the same unconfirmed conntrack may
1126 * win the race. This may happen for bridge(br_flood)
1127 * or broadcast/multicast packets do skb_clone with
1128 * unconfirmed conntrack.
1130 if (unlikely(nf_ct_is_confirmed(ct))) {
1132 nf_conntrack_double_unlock(hash, reply_hash);
1137 pr_debug("Confirming conntrack %p\n", ct);
1138 /* We have to check the DYING flag after unlink to prevent
1139 * a race against nf_ct_get_next_corpse() possibly called from
1140 * user context, else we insert an already 'dead' hash, blocking
1141 * further use of that particular connection -JM.
1143 nf_ct_del_from_dying_or_unconfirmed_list(ct);
1145 if (unlikely(nf_ct_is_dying(ct))) {
1146 nf_ct_add_to_dying_list(ct);
1147 NF_CT_STAT_INC(net, insert_failed);
1151 /* See if there's one in the list already, including reverse:
1152 NAT could have grabbed it without realizing, since we're
1153 not in the hash. If there is, we lost race. */
1154 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
1155 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1159 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
1160 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1164 /* Timer relative to confirmation time, not original
1165 setting time, otherwise we'd get timer wrap in
1166 weird delay cases. */
1167 ct->timeout += nfct_time_stamp;
1169 __nf_conntrack_insert_prepare(ct);
1171 /* Since the lookup is lockless, hash insertion must be done after
1172 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1173 * guarantee that no other CPU can find the conntrack before the above
1174 * stores are visible.
1176 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1177 nf_conntrack_double_unlock(hash, reply_hash);
1180 help = nfct_help(ct);
1181 if (help && help->helper)
1182 nf_conntrack_event_cache(IPCT_HELPER, ct);
1184 nf_conntrack_event_cache(master_ct(ct) ?
1185 IPCT_RELATED : IPCT_NEW, ct);
1189 ret = nf_ct_resolve_clash(skb, h, reply_hash);
1191 nf_conntrack_double_unlock(hash, reply_hash);
1195 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1197 /* Returns true if a connection correspondings to the tuple (required
1200 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1201 const struct nf_conn *ignored_conntrack)
1203 struct net *net = nf_ct_net(ignored_conntrack);
1204 const struct nf_conntrack_zone *zone;
1205 struct nf_conntrack_tuple_hash *h;
1206 struct hlist_nulls_head *ct_hash;
1207 unsigned int hash, hsize;
1208 struct hlist_nulls_node *n;
1211 zone = nf_ct_zone(ignored_conntrack);
1215 nf_conntrack_get_ht(&ct_hash, &hsize);
1216 hash = __hash_conntrack(net, tuple, hsize);
1218 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1219 ct = nf_ct_tuplehash_to_ctrack(h);
1221 if (ct == ignored_conntrack)
1224 if (nf_ct_is_expired(ct)) {
1225 nf_ct_gc_expired(ct);
1229 if (nf_ct_key_equal(h, tuple, zone, net)) {
1230 /* Tuple is taken already, so caller will need to find
1231 * a new source port to use.
1234 * If the *original tuples* are identical, then both
1235 * conntracks refer to the same flow.
1236 * This is a rare situation, it can occur e.g. when
1237 * more than one UDP packet is sent from same socket
1238 * in different threads.
1240 * Let nf_ct_resolve_clash() deal with this later.
1242 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1243 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1244 nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1247 NF_CT_STAT_INC_ATOMIC(net, found);
1253 if (get_nulls_value(n) != hash) {
1254 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1262 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1264 #define NF_CT_EVICTION_RANGE 8
1266 /* There's a small race here where we may free a just-assured
1267 connection. Too bad: we're in trouble anyway. */
1268 static unsigned int early_drop_list(struct net *net,
1269 struct hlist_nulls_head *head)
1271 struct nf_conntrack_tuple_hash *h;
1272 struct hlist_nulls_node *n;
1273 unsigned int drops = 0;
1274 struct nf_conn *tmp;
1276 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1277 tmp = nf_ct_tuplehash_to_ctrack(h);
1279 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1282 if (nf_ct_is_expired(tmp)) {
1283 nf_ct_gc_expired(tmp);
1287 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1288 !net_eq(nf_ct_net(tmp), net) ||
1289 nf_ct_is_dying(tmp))
1292 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1295 /* kill only if still in same netns -- might have moved due to
1296 * SLAB_TYPESAFE_BY_RCU rules.
1298 * We steal the timer reference. If that fails timer has
1299 * already fired or someone else deleted it. Just drop ref
1300 * and move to next entry.
1302 if (net_eq(nf_ct_net(tmp), net) &&
1303 nf_ct_is_confirmed(tmp) &&
1304 nf_ct_delete(tmp, 0, 0))
1313 static noinline int early_drop(struct net *net, unsigned int hash)
1315 unsigned int i, bucket;
1317 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1318 struct hlist_nulls_head *ct_hash;
1319 unsigned int hsize, drops;
1322 nf_conntrack_get_ht(&ct_hash, &hsize);
1324 bucket = reciprocal_scale(hash, hsize);
1326 bucket = (bucket + 1) % hsize;
1328 drops = early_drop_list(net, &ct_hash[bucket]);
1332 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1340 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1342 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1345 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1347 const struct nf_conntrack_l4proto *l4proto;
1349 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1352 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1353 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1359 static void gc_worker(struct work_struct *work)
1361 unsigned long end_time = jiffies + GC_SCAN_MAX_DURATION;
1362 unsigned int i, hashsz, nf_conntrack_max95 = 0;
1363 unsigned long next_run = GC_SCAN_INTERVAL;
1364 struct conntrack_gc_work *gc_work;
1365 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1367 i = gc_work->next_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 struct nf_conn *tmp;
1379 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);
1391 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1392 nf_ct_offload_timeout(tmp);
1396 if (nf_ct_is_expired(tmp)) {
1397 nf_ct_gc_expired(tmp);
1401 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1404 net = nf_ct_net(tmp);
1405 cnet = nf_ct_pernet(net);
1406 if (atomic_read(&cnet->count) < nf_conntrack_max95)
1409 /* need to take reference to avoid possible races */
1410 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1413 if (gc_worker_skip_ct(tmp)) {
1418 if (gc_worker_can_early_drop(tmp))
1424 /* could check get_nulls_value() here and restart if ct
1425 * was moved to another chain. But given gc is best-effort
1426 * we will just continue with next hash slot.
1432 if (time_after(jiffies, end_time) && i < hashsz) {
1433 gc_work->next_bucket = i;
1437 } while (i < hashsz);
1439 if (gc_work->exiting)
1443 * Eviction will normally happen from the packet path, and not
1444 * from this gc worker.
1446 * This worker is only here to reap expired entries when system went
1447 * idle after a busy period.
1450 gc_work->early_drop = false;
1451 gc_work->next_bucket = 0;
1453 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1456 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1458 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1459 gc_work->exiting = false;
1462 static struct nf_conn *
1463 __nf_conntrack_alloc(struct net *net,
1464 const struct nf_conntrack_zone *zone,
1465 const struct nf_conntrack_tuple *orig,
1466 const struct nf_conntrack_tuple *repl,
1467 gfp_t gfp, u32 hash)
1469 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
1470 unsigned int ct_count;
1473 /* We don't want any race condition at early drop stage */
1474 ct_count = atomic_inc_return(&cnet->count);
1476 if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1477 if (!early_drop(net, hash)) {
1478 if (!conntrack_gc_work.early_drop)
1479 conntrack_gc_work.early_drop = true;
1480 atomic_dec(&cnet->count);
1481 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1482 return ERR_PTR(-ENOMEM);
1487 * Do not use kmem_cache_zalloc(), as this cache uses
1488 * SLAB_TYPESAFE_BY_RCU.
1490 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1494 spin_lock_init(&ct->lock);
1495 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1496 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1497 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1498 /* save hash for reusing when confirming */
1499 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1502 write_pnet(&ct->ct_net, net);
1503 memset(&ct->__nfct_init_offset, 0,
1504 offsetof(struct nf_conn, proto) -
1505 offsetof(struct nf_conn, __nfct_init_offset));
1507 nf_ct_zone_add(ct, zone);
1509 /* Because we use RCU lookups, we set ct_general.use to zero before
1510 * this is inserted in any list.
1512 atomic_set(&ct->ct_general.use, 0);
1515 atomic_dec(&cnet->count);
1516 return ERR_PTR(-ENOMEM);
1519 struct nf_conn *nf_conntrack_alloc(struct net *net,
1520 const struct nf_conntrack_zone *zone,
1521 const struct nf_conntrack_tuple *orig,
1522 const struct nf_conntrack_tuple *repl,
1525 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1527 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1529 void nf_conntrack_free(struct nf_conn *ct)
1531 struct net *net = nf_ct_net(ct);
1532 struct nf_conntrack_net *cnet;
1534 /* A freed object has refcnt == 0, that's
1535 * the golden rule for SLAB_TYPESAFE_BY_RCU
1537 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1539 nf_ct_ext_destroy(ct);
1540 kmem_cache_free(nf_conntrack_cachep, ct);
1541 cnet = nf_ct_pernet(net);
1543 smp_mb__before_atomic();
1544 atomic_dec(&cnet->count);
1546 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1549 /* Allocate a new conntrack: we return -ENOMEM if classification
1550 failed due to stress. Otherwise it really is unclassifiable. */
1551 static noinline struct nf_conntrack_tuple_hash *
1552 init_conntrack(struct net *net, struct nf_conn *tmpl,
1553 const struct nf_conntrack_tuple *tuple,
1554 struct sk_buff *skb,
1555 unsigned int dataoff, u32 hash)
1558 struct nf_conn_help *help;
1559 struct nf_conntrack_tuple repl_tuple;
1560 struct nf_conntrack_ecache *ecache;
1561 struct nf_conntrack_expect *exp = NULL;
1562 const struct nf_conntrack_zone *zone;
1563 struct nf_conn_timeout *timeout_ext;
1564 struct nf_conntrack_zone tmp;
1565 struct nf_conntrack_net *cnet;
1567 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1568 pr_debug("Can't invert tuple.\n");
1572 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1573 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1576 return (struct nf_conntrack_tuple_hash *)ct;
1578 if (!nf_ct_add_synproxy(ct, tmpl)) {
1579 nf_conntrack_free(ct);
1580 return ERR_PTR(-ENOMEM);
1583 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1586 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1589 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1590 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1591 nf_ct_labels_ext_add(ct);
1593 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1594 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1595 ecache ? ecache->expmask : 0,
1599 cnet = nf_ct_pernet(net);
1600 if (cnet->expect_count) {
1601 spin_lock(&nf_conntrack_expect_lock);
1602 exp = nf_ct_find_expectation(net, zone, tuple);
1604 pr_debug("expectation arrives ct=%p exp=%p\n",
1606 /* Welcome, Mr. Bond. We've been expecting you... */
1607 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1608 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1609 ct->master = exp->master;
1611 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1613 rcu_assign_pointer(help->helper, exp->helper);
1616 #ifdef CONFIG_NF_CONNTRACK_MARK
1617 ct->mark = exp->master->mark;
1619 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1620 ct->secmark = exp->master->secmark;
1622 NF_CT_STAT_INC(net, expect_new);
1624 spin_unlock(&nf_conntrack_expect_lock);
1627 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1629 /* Now it is inserted into the unconfirmed list, bump refcount */
1630 nf_conntrack_get(&ct->ct_general);
1631 nf_ct_add_to_unconfirmed_list(ct);
1637 exp->expectfn(ct, exp);
1638 nf_ct_expect_put(exp);
1641 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1644 /* On success, returns 0, sets skb->_nfct | ctinfo */
1646 resolve_normal_ct(struct nf_conn *tmpl,
1647 struct sk_buff *skb,
1648 unsigned int dataoff,
1650 const struct nf_hook_state *state)
1652 const struct nf_conntrack_zone *zone;
1653 struct nf_conntrack_tuple tuple;
1654 struct nf_conntrack_tuple_hash *h;
1655 enum ip_conntrack_info ctinfo;
1656 struct nf_conntrack_zone tmp;
1660 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1661 dataoff, state->pf, protonum, state->net,
1663 pr_debug("Can't get tuple\n");
1667 /* look for tuple match */
1668 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1669 hash = hash_conntrack_raw(&tuple, state->net);
1670 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1672 h = init_conntrack(state->net, tmpl, &tuple,
1673 skb, dataoff, hash);
1679 ct = nf_ct_tuplehash_to_ctrack(h);
1681 /* It exists; we have (non-exclusive) reference. */
1682 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1683 ctinfo = IP_CT_ESTABLISHED_REPLY;
1685 /* Once we've had two way comms, always ESTABLISHED. */
1686 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1687 pr_debug("normal packet for %p\n", ct);
1688 ctinfo = IP_CT_ESTABLISHED;
1689 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1690 pr_debug("related packet for %p\n", ct);
1691 ctinfo = IP_CT_RELATED;
1693 pr_debug("new packet for %p\n", ct);
1697 nf_ct_set(skb, ct, ctinfo);
1702 * icmp packets need special treatment to handle error messages that are
1703 * related to a connection.
1705 * Callers need to check if skb has a conntrack assigned when this
1706 * helper returns; in such case skb belongs to an already known connection.
1708 static unsigned int __cold
1709 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1710 struct sk_buff *skb,
1711 unsigned int dataoff,
1713 const struct nf_hook_state *state)
1717 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1718 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1719 #if IS_ENABLED(CONFIG_IPV6)
1720 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1721 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1727 NF_CT_STAT_INC_ATOMIC(state->net, error);
1732 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1733 enum ip_conntrack_info ctinfo)
1735 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1738 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1740 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1744 /* Returns verdict for packet, or -1 for invalid. */
1745 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1746 struct sk_buff *skb,
1747 unsigned int dataoff,
1748 enum ip_conntrack_info ctinfo,
1749 const struct nf_hook_state *state)
1751 switch (nf_ct_protonum(ct)) {
1753 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1756 return nf_conntrack_udp_packet(ct, skb, dataoff,
1759 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1760 #if IS_ENABLED(CONFIG_IPV6)
1761 case IPPROTO_ICMPV6:
1762 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1764 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1765 case IPPROTO_UDPLITE:
1766 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1769 #ifdef CONFIG_NF_CT_PROTO_SCTP
1771 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1774 #ifdef CONFIG_NF_CT_PROTO_DCCP
1776 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1779 #ifdef CONFIG_NF_CT_PROTO_GRE
1781 return nf_conntrack_gre_packet(ct, skb, dataoff,
1786 return generic_packet(ct, skb, ctinfo);
1790 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1792 enum ip_conntrack_info ctinfo;
1793 struct nf_conn *ct, *tmpl;
1797 tmpl = nf_ct_get(skb, &ctinfo);
1798 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1799 /* Previously seen (loopback or untracked)? Ignore. */
1800 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1801 ctinfo == IP_CT_UNTRACKED)
1806 /* rcu_read_lock()ed by nf_hook_thresh */
1807 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1809 pr_debug("not prepared to track yet or error occurred\n");
1810 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1815 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1816 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1822 /* ICMP[v6] protocol trackers may assign one conntrack. */
1827 ret = resolve_normal_ct(tmpl, skb, dataoff,
1830 /* Too stressed to deal. */
1831 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1836 ct = nf_ct_get(skb, &ctinfo);
1838 /* Not valid part of a connection */
1839 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1844 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1846 /* Invalid: inverse of the return code tells
1847 * the netfilter core what to do */
1848 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1849 nf_conntrack_put(&ct->ct_general);
1851 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1852 if (ret == -NF_DROP)
1853 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1854 /* Special case: TCP tracker reports an attempt to reopen a
1855 * closed/aborted connection. We have to go back and create a
1858 if (ret == -NF_REPEAT)
1864 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1865 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1866 nf_conntrack_event_cache(IPCT_REPLY, ct);
1873 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1875 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1876 implicitly racy: see __nf_conntrack_confirm */
1877 void nf_conntrack_alter_reply(struct nf_conn *ct,
1878 const struct nf_conntrack_tuple *newreply)
1880 struct nf_conn_help *help = nfct_help(ct);
1882 /* Should be unconfirmed, so not in hash table yet */
1883 WARN_ON(nf_ct_is_confirmed(ct));
1885 pr_debug("Altering reply tuple of %p to ", ct);
1886 nf_ct_dump_tuple(newreply);
1888 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1889 if (ct->master || (help && !hlist_empty(&help->expectations)))
1893 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1896 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1898 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1899 void __nf_ct_refresh_acct(struct nf_conn *ct,
1900 enum ip_conntrack_info ctinfo,
1901 const struct sk_buff *skb,
1905 /* Only update if this is not a fixed timeout */
1906 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1909 /* If not in hash table, timer will not be active yet */
1910 if (nf_ct_is_confirmed(ct))
1911 extra_jiffies += nfct_time_stamp;
1913 if (READ_ONCE(ct->timeout) != extra_jiffies)
1914 WRITE_ONCE(ct->timeout, extra_jiffies);
1917 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1919 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1921 bool nf_ct_kill_acct(struct nf_conn *ct,
1922 enum ip_conntrack_info ctinfo,
1923 const struct sk_buff *skb)
1925 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1927 return nf_ct_delete(ct, 0, 0);
1929 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1931 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1933 #include <linux/netfilter/nfnetlink.h>
1934 #include <linux/netfilter/nfnetlink_conntrack.h>
1935 #include <linux/mutex.h>
1937 /* Generic function for tcp/udp/sctp/dccp and alike. */
1938 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1939 const struct nf_conntrack_tuple *tuple)
1941 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1942 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1943 goto nla_put_failure;
1949 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1951 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1952 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1953 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1955 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1957 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1958 struct nf_conntrack_tuple *t,
1961 if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
1962 if (!tb[CTA_PROTO_SRC_PORT])
1965 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1968 if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
1969 if (!tb[CTA_PROTO_DST_PORT])
1972 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1977 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1979 unsigned int nf_ct_port_nlattr_tuple_size(void)
1981 static unsigned int size __read_mostly;
1984 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1988 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1991 /* Used by ipt_REJECT and ip6t_REJECT. */
1992 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1995 enum ip_conntrack_info ctinfo;
1997 /* This ICMP is in reverse direction to the packet which caused it */
1998 ct = nf_ct_get(skb, &ctinfo);
1999 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2000 ctinfo = IP_CT_RELATED_REPLY;
2002 ctinfo = IP_CT_RELATED;
2004 /* Attach to new skbuff, and increment count */
2005 nf_ct_set(nskb, ct, ctinfo);
2006 nf_conntrack_get(skb_nfct(nskb));
2009 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2011 enum ip_conntrack_info ctinfo)
2013 struct nf_conntrack_tuple_hash *h;
2014 struct nf_conntrack_tuple tuple;
2015 struct nf_nat_hook *nat_hook;
2016 unsigned int status;
2021 l3num = nf_ct_l3num(ct);
2023 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2027 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2028 l4num, net, &tuple))
2031 if (ct->status & IPS_SRC_NAT) {
2032 memcpy(tuple.src.u3.all,
2033 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2034 sizeof(tuple.src.u3.all));
2036 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2039 if (ct->status & IPS_DST_NAT) {
2040 memcpy(tuple.dst.u3.all,
2041 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2042 sizeof(tuple.dst.u3.all));
2044 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2047 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2051 /* Store status bits of the conntrack that is clashing to re-do NAT
2052 * mangling according to what it has been done already to this packet.
2054 status = ct->status;
2057 ct = nf_ct_tuplehash_to_ctrack(h);
2058 nf_ct_set(skb, ct, ctinfo);
2060 nat_hook = rcu_dereference(nf_nat_hook);
2064 if (status & IPS_SRC_NAT &&
2065 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2066 IP_CT_DIR_ORIGINAL) == NF_DROP)
2069 if (status & IPS_DST_NAT &&
2070 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2071 IP_CT_DIR_ORIGINAL) == NF_DROP)
2077 /* This packet is coming from userspace via nf_queue, complete the packet
2078 * processing after the helper invocation in nf_confirm().
2080 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2081 enum ip_conntrack_info ctinfo)
2083 const struct nf_conntrack_helper *helper;
2084 const struct nf_conn_help *help;
2087 help = nfct_help(ct);
2091 helper = rcu_dereference(help->helper);
2092 if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2095 switch (nf_ct_l3num(ct)) {
2097 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2099 #if IS_ENABLED(CONFIG_IPV6)
2100 case NFPROTO_IPV6: {
2104 pnum = ipv6_hdr(skb)->nexthdr;
2105 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2107 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2116 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2117 !nf_is_loopback_packet(skb)) {
2118 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2119 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2124 /* We've seen it coming out the other side: confirm it */
2125 return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2128 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2130 enum ip_conntrack_info ctinfo;
2134 ct = nf_ct_get(skb, &ctinfo);
2138 if (!nf_ct_is_confirmed(ct)) {
2139 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2143 ct = nf_ct_get(skb, &ctinfo);
2146 return nf_confirm_cthelper(skb, ct, ctinfo);
2149 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2150 const struct sk_buff *skb)
2152 const struct nf_conntrack_tuple *src_tuple;
2153 const struct nf_conntrack_tuple_hash *hash;
2154 struct nf_conntrack_tuple srctuple;
2155 enum ip_conntrack_info ctinfo;
2158 ct = nf_ct_get(skb, &ctinfo);
2160 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2161 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2165 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2166 NFPROTO_IPV4, dev_net(skb->dev),
2170 hash = nf_conntrack_find_get(dev_net(skb->dev),
2176 ct = nf_ct_tuplehash_to_ctrack(hash);
2177 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2178 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2184 /* Bring out ya dead! */
2185 static struct nf_conn *
2186 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2187 void *data, unsigned int *bucket)
2189 struct nf_conntrack_tuple_hash *h;
2191 struct hlist_nulls_node *n;
2194 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2195 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2197 nf_conntrack_lock(lockp);
2198 if (*bucket < nf_conntrack_htable_size) {
2199 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
2200 if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2202 /* All nf_conn objects are added to hash table twice, one
2203 * for original direction tuple, once for the reply tuple.
2205 * Exception: In the IPS_NAT_CLASH case, only the reply
2206 * tuple is added (the original tuple already existed for
2207 * a different object).
2209 * We only need to call the iterator once for each
2210 * conntrack, so we just use the 'reply' direction
2211 * tuple while iterating.
2213 ct = nf_ct_tuplehash_to_ctrack(h);
2225 atomic_inc(&ct->ct_general.use);
2231 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2232 void *data, u32 portid, int report)
2234 unsigned int bucket = 0, sequence;
2240 sequence = read_seqcount_begin(&nf_conntrack_generation);
2242 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2243 /* Time to push up daises... */
2245 nf_ct_delete(ct, portid, report);
2250 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2257 int (*iter)(struct nf_conn *i, void *data);
2262 static int iter_net_only(struct nf_conn *i, void *data)
2264 struct iter_data *d = data;
2266 if (!net_eq(d->net, nf_ct_net(i)))
2269 return d->iter(i, d->data);
2273 __nf_ct_unconfirmed_destroy(struct net *net)
2277 for_each_possible_cpu(cpu) {
2278 struct nf_conntrack_tuple_hash *h;
2279 struct hlist_nulls_node *n;
2280 struct ct_pcpu *pcpu;
2282 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2284 spin_lock_bh(&pcpu->lock);
2285 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2288 ct = nf_ct_tuplehash_to_ctrack(h);
2290 /* we cannot call iter() on unconfirmed list, the
2291 * owning cpu can reallocate ct->ext at any time.
2293 set_bit(IPS_DYING_BIT, &ct->status);
2295 spin_unlock_bh(&pcpu->lock);
2300 void nf_ct_unconfirmed_destroy(struct net *net)
2302 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2306 if (atomic_read(&cnet->count) > 0) {
2307 __nf_ct_unconfirmed_destroy(net);
2308 nf_queue_nf_hook_drop(net);
2312 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2314 void nf_ct_iterate_cleanup_net(struct net *net,
2315 int (*iter)(struct nf_conn *i, void *data),
2316 void *data, u32 portid, int report)
2318 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2323 if (atomic_read(&cnet->count) == 0)
2330 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2332 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2335 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2336 * @iter: callback to invoke for each conntrack
2337 * @data: data to pass to @iter
2339 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2340 * unconfirmed list as dying (so they will not be inserted into
2343 * Can only be called in module exit path.
2346 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2350 down_read(&net_rwsem);
2352 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2354 if (atomic_read(&cnet->count) == 0)
2356 __nf_ct_unconfirmed_destroy(net);
2357 nf_queue_nf_hook_drop(net);
2359 up_read(&net_rwsem);
2361 /* Need to wait for netns cleanup worker to finish, if its
2362 * running -- it might have deleted a net namespace from
2363 * the global list, so our __nf_ct_unconfirmed_destroy() might
2364 * not have affected all namespaces.
2368 /* a conntrack could have been unlinked from unconfirmed list
2369 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2370 * This makes sure its inserted into conntrack table.
2374 nf_ct_iterate_cleanup(iter, data, 0, 0);
2376 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2378 static int kill_all(struct nf_conn *i, void *data)
2380 return net_eq(nf_ct_net(i), data);
2383 void nf_conntrack_cleanup_start(void)
2385 conntrack_gc_work.exiting = true;
2386 RCU_INIT_POINTER(ip_ct_attach, NULL);
2389 void nf_conntrack_cleanup_end(void)
2391 RCU_INIT_POINTER(nf_ct_hook, NULL);
2392 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2393 kvfree(nf_conntrack_hash);
2395 nf_conntrack_proto_fini();
2396 nf_conntrack_seqadj_fini();
2397 nf_conntrack_labels_fini();
2398 nf_conntrack_helper_fini();
2399 nf_conntrack_timeout_fini();
2400 nf_conntrack_ecache_fini();
2401 nf_conntrack_tstamp_fini();
2402 nf_conntrack_acct_fini();
2403 nf_conntrack_expect_fini();
2405 kmem_cache_destroy(nf_conntrack_cachep);
2409 * Mishearing the voices in his head, our hero wonders how he's
2410 * supposed to kill the mall.
2412 void nf_conntrack_cleanup_net(struct net *net)
2416 list_add(&net->exit_list, &single);
2417 nf_conntrack_cleanup_net_list(&single);
2420 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2426 * This makes sure all current packets have passed through
2427 * netfilter framework. Roll on, two-stage module
2433 list_for_each_entry(net, net_exit_list, exit_list) {
2434 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2436 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2437 if (atomic_read(&cnet->count) != 0)
2442 goto i_see_dead_people;
2445 list_for_each_entry(net, net_exit_list, exit_list) {
2446 nf_conntrack_ecache_pernet_fini(net);
2447 nf_conntrack_expect_pernet_fini(net);
2448 free_percpu(net->ct.stat);
2449 free_percpu(net->ct.pcpu_lists);
2453 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2455 struct hlist_nulls_head *hash;
2456 unsigned int nr_slots, i;
2458 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2461 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2462 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2464 hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2467 for (i = 0; i < nr_slots; i++)
2468 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2472 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2474 int nf_conntrack_hash_resize(unsigned int hashsize)
2477 unsigned int old_size;
2478 struct hlist_nulls_head *hash, *old_hash;
2479 struct nf_conntrack_tuple_hash *h;
2485 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2489 old_size = nf_conntrack_htable_size;
2490 if (old_size == hashsize) {
2496 nf_conntrack_all_lock();
2497 write_seqcount_begin(&nf_conntrack_generation);
2499 /* Lookups in the old hash might happen in parallel, which means we
2500 * might get false negatives during connection lookup. New connections
2501 * created because of a false negative won't make it into the hash
2502 * though since that required taking the locks.
2505 for (i = 0; i < nf_conntrack_htable_size; i++) {
2506 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2507 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2508 struct nf_conntrack_tuple_hash, hnnode);
2509 ct = nf_ct_tuplehash_to_ctrack(h);
2510 hlist_nulls_del_rcu(&h->hnnode);
2511 bucket = __hash_conntrack(nf_ct_net(ct),
2512 &h->tuple, hashsize);
2513 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2516 old_size = nf_conntrack_htable_size;
2517 old_hash = nf_conntrack_hash;
2519 nf_conntrack_hash = hash;
2520 nf_conntrack_htable_size = hashsize;
2522 write_seqcount_end(&nf_conntrack_generation);
2523 nf_conntrack_all_unlock();
2531 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2533 unsigned int hashsize;
2536 if (current->nsproxy->net_ns != &init_net)
2539 /* On boot, we can set this without any fancy locking. */
2540 if (!nf_conntrack_hash)
2541 return param_set_uint(val, kp);
2543 rc = kstrtouint(val, 0, &hashsize);
2547 return nf_conntrack_hash_resize(hashsize);
2550 static __always_inline unsigned int total_extension_size(void)
2552 /* remember to add new extensions below */
2553 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2555 return sizeof(struct nf_ct_ext) +
2556 sizeof(struct nf_conn_help)
2557 #if IS_ENABLED(CONFIG_NF_NAT)
2558 + sizeof(struct nf_conn_nat)
2560 + sizeof(struct nf_conn_seqadj)
2561 + sizeof(struct nf_conn_acct)
2562 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2563 + sizeof(struct nf_conntrack_ecache)
2565 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2566 + sizeof(struct nf_conn_tstamp)
2568 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2569 + sizeof(struct nf_conn_timeout)
2571 #ifdef CONFIG_NF_CONNTRACK_LABELS
2572 + sizeof(struct nf_conn_labels)
2574 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2575 + sizeof(struct nf_conn_synproxy)
2580 int nf_conntrack_init_start(void)
2582 unsigned long nr_pages = totalram_pages();
2587 /* struct nf_ct_ext uses u8 to store offsets/size */
2588 BUILD_BUG_ON(total_extension_size() > 255u);
2590 seqcount_spinlock_init(&nf_conntrack_generation,
2591 &nf_conntrack_locks_all_lock);
2593 for (i = 0; i < CONNTRACK_LOCKS; i++)
2594 spin_lock_init(&nf_conntrack_locks[i]);
2596 if (!nf_conntrack_htable_size) {
2597 /* Idea from tcp.c: use 1/16384 of memory.
2598 * On i386: 32MB machine has 512 buckets.
2599 * >= 1GB machines have 16384 buckets.
2600 * >= 4GB machines have 65536 buckets.
2602 nf_conntrack_htable_size
2603 = (((nr_pages << PAGE_SHIFT) / 16384)
2604 / sizeof(struct hlist_head));
2605 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2606 nf_conntrack_htable_size = 65536;
2607 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2608 nf_conntrack_htable_size = 16384;
2609 if (nf_conntrack_htable_size < 32)
2610 nf_conntrack_htable_size = 32;
2612 /* Use a max. factor of four by default to get the same max as
2613 * with the old struct list_heads. When a table size is given
2614 * we use the old value of 8 to avoid reducing the max.
2619 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2620 if (!nf_conntrack_hash)
2623 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2625 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2626 sizeof(struct nf_conn),
2628 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2629 if (!nf_conntrack_cachep)
2632 ret = nf_conntrack_expect_init();
2636 ret = nf_conntrack_acct_init();
2640 ret = nf_conntrack_tstamp_init();
2644 ret = nf_conntrack_ecache_init();
2648 ret = nf_conntrack_timeout_init();
2652 ret = nf_conntrack_helper_init();
2656 ret = nf_conntrack_labels_init();
2660 ret = nf_conntrack_seqadj_init();
2664 ret = nf_conntrack_proto_init();
2668 conntrack_gc_work_init(&conntrack_gc_work);
2669 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2674 nf_conntrack_seqadj_fini();
2676 nf_conntrack_labels_fini();
2678 nf_conntrack_helper_fini();
2680 nf_conntrack_timeout_fini();
2682 nf_conntrack_ecache_fini();
2684 nf_conntrack_tstamp_fini();
2686 nf_conntrack_acct_fini();
2688 nf_conntrack_expect_fini();
2690 kmem_cache_destroy(nf_conntrack_cachep);
2692 kvfree(nf_conntrack_hash);
2696 static struct nf_ct_hook nf_conntrack_hook = {
2697 .update = nf_conntrack_update,
2698 .destroy = destroy_conntrack,
2699 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2702 void nf_conntrack_init_end(void)
2704 /* For use by REJECT target */
2705 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2706 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2710 * We need to use special "null" values, not used in hash table
2712 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2713 #define DYING_NULLS_VAL ((1<<30)+1)
2715 int nf_conntrack_init_net(struct net *net)
2717 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2721 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2722 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2723 atomic_set(&cnet->count, 0);
2725 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2726 if (!net->ct.pcpu_lists)
2729 for_each_possible_cpu(cpu) {
2730 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2732 spin_lock_init(&pcpu->lock);
2733 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2734 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2737 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2739 goto err_pcpu_lists;
2741 ret = nf_conntrack_expect_pernet_init(net);
2745 nf_conntrack_acct_pernet_init(net);
2746 nf_conntrack_tstamp_pernet_init(net);
2747 nf_conntrack_ecache_pernet_init(net);
2748 nf_conntrack_helper_pernet_init(net);
2749 nf_conntrack_proto_pernet_init(net);
2754 free_percpu(net->ct.stat);
2756 free_percpu(net->ct.pcpu_lists);